diff --git a/assets/dashboard/js/app.js b/assets/dashboard/js/app.js index d15a63e..68e33ce 100644 --- a/assets/dashboard/js/app.js +++ b/assets/dashboard/js/app.js @@ -1,20 +1,14 @@ -window.Web3 = require('web3'); -window.privateKeyToAddress = require('ethereum-private-key-to-address'); -window.Buf = require('buffer').Buffer; -var Common = require('ethereumjs-common') - -/* global location */ 'use strict' +const Web3 = require('web3'); +const privateKeyToAddress = require('ethereum-private-key-to-address'); +const Buf = require('buffer').Buffer; +const Common = require('ethereumjs-common'); const fetch = require("node-fetch"); -const IPFS = require('ipfs') -const { - Buffer -} = IPFS const fs = require('fs'); -const Protector = require('libp2p-pnet') const fileReaderPullStream = require('pull-file-reader') const request = require('request'); + // Node const $ethomessage = document.querySelector('.etho-message') const $nodeId = document.querySelector('.node-id') @@ -35,8 +29,6 @@ const $allDisabledElements = document.querySelectorAll('.disabled') let MainFileArray = []; const FILES = [] -const workspace = location.hash -var ChannelStringArray = new Array(); var usedStorageArray = new Array(); var availableStorageArray = new Array(); var nodeCountArray = new Array(); @@ -44,92 +36,675 @@ var PeersForChannel = new Array(); let uploadCount = 0; let fileSize = 0 process.env.LIBP2P_FORCE_PNET = 1 -let node -let info let addr let messageFlag = 0; let messageString = ""; let healthMessage = ""; let averageAvailableStorageTotal = 0; -const swarmKey = "/key/swarm/psk/1.0.0/\n/base16/\n38307a74b2176d0054ffa2864e31ee22d0fc6c3266dd856f6d41bddf14e2ad63"; -var swarmKeyBuffer = new Buffer(swarmKey); -/* =========================================================================== - Start the IPFS node - =========================================================================== */ -function start() { - if (!node) { - const options = { - libp2p: { - modules: { - connProtector: new Protector(swarmKeyBuffer) - }, - config: { - dht: { - enabled: false - } - } - }, - config: { - Bootstrap: [ - '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', - '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst', - '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu', - '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ', - '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw', - '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', - '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX', - '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu', - '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', - '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', - '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ' - ], - Addresses: { - Swarm: [ - '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', - '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst', - '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu', - '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ', - '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw', - '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', - '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX', - '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu', - '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', - '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', - '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ' - ] - } + +/*SET CONTRACTS UP HERE*/ +var GlobalChannelString = "ethoFSPinningChannel_alpha11"; +var GlobalControllerContractAddress = "0xc38B47169950D8A28bC77a6Fa7467464f25ADAFc"; +var GlobalControllerABI = JSON.parse('[ { "constant": true, "inputs": [], "name": "last_completed_migration", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [ { "name": "completed", "type": "uint256" } ], "name": "setCompleted", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "new_address", "type": "address" } ], "name": "upgrade", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinToAdd", "type": "string" }, { "name": "pinSize", "type": "uint32" } ], "name": "PinAdd", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pin", "type": "string" } ], "name": "PinRemove", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [], "name": "deleteContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "hostingCost", "type": "uint256" } ], "name": "SetHostingCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinStorageAddress", "type": "address" } ], "name": "SetPinStorageAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSDashboardAddress", "type": "address" } ], "name": "SetEthoFSDashboardAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSHostingContractsAddress", "type": "address" } ], "name": "SetEthoFSHostingContractsAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountName", "type": "string" } ], "name": "AddNewUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "RemoveUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "pinSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddNewContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "MainContentHash", "type": "string" } ], "name": "RemoveHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubHostingContracts", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool", "value": false } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "newOperator", "type": "address" } ], "name": "changeOperator", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "newContractAddress", "type": "address" }, { "name": "UserAddress", "type": "address" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" } ], "name": "AddHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" } ], "name": "RemoveHostingContract1", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubContractList", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "uint256" } ], "name": "SetHostingContractCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendHostingContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddHostingContract", "outputs": [ { "name": "value", "type": "address" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "CustomerAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" }, { "name": "AccountCollectionAddress", "type": "address" } ], "name": "RemoveHostingContract2", "outputs": [ { "name": "value", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountCollectionAddress", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]'); +/*END OF CONTRACT SETUP*/ +const $miningMessage = document.querySelector('.mining-message') + +/*START OF MISC GLOBAL VARIABLES*/ +var privateKeyLogin = false; +var GlobalPrivateKey; +var minimumContractCost = 10000000000000000; + +var GlobalUploadName = ""; +var GlobalUserAddress = ""; +var GlobalHostingCost = 1.0; +var GlobalHostingCostWei = GlobalHostingCost * 1000000000000000000; +var GlobalUploadSize = 0; +var GlobalHashArray = new Array(); +var GlobalSizeArray = new Array(); +var GlobalPathArray = new Array(); +var GlobalMainHashArray = new Array(); +var GlobalMainPathArray = new Array(); +var GlobalMainContentHash = ""; +var GlobalUploadHash = ""; +var GlobalUploadPath = ""; +var GlobalContractDuration = ""; +var GlobalHostingContractArray = new Array(); +var GlobalTotalContractCount = 0; +var GlobalHostingContractDetailArray = new Array(); +var GlobalExtensionDuration; +/*END OF MISC GLOBAL VARIABLES*/ + + +fetch('https://api.coinmarketcap.com/v2/ticker/3452/').then(response => { + return response.json(); +}).then(data => { + var ethoPriceUSD = data.data.quotes.USD.price; + document.getElementById("ethoprice").textContent = round(ethoPriceUSD, 4); +}).catch(err => {}); + +if (typeof web3 == 'undefined') { + var web3 = new Web3() + web3.setProvider(new Web3.providers.HttpProvider('https://rpc.ether1.org')) + $('#ethofsLoginModal').modal('show'); +} else { + ethofsLogin(""); +} + +function ethofsLogin(privateKey) { + $('#ethofsLoginModal').modal('hide'); + $('#ethofsRegistrationModal').modal('hide'); + //CREATE ETHER-1 CHAIN CONNECTION AND LOOK FOR EXISTING USER ACCOUNT + if (privateKey != "") { + GlobalPrivateKey = privateKey; + privateKeyLogin = true; + web3.eth.net.isListening() + .then(function() { + console.log('ethoFS is connected') + let account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey); + console.log(account); + web3.eth.accounts.wallet.add(account) + web3.eth.defaultAccount = account.address; + startEthofs() + }) + } else { + privateKeyLogin = false; + web3 = new Web3(web3.currentProvider); + web3.eth.getAccounts(function(err, accounts) { + if (err != null) { + console.error("An error occurred: " + err); + outputNoAddressContractTable(); + } else if (accounts.length == 0) { + $('#ethofsLoginModal').modal('show'); + console.log("User is not logged in"); + document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension"; + document.getElementById("accountaddress").textContent = "Address Not Found"; + outputNoAddressContractTable(); + } else { + console.log("User is logged in"); + web3.eth.defaultAccount = accounts[0]; + startEthofs(); } - } - node = new IPFS(options) - node.once('start', () => { - node.id() - .then((id) => { - info = id - subscribeToHealthChannel() - updateView('ready', node) - onSuccess('Node is ready.') - setInterval(refreshPeerList, 10000) - setInterval(sendFileList, 10000) - }) - .catch((error) => onError(error)) - }) + }); } } -function SwarmPeers() { - node.swarm.peers(function(err, peerInfos) { - if (err) { - throw err +function startEthofs() { + console.log("Starting ethoFS"); + GlobalUserAddress = web3.eth.defaultAccount; + var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); + ethoFSAccounts.methods.CheckAccountExistence(GlobalUserAddress).call(function(error, result) { + if (!error) { + if (result) { + document.getElementById("accountaddress").textContent = web3.eth.defaultAccount; + ethoFSAccounts.methods.GetUserAccountName(GlobalUserAddress).call(function(error, result) { + if (!error) { + if (result) { + getBlockHeight(web3); + getBalance(web3); + document.getElementById("welcome-name").textContent = "Welcome Back " + result; + updateContractTable(); + startApplication(); + } + } else { + console.log("Error getting user account name"); + } + }); + } else { + document.getElementById("welcome-name").textContent = "User Not Found"; + document.getElementById("accountaddress").textContent = "Address Not Found"; + console.log("User Not Found"); + $('#ethofsRegistrationModal').modal('show'); + } + } else { + document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension"; + document.getElementById("accountaddress").textContent = "Address Not Found"; + console.log("Blockchain Access Error"); } - console.log(peerInfos) - }) + }); } + +/*************************************************************************************************************/ +function AddNewUser(userName) { + console.log("Initiating New User Addition... " + userName); + var controller = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); + + if (privateKeyLogin == true) { + const tx = { + to: GlobalControllerContractAddress, + from: GlobalUserAddress, + gas: 4000000, + data: controller.methods.AddNewUserPublic(userName).encodeABI() + }; + var privateKey = '0x' + GlobalPrivateKey; + web3.eth.accounts.signTransaction(tx, privateKey) + .then(function(signedTransactionData) { + web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { + if (!error) { + if (result) { + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + ethofsLogin(GlobalPrivateKey); + }); + } else { + console.log("There was a problem adding new contract"); + } + } else { + console.error(error); + } + }); + }); + } else { + controller.methods.AddNewUserPublic(userName).send(function(error, result) { + if (!error) { + if (result) { + document.getElementById("wait").innerHTML = 'Waiting For Add User Confirmation.'; + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + ethofsLogin(""); + }); + } else { + console.log("There was a problem adding new user"); + $('#ethofsLoginModal').modal('show'); + } + } else { + console.error(error); + $('#ethofsLoginModal').modal('show'); + } + }); + } +} +/*************************************************************************************************************/ +function getBlockHeight(web3) { + console.log("Starting Block Height Detection.."); + web3.eth.getBlockNumber(function(err, data) { + document.getElementById("blocknumber").textContent = data; + console.log("ETHO Block Number: " + data); + }); +} +/*************************************************************************************************************/ +function getBalance(web3) { + console.log("Starting Balance Detection.."); + web3.eth.getBalance(web3.eth.defaultAccount, function(err, data) { + var balance = "ETHO Balance: " + Number(web3.utils.fromWei(data, "ether")).toFixed(2); + document.getElementById("ethobalance").textContent = balance; + console.log("ETHO Balance: " + data); + }); +} +/*************************************************************************************************************/ +//CALCULATE AMOUNT TO BE SENT +function calculateCost(contractSize, contractDuration, hostingCost) { + var cost = ((((contractSize / 1048576) * hostingCost) * (contractDuration / 46522))); + if (cost < minimumContractCost) { + cost = minimumContractCost; + } + return cost; +} +/*************************************************************************************************************/ +//CHECK FOR TX - BLOCK TO BE MINED +function waitForReceipt(hash, cb) { + web3.eth.getTransactionReceipt(hash, function(err, receipt) { + document.getElementById("mining-status-message").textContent = "In Progress"; + $miningMessage.innerText = "Waiting For Transaction Confirmation"; + web3.eth.getBlock('latest', function(e, res) { + if (!e) { + document.getElementById("block-height").textContent = res.number; + } + }); + if (err) { + error(err); + $miningMessage.innerText = "Error Conneting To Ether-1 Network"; + } + if (receipt !== null) { + $miningMessage.innerText = "Transaction Confirmed"; + document.getElementById("mining-status-message").textContent = "Complete"; + if (cb) { + cb(receipt); + } + } else { + setTimeout(function() { + waitForReceipt(hash, cb); + }, 10000); + } + }); +} +/*************************************************************************************************************/ +//CREATE ETHER-1 CHAIN CONNECTION AND REMOVE CONTRACT +function RemoveContract(hostingAddress, contentHash) { + var pinRemoving = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); + if (privateKeyLogin == true) { + const tx = { + to: GlobalControllerContractAddress, + from: GlobalUserAddress, + gas: 4000000, + data: pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).encodeABI() + }; + var privateKey = '0x' + GlobalPrivateKey; + console.log("Private Key: " + privateKey); + web3.eth.accounts.signTransaction(tx, privateKey) + .then(function(signedTransactionData) { + console.log("Signed TX Data: " + signedTransactionData.rawTransaction); + web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { + if (!error) { + if (result) { + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + updateContractTable(); + }); + } else { + console.log("There was a problem adding new contract"); + } + } else { + console.error(error); + } + }); + }); + } else { + const tx = { + to: GlobalControllerContractAddress, + from: GlobalUserAddress, + }; + pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).send(tx, function(error, result) { + if (!error) { + if (result) { + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + updateContractTable(); + }); + } else { + console.log("There was a problem removing contract"); + } + } else { + console.error(error); + } + }); + } +} + +function updateContractTable() { + /*************************************************************************************************************/ + //CREATE ETHER-1 CHAIN CONNECTION AND GET USER ACCOUNT & CONTRACTS + var ethoFSHostingContracts = new Array(); + var hostingContracts = ""; + var TotalContractCount = 0; + var blockHeight = 0; + web3.eth.getBlockNumber(function(error, result) { + if (!error) { + blockHeight = result; + } else + console.error(error); + }); + var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); + ethoFSAccounts.methods.GetUserAccountTotalContractCount(web3.eth.defaultAccount).call(function(error, result) { + TotalContractCount = result; + GlobalTotalContractCount = result; + const getContractData = async (ethoFSAccounts, account, TotalContractCount) => { + if (TotalContractCount == 0) { + outputNoAddressContractTableWithButton(); + } + for (var i = 0; i < TotalContractCount; i++) { + const promisify = (inner) => + new Promise((resolve, reject) => + inner((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }) + ); + var counter = i; + GlobalHostingContractArray[counter] = new Array(); + var ethoFSHostingContractAddress = promisify(cb => ethoFSAccounts.methods.GetHostingContractAddress(account, counter).call(cb)); + await Promise.all([getAdditionalContractData(await ethoFSHostingContractAddress, counter, ethoFSAccounts)]); + + async function getAdditionalContractData(ethoFSHostingContractAddress, counter, ethoFSAccounts) { + const promisify = (inner) => + new Promise((resolve, reject) => + inner((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }) + ); + var ethoFSHostingContractCost = counter; + var ethoFSHostingContractName = promisify(cb => ethoFSAccounts.methods.GetHostingContractName(ethoFSHostingContractAddress).call(cb)); + var ethoFSHostingContractMainHash = promisify(cb => ethoFSAccounts.methods.GetMainContentHash(ethoFSHostingContractAddress).call(cb)); + var ethoFSHostingContractHashString = promisify(cb => ethoFSAccounts.methods.GetContentHashString(ethoFSHostingContractAddress).call(cb)); + var ethoFSHostingContractPathString = promisify(cb => ethoFSAccounts.methods.GetContentPathString(ethoFSHostingContractAddress).call(cb)); + + var ethoFSHostingContractStorage = promisify(cb => ethoFSAccounts.methods.GetHostingContractStorageUsed(ethoFSHostingContractAddress).call(cb)); + var ethoFSHostingContractStartBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractDeployedBlockHeight(ethoFSHostingContractAddress).call(cb)); + var ethoFSHostingContractEndBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractExpirationBlockHeight(ethoFSHostingContractAddress).call(cb)); + + GlobalHostingContractArray[counter]['address'] = await ethoFSHostingContractAddress; + GlobalHostingContractArray[counter]['name'] = await ethoFSHostingContractName; + GlobalHostingContractArray[counter]['mainhash'] = await ethoFSHostingContractMainHash; + GlobalHostingContractArray[counter]['hashstring'] = await ethoFSHostingContractHashString; + GlobalHostingContractArray[counter]['pathstring'] = await ethoFSHostingContractPathString; + GlobalHostingContractArray[counter]['storage'] = await ethoFSHostingContractStorage; + GlobalHostingContractArray[counter]['startblock'] = await ethoFSHostingContractStartBlock; + GlobalHostingContractArray[counter]['endblock'] = await ethoFSHostingContractEndBlock; + + GlobalHostingContractArray[counter]['hash'] = new Array(); + GlobalHostingContractArray[counter]['path'] = new Array(); + + var ContractHashArray = new Array(); + var ContractPathArray = new Array(); + var splitHashArray = await Promise.all([splitString(await ethoFSHostingContractHashString, ":")]); + var splitPathArray = await Promise.all([splitString(await ethoFSHostingContractPathString, ":")]); + + function splitString(stringToSplit, splitDelimeter) { + return stringToSplit.split(splitDelimeter); + } + await Promise.all([loopSplitStrings(await splitHashArray[0], await splitPathArray[0], counter)]); + + function loopSplitStrings(splitHashArray, splitPathArray, counter) { + for (var j = 1; j < splitHashArray.length; j++) { + GlobalHostingContractArray[counter]['hash'][j] = splitHashArray[j]; + GlobalHostingContractArray[counter]['path'][j] = splitPathArray[j]; + } + } + + await Promise.all([addNewTableEntry(await ethoFSHostingContractAddress, await ethoFSHostingContractMainHash, await ethoFSHostingContractName, await ethoFSHostingContractAddress, await ethoFSHostingContractStorage, await ethoFSHostingContractStartBlock, await ethoFSHostingContractEndBlock, await ethoFSHostingContractCost, await counter, await blockHeight)]); + } + } + //END GET ADDITIONAL CONTACT DATA + }; + getContractData(ethoFSAccounts, web3.eth.defaultAccount, TotalContractCount); + + function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractMainHash, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractCost, counter, blockHeight) { + if (blockHeight > ethoFSHostingContractEndBlock) { + var ethoFSHostingContractStatus = "Expired"; + hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
'; + } else { + var ethoFSHostingContractStatus = "Active"; + hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
'; + } + GlobalHostingContractArray[counter]['status'] = ethoFSHostingContractStatus; + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; + } + }); +} +/*************************************************************************************************************/ +//UPDATE CONTRACT DURATION AND CONTRACT COST +function contractDurationChange(selectObj) { + var duration = document.getElementById('contract-duration').value; + GlobalContractDuration = duration; + var ContractCost = (((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522)); + document.getElementById("contract-cost").innerHTML = round(ContractCost, 2); + return false; +} +/*************************************************************************************************************/ +//MISC ROUNDING FUNCTION +function round(value, decimals) { + return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals); +} +/*************************************************************************************************************/ +function finishUploadModal() { + $('#uploadTrackerModal').modal('hide'); + stopApplication(); + resetUploadSystem(); + updateContractTable(); + return false; +} + +function resetUploadModal() { + stopApplication(); + resetUploadSystem(); + updateContractTable(); + return false; +} +/*************************************************************************************************************/ +//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT +function checkForUploadedContentAvailability(HostingContractName) { + document.getElementById("upload-check-button").style.visibility = "hidden"; + $('#uploadTrackerModal').modal('show'); + document.getElementById("upload-hash").innerHTML = HostingContractName; + return false; +} +/*************************************************************************************************************/ +/*************************************************************************************************************/ +function resetUploadSystem() { + GlobalMainHashArray = new Array(); + GlobalMainPathArray = new Array(); + GlobalHashArray = new Array(); + GlobalPathArray = new Array(); + GlobalUploadHash = ""; + GlobalUploadPath = ""; + GlobalUploadSize = 0; + var TableBody = document.getElementById("file-history-body"); + TableBody.innerHTML = 'There are no files awaiting upload'; + var duration = document.getElementById('contract-duration').value; + GlobalContractDuration = duration; + var ContractCost = ((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522); + document.getElementById("contract-cost").innerHTML = round(ContractCost, 2); + document.getElementById("upload-hash").innerHTML = ""; + document.getElementById("upload-size").innerHTML = 0; + return false; +} +/*************************************************************************************************************/ +/*************************************************************************************************************/ +//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT +function sortContractTable() { + var hostingContracts = ""; + var i; + var localContractArray = GlobalHostingContractArray; + var tableSortDirection = ""; + var sortSelection = document.getElementById('sort-contracts'); + var tableSorter = sortSelection.value; + var filterSelection = document.getElementById('filter-contracts'); + var tableFilterer = filterSelection.value; + + if (tableSorter == "Ascending") { + tableSortDirection = "asc"; + } else { + tableSortDirection = "desc"; + } + localContractArray = multiSort(localContractArray, { + startblock: tableSortDirection + }); + var filterCounter = 0; + for (var i = 0; i < GlobalTotalContractCount; i++) { + if ((localContractArray[i]['status'] != "Expired" && tableFilterer == "Active Contracts") || (localContractArray[i]['status'] != "Active" && tableFilterer == "Expired Contracts") || tableFilterer == "All Contracts") { + addNewTableEntry(localContractArray[i]['address'], localContractArray[i]['name'], localContractArray[i]['hash'], localContractArray[i]['storage'], localContractArray[i]['startblock'], localContractArray[i]['endblock'], localContractArray[i]['status'], localContractArray[i]['cost'], i); + filterCounter++; + } else { + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; + } + } + if (GlobalTotalContractCount == 0 || filterCounter == 0) { + hostingContracts = 'No Hosting Contracts Found
'; + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; + + } + + function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractStatus, ethoFSHostingContractCost, counter) { + if (ethoFSHostingContractStatus == "Active") { + hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
'; + } else { + hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
'; + } + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; + } + + function multiSort(array, sortObject = {}) { + const sortKeys = Object.keys(sortObject); + // Return array if no sort object is supplied. + if (!sortKeys.length) { + return array; + } + // Change the values of the sortObject keys to -1, 0, or 1. + for (let key in sortObject) { + sortObject[key] = sortObject[key] === 'desc' || sortObject[key] === -1 ? -1 : + (sortObject[key] === 'skip' || sortObject[key] === 0 ? 0 : 1); + } + const keySort = (a, b, direction) => { + direction = direction !== null ? direction : 1; + if (a === b) { // If the values are the same, do not switch positions. + return 0; + } + // If b > a, multiply by -1 to get the reverse direction. + return a > b ? direction : -1 * direction; + }; + return array.sort((a, b) => { + let sorted = 0; + let index = 0; + // Loop until sorted (-1 or 1) or until the sort keys have been processed. + while (sorted === 0 && index < sortKeys.length) { + const key = sortKeys[index]; + if (key) { + const direction = sortObject[key]; + sorted = keySort(a[key], b[key], direction); + index++; + } + } + return sorted; + }); + } +} +/*************************************************************************************************************/ +//SHOW MODAL WITH HOSTING CONTRACT DETAILS +function showHostingContractDetails(counter) { + resetContractExtensionChange(); + + GlobalHostingContractDetailArray = GlobalHostingContractArray[counter]; + $('#contractDetailModal').modal('show'); + document.getElementById("contract-detail-name").innerHTML = GlobalHostingContractDetailArray['name']; + var hashOutputString = ""; + var hostingContractEntry = ""; + for (var i = 1; GlobalHostingContractDetailArray['hash'].length > i; i++) { + addNewTableEntry(GlobalHostingContractDetailArray['hash'][i], GlobalHostingContractDetailArray['path'][i], i); + } + document.getElementById("contract-detail-startblock").innerHTML = GlobalHostingContractDetailArray['startblock']; + document.getElementById("contract-detail-endblock").innerHTML = GlobalHostingContractDetailArray['endblock']; + document.getElementById("contract-detail-status").innerHTML = GlobalHostingContractDetailArray['status']; + document.getElementById("contract-detail-size").innerHTML = (GlobalHostingContractDetailArray['storage'] / 1048576); + + function addNewTableEntry(ethoFSHostingContractHash, ethoFSHostingContractPath, count) { + var table = document.getElementById("contract-detail-table"); + var row = table.insertRow(count + 10); + var cell1 = row.insertCell(0); + //var cell2 = row.insertCell(1); + //cell1.innerHTML = ethoFSHostingContractPath; + cell1.innerHTML = '' + ethoFSHostingContractHash + ''; + } + +} + +function resetContractDetailTableRows() { + var x = document.getElementById("contract-detail-table").rows.length; + for (var y = (x - 1); y > 10; y--) { + document.getElementById("contract-detail-table").deleteRow(y); + } +} +/*************************************************************************************************************/ +//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT +function outputNoAddressContractTable() { + hostingContracts = 'No Hosting Contracts Found
'; + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; +} +//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT +function outputNoAddressContractTableWithButton() { + hostingContracts = 'No Hosting Contracts Found
'; + document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; +} +/*************************************************************************************************************/ +function resetContractExtensionChange() { + GlobalExtensionDuration = 0; + document.getElementById("contract-extension-cost").innerHTML = 0; + document.getElementById("extend-contract").selectedIndex = "0"; +} +/*************************************************************************************************************/ +//CONTRACT EXTENSION VALUE CHANGE +function contractExtensionChange(selectObj) { + var index = selectObj.selectedIndex; + var extensionDuration = selectObj.options[index].value; + GlobalExtensionDuration = extensionDuration; + document.getElementById("contract-extension-button").style.visibility = "visible"; + var extensionCost = ((GlobalHostingContractDetailArray['storage'] / 1048576) * GlobalHostingCost) * (extensionDuration / 46522); + document.getElementById("contract-extension-cost").innerHTML = round(extensionCost, 2); +} +/*************************************************************************************************************/ +//CONTRACT EXTENSION CONFIRM +function contractExtensionConfirmation() { + if (GlobalExtensionDuration > 0) { + var extensionDuration = GlobalExtensionDuration; + var ethoFSController = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); + + var extensionCost = calculateCost(GlobalHostingContractDetailArray['storage'], extensionDuration, GlobalHostingCostWei); + const transactionObject = { + from: GlobalUserAddress, + value: extensionCost + }; + if (privateKeyLogin == true) { + const tx = { + to: GlobalControllerContractAddress, + from: GlobalUserAddress, + value: extensionCost, + gas: 4000000, + data: ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).encodeABI() + }; + var privateKey = '0x' + GlobalPrivateKey; + console.log("Private Key: " + privateKey); + web3.eth.accounts.signTransaction(tx, privateKey) + .then(function(signedTransactionData) { + console.log("Signed TX Data: " + signedTransactionData.rawTransaction); + web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { + if (!error) { + if (result) { + $('#contractDetailModal').modal('hide'); + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + updateContractTable(); + }); + } else { + console.log("There was a problem adding new contract"); + } + } else { + console.error(error); + } + }); + }); + } else { + + ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).send(transactionObject, function(error, result) { + if (!error) { + if (result) { + $('#contractDetailModal').modal('hide'); + $('#minedBlockTrackerModal').modal('show'); + waitForReceipt(result, function(receipt) { + console.log("Transaction Has Been Mined: " + receipt); + $('#minedBlockTrackerModal').modal('hide'); + updateContractTable(); + }); + } + } else { + console.log(error); + } + }); + } + } +} +/*************************************************************************************************************/ + /* =========================================================================== Pubsub =========================================================================== */ const subscribeToHealthChannel = () => { - node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler) + window.node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler) .catch(() => onError('An error occurred when subscribing to the health check workspace.')) } const healthMessageHandler = (message) => { @@ -202,19 +777,16 @@ const receiveExitMsg = (msg) => console.log("Content Upload Successful") const exitMessageHandler = (message) => { const cancelMessageString = message.data.toString() } -window.CheckForUploadedContentVerification = function(){ - -} const subscribeToMessaging = () => { for(var i = 4; i < PeersForChannel.length; i++){ - node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler) + window.node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler) .catch(() => onError('An error occurred when subscribing to the workspace.')) } } const unsubscribeToMessaging = () => { for(var i = 4; i < PeersForChannel.length; i++){ - node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler) + window.node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler) .catch(() => onError('An error occurred when unsubscribing to the workspace.')) } } @@ -222,7 +794,7 @@ const publishImmediatePin = (hash) => { const data = Buffer.from(hash) for (var i = 0; i < PeersForChannel.length; i++) { var channel = PeersForChannel[i] + "ImmediatePinningChannel_alpha11"; - node.pubsub.publish(channel, data) + window.node.pubsub.publish(channel, data) .catch(() => onError('An error occurred when publishing the message.')) } } @@ -230,18 +802,15 @@ const publishImmediatePin = (hash) => { /* =========================================================================== Files handling =========================================================================== */ - -const isFileInList = (hash) => FILES.indexOf(hash) !== -1 - const sendFileList = () => FILES.forEach((hash) => publishHash(hash)) -const updateProgress = (bytesLoaded) => { +/*const updateProgress = (bytesLoaded) => { let percent = 100 - ((bytesLoaded / fileSize) * 100) if (percent <= 5) { document.getElementById("upload-confirm-button").style.visibility = "visible"; } $progressBar.style.transform = `translateX(${-percent}%)` -} +}*/ const resetProgress = () => { $progressBar.style.transform = 'translateX(-100%)' @@ -289,13 +858,16 @@ function resetFileTable() { const onDragEnter = (event) => $dragContainer.classList.add('dragging') const onDragLeave = () => $dragContainer.classList.remove('dragging') -window.startUploadProcess = function() { +function startUploadProcess() { + console.log("Starting Upload Process.."); $('#preparingUploadModal').modal('show'); var streamFinishCount = 0; for (var i = 0; i < MainFileArray.length; i++) { const streamFiles = (files) => { const stream = node.addReadableStream() stream.on('data', function(data) { + console.log("Data..."); + console.log(data); GlobalHashArray.push(`${data.hash}`); GlobalSizeArray.push(`${data.size}`); GlobalPathArray.push(`${data.path}`); @@ -306,7 +878,7 @@ window.startUploadProcess = function() { streamFinishCount++; GlobalMainHashArray.push(`${data.hash}`); GlobalMainPathArray.push(`${data.path}`); - if (streamFinishCount == MainFileArray.length) { + if(streamFinishCount == MainFileArray.length) { createMainHash(); } } @@ -385,7 +957,7 @@ window.startUploadProcess = function() { for (i = 0; i < GlobalMainHashArray.length; i++) { contentHashString += ":" + GlobalMainHashArray[i]; } - node.add(Buffer.from(contentHashString), (err, res) => { + window.node.add(Buffer.from(contentHashString), (err, res) => { if (err || !res) { return console.error('ipfs add error', err, res) } @@ -493,46 +1065,66 @@ function updateAnalyzeProgress(width) { } function onFileUpload(event) { + event.preventDefault() document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA"; document.getElementById("upload-confirm-button").style.visibility = "hidden"; MainFileArray.push([]); - let filesUploaded = event.target.files; - var streamCompareCount = filesUploaded.length; - for (let i = 0; filesUploaded.length > i; i++) { - handleFile(filesUploaded[i]); - } + let dirSelected = event.target.files; + let dirPath = dirSelected[0].path; + var streamCompareCount = 0; + var totalUploadItems = 0; + readDirectoryContents(dirPath); - function readFileContents(file) { - return new Promise((resolve) => { - const reader = new window.FileReader() - reader.onload = (event) => resolve(event.target.result) - reader.readAsArrayBuffer(file) - }) - } - - function handleFile(file) { - readFileContents(file).then((buffer) => { - var filePath = file.webkitRelativePath; - var filetowrite = { - path: filePath, - content: Buffer.from(buffer) - }; - MainFileArray[MainFileArray.length - 1].push(filetowrite); - GlobalUploadSize += Number(file.size); - fileSize += Number(file.size); - var totalUploadSizeMB = GlobalUploadSize / 1000000; - appendFile(filePath, file.name, file.size, null); - console.log("Path: " + filePath + " Size: " + file.size + " Total Size: " + GlobalUploadSize); - document.getElementById("upload-size").textContent = totalUploadSizeMB; - contractDurationChange(document.getElementById('contract-duration').value); - streamCompareCount--; - updateAnalyzeProgress(((filesUploaded.length - streamCompareCount) / filesUploaded.length)); - if (streamCompareCount == 0) { - document.getElementById("upload-hash").textContent = "READY FOR UPLOAD"; - document.getElementById("upload-confirm-button").style.visibility = "visible"; + function readDirectoryContents(directory) { + console.log("Directory Path: " + directory); + fs.readdir(directory, function(err, filesUploaded) { + if(!err) { + for (let i = 0; filesUploaded.length > i; i++) { + handleItem(filesUploaded[i], directory); + } + } else { + console.log("File Upload Error: " + err); } }); } + + function handleItem(filename, relativePath) { + var filepath = relativePath.concat('\\', filename); + fs.stat(filepath, function(err, stats) { + if(!err) { + if(stats.isDirectory()) { + readDirectoryContents(filepath) + } else { + streamCompareCount ++; + totalUploadItems ++; + console.log("File Path: " + filepath); + fs.readFile(filepath, function(err, file) { + var filetowrite = { + path: filepath, + content: file + }; + var filename = filepath; + MainFileArray[MainFileArray.length - 1].push(filetowrite); + GlobalUploadSize += Number(stats.size); + fileSize += Number(stats.size); + var totalUploadSizeMB = GlobalUploadSize / 1000000; + appendFile(filepath, filename, stats.size, null); + console.log("Path: " + filepath + " Size: " + stats.size + " Total Size: " + GlobalUploadSize); + document.getElementById("upload-size").textContent = totalUploadSizeMB; + contractDurationChange(document.getElementById('contract-duration').value); + streamCompareCount--; + updateAnalyzeProgress(((totalUploadItems - streamCompareCount) / totalUploadItems)); + if (streamCompareCount == 0) { + document.getElementById("upload-hash").textContent = "READY FOR UPLOAD"; + document.getElementById("upload-confirm-button").style.visibility = "visible"; + } + }); + } + } else { + console.log("File Stats Error: " + err); + } + }); + } } function onDrop(event) { @@ -626,7 +1218,7 @@ function connectToPeer(event) { return onError('No multiaddr was inserted.') } - node.swarm.connect(multiaddr) + window.node.swarm.connect(multiaddr) .then(() => { onSuccess(`Successfully connected to peer.`) $multiaddrInput.value = '' @@ -653,7 +1245,7 @@ function updatePeerProgress(width, peercount) { function refreshPeerList() { var updatedPeerCount = 0; - node.swarm.peers() + window.node.swarm.peers() .then((peers) => { const peersAsHtml = peers.reverse() .map((peer) => { @@ -712,10 +1304,10 @@ window.onerror = onError const states = { ready: () => { - const addressesHtml = info.addresses.map((address) => { + const addressesHtml = window.info.addresses.map((address) => { return `
  • ${address}
  • ` }).join('') - $nodeId.innerText = info.id + $nodeId.innerText = window.info.id $allDisabledButtons.forEach(b => { b.disabled = false }) @@ -738,21 +1330,22 @@ function updateView(state, ipfs) { /* =========================================================================== Boot the app =========================================================================== */ -window.startApplication = function() { +function startApplication() { // Setup event listeners $dragContainer.addEventListener('dragenter', onDragEnter) $dragContainer.addEventListener('dragover', onDragEnter) $dragContainer.addEventListener('drop', onDrop) $dragContainer.addEventListener('dragleave', onDragLeave) document.getElementById("fileUploadButton").addEventListener("change", onFileUpload) - start() + //start() + window.startNode() extendedStartApplication() } function extendedStartApplication() { $ethomessage.innerText = GlobalUserAddress; } -window.stopApplication = function() { +function stopApplication() { resetUploadProcess(); resetFileTable(); } diff --git a/assets/dashboard/js/bundle.js b/assets/dashboard/js/bundle.js index ec3b59f..2169965 100644 --- a/assets/dashboard/js/bundle.js +++ b/assets/dashboard/js/bundle.js @@ -1,65 +1,23 @@ (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 { - node.id() + console.log("Launching ethoFS Node..."); + window.node = new IPFS(options) + console.log("Waiting For ethoFS Node Launch Confirmation..."); + window.node.once('start', () => { + console.log("ethoFS Node Startup Confirmed..."); + window.node.id() .then((id) => { - info = id + + window.info = id + console.log("Getting ethoFS Node ID..."); subscribeToHealthChannel() - updateView('ready', node) + updateView('ready', window.node) onSuccess('Node is ready.') setInterval(refreshPeerList, 10000) setInterval(sendFileList, 10000) @@ -117,650 +80,11 @@ function start() { }) } } - -function SwarmPeers() { - node.swarm.peers(function(err, peerInfos) { - if (err) { - throw err - } - console.log(peerInfos) - }) -} -/* =========================================================================== - Pubsub - =========================================================================== */ - -const subscribeToHealthChannel = () => { - node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler) - .catch(() => onError('An error occurred when subscribing to the health check workspace.')) -} -const healthMessageHandler = (message) => { - healthMessage = message.data.toString(); - UpdateHealthCheckInfo(healthMessage); -} -function UpdateHealthCheckInfo(healthMessage) { - var mainMessage = healthMessage.split(";")[1]; - var splitMessage = mainMessage.split(","); - var usedStorageTotal = 0; - var availableStorageTotal = 0; - var activeHistory = 0; - var nodeCounter = 0; - splitMessage.forEach(function(nodeMessage, index) { - var nodeSplitMessage = nodeMessage.split(":"); - activeHistory = Number(nodeSplitMessage[5]); - if(activeHistory >= 5){ - nodeCounter++; - usedStorageTotal += Number(nodeSplitMessage[8]); - availableStorageTotal += Number(nodeSplitMessage[7]); - } - if(index == (splitMessage.length - 1)){ - updateStorageArrays(usedStorageTotal, availableStorageTotal, nodeCounter); - } - }); - function updateStorageArrays(usedStorageTotal, availableStorageTotal, nodecount){ - - if(availableStorageArray.length >= 50){ - if(availableStorageTotal > 0.75 * averageAvailableStorageTotal && availableStorageTotal < 1.25 * averageAvailableStorageTotal){ - availableStorageArray.push(availableStorageTotal); - availableStorageArray.shift(); - } - }else{ - availableStorageArray.push(availableStorageTotal); - } - if(nodeCountArray.length >= 50){ - nodeCountArray.push(nodecount); - nodeCountArray.shift(); - }else{ - nodeCountArray.push(nodecount); - } - calculateStorageAverages(usedStorageArray, availableStorageArray, nodeCountArray); - } - function calculateStorageAverages(usedStorageArray, availableStorageArray, nodeCountArray){ - - var sumAvailableStorage = 0; - availableStorageArray.forEach(function(value, index) { - sumAvailableStorage += value; - if(index == (availableStorageArray.length - 1)){ - averageAvailableStorageTotal = (sumAvailableStorage/availableStorageArray.length); - document.getElementById("nodestorage").textContent=(round(2+((averageAvailableStorageTotal)/1000000), 1)) + "TB"; - } - }); - var sumNodeCount = 0; - nodeCountArray.forEach(function(value, index) { - sumNodeCount += value; - if(index == (nodeCountArray.length - 1)){ - var averageNodeCount = (sumNodeCount/nodeCountArray.length) + 19; - document.getElementById("nodecount").textContent=(round(averageNodeCount, 0)); - } - }); - } -} - - -const messageHandler = (message) => { - messageString = message.data.toString(); -} -const receiveExitMsg = (msg) => console.log("Content Upload Successful") -const exitMessageHandler = (message) => { - const cancelMessageString = message.data.toString() -} -window.CheckForUploadedContentVerification = function(){ - -} - -const subscribeToMessaging = () => { - for(var i = 4; i < PeersForChannel.length; i++){ - node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler) - .catch(() => onError('An error occurred when subscribing to the workspace.')) - } -} -const unsubscribeToMessaging = () => { - for(var i = 4; i < PeersForChannel.length; i++){ - node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler) - .catch(() => onError('An error occurred when unsubscribing to the workspace.')) - } -} -const publishImmediatePin = (hash) => { - const data = Buffer.from(hash) - for (var i = 0; i < PeersForChannel.length; i++) { - var channel = PeersForChannel[i] + "ImmediatePinningChannel_alpha11"; - node.pubsub.publish(channel, data) - .catch(() => onError('An error occurred when publishing the message.')) - } -} - -/* =========================================================================== - Files handling - =========================================================================== */ - -const isFileInList = (hash) => FILES.indexOf(hash) !== -1 - -const sendFileList = () => FILES.forEach((hash) => publishHash(hash)) - -const updateProgress = (bytesLoaded) => { - let percent = 100 - ((bytesLoaded / fileSize) * 100) - if (percent <= 5) { - document.getElementById("upload-confirm-button").style.visibility = "visible"; - } - $progressBar.style.transform = `translateX(${-percent}%)` -} - -const resetProgress = () => { - $progressBar.style.transform = 'translateX(-100%)' -} - -function appendFile(name, hash, size, data) { - const file = new window.Blob([data], { - type: 'application/octet-binary' - }) - const url = window.URL.createObjectURL(file) - const row = document.createElement('tr') - - const nameCell = document.createElement('td') - nameCell.innerHTML = name - - const hashCell = document.createElement('td') - hashCell.innerHTML = hash - - const sizeCell = document.createElement('td') - sizeCell.innerText = size - - const downloadCell = document.createElement('td') - const link = document.createElement('a') - link.setAttribute('href', url) - link.setAttribute('download', name) - link.innerHTML = 'Download' - downloadCell.appendChild(link) - - row.appendChild(nameCell) - row.appendChild(hashCell) - row.appendChild(sizeCell) - row.appendChild(downloadCell) - - $fileHistory.insertBefore(row, $fileHistory.firstChild) -} - -function resetFileTable() { - while ($fileHistory.hasChildNodes()) { - $fileHistory.removeChild($fileHistory.firstChild); - } -} -/* Drag & Drop - =========================================================================== */ - -const onDragEnter = (event) => $dragContainer.classList.add('dragging') -const onDragLeave = () => $dragContainer.classList.remove('dragging') - -window.startUploadProcess = function() { - $('#preparingUploadModal').modal('show'); - var streamFinishCount = 0; - for (var i = 0; i < MainFileArray.length; i++) { - const streamFiles = (files) => { - const stream = node.addReadableStream() - stream.on('data', function(data) { - GlobalHashArray.push(`${data.hash}`); - GlobalSizeArray.push(`${data.size}`); - GlobalPathArray.push(`${data.path}`); - GlobalUploadHash = `${data.hash}`; - GlobalUploadPath = `${data.path}`; - var splitString = GlobalUploadPath.split("/") - if (splitString.length == 1 || splitString[0] == "") { - streamFinishCount++; - GlobalMainHashArray.push(`${data.hash}`); - GlobalMainPathArray.push(`${data.path}`); - if (streamFinishCount == MainFileArray.length) { - createMainHash(); - } - } - }); - files.forEach(file => stream.write(file)) - stream.end() - } - var filesForStream = MainFileArray[i]; - streamFiles(filesForStream); - } - - const streamFilesExternally = (filesArray, MainHashArray) => { - - var confirmationServers = ["https://ipfsapi.ethofs.com/ipfs/", "https://ipfsapi1.ethofs.com/ipfs/", "https://ipfsapi2.ethofs.com/ipfs/", "https://ipfsapi5.ethofs.com/ipfs/", "https://ipfsapi6.ethofs.com/ipfs/", "https://ipfsapi7.ethofs.com/ipfs/"]; - let hashVerificationArray = [...GlobalHashArray, ...GlobalMainHashArray]; - hashVerificationArray.push(GlobalMainContentHash); - var hashConfirmationCount = 0; - - - for (var i = 0; i < MainHashArray.length; i++) { - console.log("Sending Immediate Pin Request: " + MainHashArray[i]); - publishImmediatePin(MainHashArray[i]); - } - setTimeout(function() { - hashVerificationArray.forEach(function(hash) { - verifyDataUpload(hash); - }); - }, 5000); - - const verifyDataUpload = async hash => { - var confirmationServer = confirmationServers[Math.floor(Math.random() * confirmationServers.length)]; - var url = confirmationServer + hash; - try { - const response = await fetch(url); - console.log("Data Confirmation Status: " + response.status + " Hash: " + hash); - if (response.status == 200) { - hashConfirmationCount++; - var confirmationPercentage = Math.ceil((hashConfirmationCount / hashVerificationArray.length) * 100); - updateUploadProgress(confirmationPercentage); - console.log("Data Upload Confirmation Received: " + hashConfirmationCount + "/" + hashVerificationArray.length); - $uploadMessage.innerText = "Upload Confirmation Received: " + hashConfirmationCount + "/" + hashVerificationArray.length; - if (confirmationPercentage >= 99) { - $uploadMessage.innerText = "Upload Complete"; - document.getElementById("upload-status-message").textContent = "Complete"; - finishUploadModal(); - } - } else { - setTimeout(function() { - verifyDataUpload(hash) - }, 2000); - } - } catch (error) { - console.log(error); - console.log("Data Confirmation Error: " + error.status); - setTimeout(function() { - verifyDataUpload(hash) - }, 2000); - } - }; - } - - function updateUploadProgress(width) { - var elem = document.getElementById("myBar"); - width = round(width, 2); - if (width >= 100) { - width = 100; - elem.style.width = width + '%'; - elem.innerHTML = width * 1 + '%'; - } - elem.style.width = width + '%'; - elem.innerHTML = width * 1 + '%'; - } - - function createMainHash() { - var contentHashString = GlobalChannelString; - for (i = 0; i < GlobalMainHashArray.length; i++) { - contentHashString += ":" + GlobalMainHashArray[i]; - } - node.add(Buffer.from(contentHashString), (err, res) => { - if (err || !res) { - return console.error('ipfs add error', err, res) - } - res.forEach((file) => { - if (file && file.hash) { - GlobalMainContentHash = file.hash; - AddNewPin(GlobalUploadHash, GlobalUploadSize, document.getElementById('newcontractname').value, GlobalContractDuration); - } - }); - }); - } - - /*****************************************************************************/ - function AddNewPin(pinToAdd, pinSize, HostingContractName, HostingContractDuration) { - var contentHashString = GlobalChannelString; - var contentPathString = GlobalChannelString; - for (i = 0; i < GlobalMainHashArray.length; i++) { - contentHashString += ":" + GlobalMainHashArray[i]; - contentPathString += ":" + GlobalMainPathArray[i]; - } - var MainHashArray = GlobalMainHashArray; - GlobalUploadName = HostingContractName; - var contractCost = calculateCost(pinSize, HostingContractDuration, GlobalHostingCostWei); - var pinAdding = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - const transactionObject = { - from: GlobalUserAddress, - value: contractCost - }; - $('#preparingUploadModal').modal('hide'); - console.log("Contract Address: " + GlobalControllerContractAddress + " Value: " + contractCost); - if (privateKeyLogin == true) { - const tx = { - to: GlobalControllerContractAddress, - from: GlobalUserAddress, - value: contractCost, - gas: 4000000, - data: pinAdding.methods.AddNewContract(GlobalMainContentHash, HostingContractName, HostingContractDuration, pinSize, pinSize, contentHashString, contentPathString).encodeABI() - }; - var privateKey = '0x' + GlobalPrivateKey; - console.log("Private Key: " + privateKey); - web3.eth.accounts.signTransaction(tx, privateKey) - .then(function(signedTransactionData) { - console.log("Signed TX Data: " + signedTransactionData.rawTransaction); - web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { - if (!error) { - if (result) { - console.log("Result: " + result); - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - $('#nodeModal').modal('hide'); - var filesForStream = MainFileArray; - streamFilesExternally(filesForStream, MainHashArray); - checkForUploadedContentAvailability(HostingContractName); - }); - } else { - console.log("There was a problem adding new contract"); - } - } else { - console.error(error); - } - }); - }); - } else { - pinAdding.methods.AddNewContract(GlobalMainContentHash, HostingContractName, HostingContractDuration, pinSize, pinSize, contentHashString, contentPathString).send(transactionObject, function(error, result) { - if (!error) { - if (result) { - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - $('#nodeModal').modal('hide'); - var filesForStream = MainFileArray; - streamFilesExternally(filesForStream, MainHashArray); - checkForUploadedContentAvailability(HostingContractName); - }); - } else { - console.log("There was a problem adding new contract"); - } - } else { - console.error(error); - } - }); - } - } - /*****************************************************************************/ -} - -function resetUploadProcess() { - MainFileArray = new Array(); - GlobalUploadSize = 0; -} - -function updateAnalyzeProgress(width) { - var elem = document.getElementById("myAnalyzeBar"); - width = round(width, 2); - if (width >= 100) { - width = 100; - elem.style.width = width + '%'; - elem.innerHTML = width * 1 + '%'; - } - elem.style.width = width + '%'; - elem.innerHTML = width * 1 + '%'; -} - -function onFileUpload(event) { - document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA"; - document.getElementById("upload-confirm-button").style.visibility = "hidden"; - MainFileArray.push([]); - let filesUploaded = event.target.files; - var streamCompareCount = filesUploaded.length; - for (let i = 0; filesUploaded.length > i; i++) { - handleFile(filesUploaded[i]); - } - - function readFileContents(file) { - return new Promise((resolve) => { - const reader = new window.FileReader() - reader.onload = (event) => resolve(event.target.result) - reader.readAsArrayBuffer(file) - }) - } - - function handleFile(file) { - readFileContents(file).then((buffer) => { - var filePath = file.webkitRelativePath; - var filetowrite = { - path: filePath, - content: Buffer.from(buffer) - }; - MainFileArray[MainFileArray.length - 1].push(filetowrite); - GlobalUploadSize += Number(file.size); - fileSize += Number(file.size); - var totalUploadSizeMB = GlobalUploadSize / 1000000; - appendFile(filePath, file.name, file.size, null); - console.log("Path: " + filePath + " Size: " + file.size + " Total Size: " + GlobalUploadSize); - document.getElementById("upload-size").textContent = totalUploadSizeMB; - contractDurationChange(document.getElementById('contract-duration').value); - streamCompareCount--; - updateAnalyzeProgress(((filesUploaded.length - streamCompareCount) / filesUploaded.length)); - if (streamCompareCount == 0) { - document.getElementById("upload-hash").textContent = "READY FOR UPLOAD"; - document.getElementById("upload-confirm-button").style.visibility = "visible"; - } - }); - } -} - -function onDrop(event) { - MainFileArray.push([]); - document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA"; - document.getElementById("upload-confirm-button").style.visibility = "hidden"; - fileSize = 0; - resetProgress(); - onDragLeave() - event.preventDefault() - if (GlobalUploadHash != "" && GlobalUploadPath != "") { - GlobalMainHashArray.push(GlobalUploadHash); - GlobalMainPathArray.push(GlobalUploadPath); - } - const dt = event.dataTransfer - const filesDropped = dt.files - const itemsDropped = dt.items - - function readFileContents(file) { - return new Promise((resolve) => { - const reader = new window.FileReader() - reader.onload = (event) => resolve(event.target.result) - reader.readAsArrayBuffer(file) - }) - } - var totalItemCount = 0; - var streamCompareCount = 0; - - function initialHandleItems(items) { - const files = []; - totalItemCount = items.length; - streamCompareCount = items.length; - for (var item of items) { - var awaitHandleEntry = handleEntry(item.webkitGetAsEntry()); - } - - function handleEntry(entry) { - if (entry.isFile) { - getFile(entry); - - function getFile(entry) { - entry.file(function(file) { - readFileContents(file) - .then((buffer) => { - var filePath = entry.fullPath; - var filetowrite = { - path: entry.fullPath, - content: Buffer.from(buffer) - }; - MainFileArray[MainFileArray.length - 1].push(filetowrite); - GlobalUploadSize += Number(file.size); - fileSize += Number(file.size); - var totalUploadSizeMB = GlobalUploadSize / 1000000; - appendFile(entry.fullPath, entry.name, file.size, null); - document.getElementById("upload-size").textContent = totalUploadSizeMB; - contractDurationChange(document.getElementById('contract-duration').value); - streamCompareCount--; - updateAnalyzeProgress(((totalItemCount - streamCompareCount) / totalItemCount)); - if (streamCompareCount == 0) { - document.getElementById("upload-hash").textContent = "READY FOR UPLOAD"; - document.getElementById("upload-confirm-button").style.visibility = "visible"; - } - }); - }); - } - - } else if (entry.isDirectory) { - let directoryReader = entry.createReader(); - directoryReader.readEntries(function(entries) { - streamCompareCount += entries.length - 1; - totalItemCount += entries.length - 1; - entries.forEach(function(newEntry) { - handleEntry(newEntry); - }); - }); - } - } - - } - initialHandleItems(event.dataTransfer.items); -} - -/* =========================================================================== - Peers handling - =========================================================================== */ - -function connectToPeer(event) { - const multiaddr = $multiaddrInput.value - - if (!multiaddr) { - return onError('No multiaddr was inserted.') - } - - node.swarm.connect(multiaddr) - .then(() => { - onSuccess(`Successfully connected to peer.`) - $multiaddrInput.value = '' - }) - .catch(() => onError('An error occurred when connecting to the peer.')) -} - -function updatePeerProgress(width, peercount) { - var backgroundcolor = ""; - var elem = document.getElementById("myPeerBar"); - width = round(width, 2); - if (width >= 100) { - width = 100; - } - if (width >= 80) { - backgroundcolor = '"#3CB371"'; - } else if (width >= 40 && width < 80) { - backgroundcolor = '"#FFFF00"'; - } else { - backgroundcolor = '"#FF0000"'; - } - elem.style.width = width + '%'; -} - -function refreshPeerList() { - var updatedPeerCount = 0; - node.swarm.peers() - .then((peers) => { - const peersAsHtml = peers.reverse() - .map((peer) => { - if (peer.addr) { - const addr = peer.addr.toString() - if (addr.indexOf('ipfs') >= 0) { - return addr - } else { - return addr + peer.peer.id.toB58String() - } - } - }) - .map((addr) => { - var splitString = addr.split("/"); - addr = splitString[splitString.length - 1]; - updatedPeerCount++; - if (!PeersForChannel.includes(addr)) { - PeersForChannel.push(addr); - } - return `${addr}` - }).join('') - - }).then(() => { - updatePeerProgress(((updatedPeerCount / 7) * 100), updatedPeerCount) - }) - .catch((error) => onError(error)) -} - -/* =========================================================================== - Error handling - =========================================================================== */ - -function onSuccess(msg) { - $logs.classList.add('success') - $logs.innerHTML = msg -} - -function onError(err) { - let msg = 'An error occured, check the dev console' - - if (err.stack !== undefined) { - msg = err.stack - } else if (typeof err === 'string') { - msg = err - } - - $logs.classList.remove('success') - $logs.innerHTML = msg -} - -window.onerror = onError - -/* =========================================================================== - App states - =========================================================================== */ - -const states = { - ready: () => { - const addressesHtml = info.addresses.map((address) => { - return `
  • ${address}
  • ` - }).join('') - $nodeId.innerText = info.id - $allDisabledButtons.forEach(b => { - b.disabled = false - }) - $allDisabledInputs.forEach(b => { - b.disabled = false - }) - $allDisabledElements.forEach(el => { - el.classList.remove('disabled') - }) - } -} - -function updateView(state, ipfs) { - if (states[state] !== undefined) { - states[state]() - } else { - throw new Error('Could not find state "' + state + '"') - } -} -/* =========================================================================== - Boot the app - =========================================================================== */ -window.startApplication = function() { - // Setup event listeners - $dragContainer.addEventListener('dragenter', onDragEnter) - $dragContainer.addEventListener('dragover', onDragEnter) - $dragContainer.addEventListener('drop', onDrop) - $dragContainer.addEventListener('dragleave', onDragLeave) - document.getElementById("fileUploadButton").addEventListener("change", onFileUpload) +window.startNode = function() { start() - extendedStartApplication() } - -function extendedStartApplication() { - $ethomessage.innerText = GlobalUserAddress; -} -window.stopApplication = function() { - resetUploadProcess(); - resetFileTable(); -} - -}).call(this,require('_process')) -},{"_process":1438,"buffer":217,"ethereum-private-key-to-address":336,"ethereumjs-common":355,"fs":212,"ipfs":692,"libp2p-pnet":1094,"node-fetch":1359,"pull-file-reader":1471,"request":1572,"web3":1839}],2:[function(require,module,exports){ +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":1258,"buffer":181,"ipfs":538,"libp2p-pnet":931}],2:[function(require,module,exports){ /*globals self, window */ "use strict" @@ -934,7 +258,7 @@ AbstractIterator.prototype._end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":1438}],5:[function(require,module,exports){ +},{"_process":1258}],5:[function(require,module,exports){ (function (Buffer,process){ var xtend = require('xtend') var supports = require('level-supports') @@ -1253,12 +577,33 @@ AbstractLevelDOWN.prototype._checkValue = function (value) { module.exports = AbstractLevelDOWN }).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) -},{"../is-buffer/index.js":766,"./abstract-chained-batch":3,"./abstract-iterator":4,"_process":1438,"level-supports":869,"xtend":1860}],6:[function(require,module,exports){ +},{"../is-buffer/index.js":608,"./abstract-chained-batch":3,"./abstract-iterator":4,"_process":1258,"level-supports":708,"xtend":7}],6:[function(require,module,exports){ exports.AbstractLevelDOWN = require('./abstract-leveldown') exports.AbstractIterator = require('./abstract-iterator') exports.AbstractChainedBatch = require('./abstract-chained-batch') },{"./abstract-chained-batch":3,"./abstract-iterator":4,"./abstract-leveldown":5}],7:[function(require,module,exports){ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + +},{}],8:[function(require,module,exports){ module.exports = after function after(count, callback, err_cb) { @@ -1288,5836 +633,7 @@ function after(count, callback, err_cb) { function noop() {} -},{}],8:[function(require,module,exports){ -'use strict'; - -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); -} - - - -/** - * 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 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; -} - - -/** - * 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 compile(schema, _meta) { - var schemaObj = this._addSchema(schema, undefined, _meta); - return schemaObj.validate || this._compile(schemaObj); -} - - -/** - * 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 addSchema(schema, key, _skipValidation, _meta) { - if (Array.isArray(schema)){ - for (var i=0; i} 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 - */ -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%\\^`{|}]|%[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":18}],13:[function(require,module,exports){ -'use strict'; - -var resolve = require('./resolve') - , util = require('./util') - , errorClasses = require('./error_classes') - , stableStringify = require('fast-json-stable-stringify'); - -var validateGenerator = require('../dotjs/validate'); - -/** - * Functions below are used inside compiled validations function - */ - -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; - - -/** - * 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 - */ -function compile(schema, root, localRefs, baseId) { - /* jshint validthis: true, evil: true */ - /* 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; - - try { - var v = localCompile(schema, root, localRefs, baseId); - compilation.validate = v; - var cv = compilation.callValidate; - 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)); - var validate; - 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; - } - - validate.schema = _schema; - validate.errors = null; - validate.refs = refs; - validate.refVal = refVal; - validate.root = isRoot ? validate : _root; - if ($async) validate.$async = true; - if (opts.sourceCode === true) { - validate.source = { - code: sourceCode, - patterns: patterns, - defaults: defaults - }; - } - - return validate; - } - - 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); - } - } - - 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; - } - return 'default' + index; - } - } - - 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); - } - } - } - - var compile = rule.definition.compile - , inline = rule.definition.inline - , macro = rule.definition.macro; - - var validate; - 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 - }; - } -} - - -/** - * 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 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 }; -} - - -/** - * 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 endCompiling(schema, root, baseId) { - /* jshint validthis: true */ - var i = compIndex.call(this, schema, root, baseId); - if (i >= 0) this._compilations.splice(i, 1); -} - - -/** - * 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 compIndex(schema, root, baseId) { - /* jshint validthis: true */ - for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { - // high surrogate, and there is a next character - value = str.charCodeAt(pos); - if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate - } - } - return length; -}; - -},{}],18:[function(require,module,exports){ -'use strict'; - - -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 + ')'; - case 'object': return '(' + OK + data + AND + - 'typeof ' + data + EQUAL + '"object"' + AND + - NOT + 'Array.isArray(' + data + '))'; - case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + - NOT + '(' + data + ' % 1)' + - AND + data + EQUAL + data + ')'; - default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; - } -} - - -function checkDataTypes(dataTypes, data) { - switch (dataTypes.length) { - case 1: return checkDataType(dataTypes[0], data, true); - default: - var code = ''; - var types = toHash(dataTypes); - if (types.array && types.object) { - code = types.null ? '(': '(!' + data + ' || '; - code += 'typeof ' + data + ' !== "object")'; - delete types.null; - delete types.array; - delete types.object; - } - if (types.number) delete types.integer; - for (var t in types) - code += (code ? ' && ' : '' ) + checkDataType(t, data, true); - - return code; - } -} - - -var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); -function coerceToTypes(optionCoerceTypes, dataTypes) { - if (Array.isArray(dataTypes)) { - var types = []; - for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); - return paths[lvl - up]; - } - - 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 expr = data; - var segments = jsonPointer.split('/'); - for (var i=0; i', - $notOp = $isMax ? '>' : '<', - $errorKeyword = undefined; - 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 */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } else if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - 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) + '=\'; '; - if ($schema === undefined) { - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $schemaValue = $schemaValueExcl; - $isData = $isDataExcl; - } - } else { - var $exclIsNumber = typeof $schemaExcl == 'number', - $opStr = $op; - if ($exclIsNumber && $isData) { - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - 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); - if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $notOp += '='; - } else { - $exclusive = false; - $opStr += '='; - } - } - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; - } - } - $errorKeyword = $errorKeyword || $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be ' + ($opStr) + ' '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schemaValue) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],22:[function(require,module,exports){ -'use strict'; -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; - } - var $op = $keyword == 'maxItems' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxItems') { - out += 'more'; - } else { - out += 'fewer'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' items\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],23:[function(require,module,exports){ -'use strict'; -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; - } - var $op = $keyword == 'maxLength' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - if (it.opts.unicode === false) { - out += ' ' + ($data) + '.length '; - } else { - out += ' ucs2length(' + ($data) + ') '; - } - out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be '; - if ($keyword == 'maxLength') { - out += 'longer'; - } else { - out += 'shorter'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' characters\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],24:[function(require,module,exports){ -'use strict'; -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 $op = $keyword == 'maxProperties' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxProperties') { - out += 'more'; - } else { - out += 'fewer'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' properties\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],25:[function(require,module,exports){ -'use strict'; -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; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : 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 += '}'; - } - } - } - } - if ($breakOnError) { - if ($allSchemasEmpty) { - out += ' if (true) { '; - } else { - out += ' ' + ($closingBraces.slice(0, -1)) + ' '; - } - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],26:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)); - }); - 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; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - 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 += '}'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should match some schema in anyOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - if (it.opts.allErrors) { - out += ' } '; - } - out = it.util.cleanUpCode(out); - } else { - if ($breakOnError) { - out += ' if (true) { '; - } - } - return out; -} - -},{}],27:[function(require,module,exports){ -'use strict'; -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); - 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);'; - } - return out; -} - -},{}],28:[function(require,module,exports){ -'use strict'; -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; - } - if (!$isData) { - out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to constant\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],29:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : 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) + ' '; - } - out += ' if (' + ($nextValid) + ') break; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; - } else { - out += ' if (' + ($data) + '.length == 0) {'; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should contain a valid item\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } else { '; - if ($nonEmptySchema) { - out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - } - if (it.opts.allErrors) { - out += ' } '; - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],30:[function(require,module,exports){ -'use strict'; -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 $rule = this, - $definition = 'definition' + $lvl, - $rDef = $rule.definition, - $closingBraces = ''; - var $compile, $inline, $macro, $ruleValidate, $validateCode; - 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 $ruleErrs = $validateCode + '.errors', - $i = 'i' + $lvl, - $ruleErr = 'ruleErr' + $lvl, - $asyncKeyword = $rDef.async; - if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); - if (!($inline || $macro)) { - out += '' + ($ruleErrs) + ' = null;'; - } - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if ($isData && $rDef.$data) { - $closingBraces += '}'; - out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; - if ($validateSchema) { - $closingBraces += '}'; - out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; - } - } - 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( '; - if (it.opts.passContext) { - out += 'this'; - } else { - out += 'self'; - } - if ($compile || $rDef.schema === false) { - out += ' , ' + ($data) + ' '; - } else { - out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; - } - out += ' , (dataPath || \'\')'; - if (it.errorPath != '""') { - out += ' + ' + (it.errorPath); - } - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; - var def_callRuleValidate = out; - out = $$outStack.pop(); - if ($rDef.errors === false) { - out += ' ' + ($valid) + ' = '; - if ($asyncKeyword) { - out += 'await '; - } - 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) + '; '; - } - } - } - if ($rDef.modifying) { - out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; - } - out += '' + ($closingBraces); - if ($rDef.valid) { - if ($breakOnError) { - out += ' if (true) { '; - } - } else { - out += ' if ( '; - if ($rDef.valid === undefined) { - out += ' !'; - if ($macro) { - out += '' + ($nextValid); - } else { - out += '' + ($valid); - } - } else { - out += ' ' + (!$rDef.valid) + ' '; - } - out += ') { '; - $errorKeyword = $rule.keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - var def_customError = out; - out = $$outStack.pop(); - if ($inline) { - if ($rDef.errors) { - if ($rDef.errors != 'full') { - out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0 : it.util.schemaHasRules($sch, it.RULES.all))) { - out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; - } - 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 += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],32:[function(require,module,exports){ -'use strict'; -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 $i = 'i' + $lvl, - $vSchema = 'schema' + $lvl; - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ';'; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to one of the allowed values\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],33:[function(require,module,exports){ -'use strict'; -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 || ''); - if (it.opts.format === false) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - 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 $unknownFormats = it.opts.unknownFormats, - $allowUnknown = Array.isArray($unknownFormats); - 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) + ') { '; - if (it.async) { - out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; - } - out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; - } - out += ' ('; - if ($unknownFormats != 'ignore') { - out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; - if ($allowUnknown) { - out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; - } - out += ') || '; - } - out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; - if (it.async) { - out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; - } else { - out += ' ' + ($format) + '(' + ($data) + ') '; - } - out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; - } else { - var $format = it.formats[$schema]; - if (!$format) { - if ($unknownFormats == 'ignore') { - it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } else { - throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); - } - } - var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; - var $formatType = $isObject && $format.type || 'string'; - if ($isObject) { - var $async = $format.async === true; - $format = $format.validate; - } - if ($formatType != $ruleType) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - 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'; - if (typeof $format == 'function') { - out += ' ' + ($formatRef) + '(' + ($data) + ') '; - } else { - out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; - } - out += ') { '; - } - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match format "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],34:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $thenSch == 'object' && Object.keys($thenSch).length > 0 : it.util.schemaHasRules($thenSch, it.RULES.all)), - $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? typeof $elseSch == 'object' && Object.keys($elseSch).length > 0 : 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\''; - } - out += ' } '; - if ($elsePresent) { - out += ' else { '; - } - } else { - out += ' if (!' + ($nextValid) + ') { '; - } - 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) + '; '; - if ($thenPresent && $elsePresent) { - $ifClause = 'ifClause' + $lvl; - out += ' var ' + ($ifClause) + ' = \'else\'; '; - } else { - $ifClause = '\'else\''; - } - out += ' } '; - } - out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - out = it.util.cleanUpCode(out); - } else { - if ($breakOnError) { - out += ' if (true) { '; - } - } - return out; -} - -},{}],35:[function(require,module,exports){ -'use strict'; - -//all requires must be explicit because browserify won't work with dynamic requires -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":21,"./_limitItems":22,"./_limitLength":23,"./_limitProperties":24,"./allOf":25,"./anyOf":26,"./comment":27,"./const":28,"./contains":29,"./dependencies":31,"./enum":32,"./format":33,"./if":34,"./items":36,"./multipleOf":37,"./not":38,"./oneOf":39,"./pattern":40,"./properties":41,"./propertyNames":42,"./ref":43,"./required":44,"./uniqueItems":45,"./validate":46}],36:[function(require,module,exports){ -'use strict'; -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 */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } '; - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : 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; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0 : 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; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } else if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : 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; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' }'; - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],37:[function(require,module,exports){ -'use strict'; -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; - } - out += 'var division' + ($lvl) + ';if ('; - if ($isData) { - out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; - } - out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; - if (it.opts.multipleOfPrecision) { - out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; - } else { - out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; - } - out += ' ) '; - if ($isData) { - out += ' ) '; - } - out += ' ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be multiple of '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schemaValue) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],38:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : 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 += ' {} '; - } - 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++; '; - } - 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 */ - 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 += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if ($breakOnError) { - out += ' if (false) { '; - } - } - return out; -} - -},{}],39:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : 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; '; - } - if ($i) { - out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; - $closingBraces += '}'; - } - out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match exactly one schema in oneOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; - if (it.opts.allErrors) { - out += ' } '; - } - return out; -} - -},{}],40:[function(require,module,exports){ -'use strict'; -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; - } - var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; - } - out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match pattern "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],41:[function(require,module,exports){ -'use strict'; -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 { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - if ($someProperties) { - out += ' var isAdditional' + ($lvl) + ' = !(false '; - if ($schemaKeys.length) { - if ($schemaKeys.length > 8) { - out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; - } else { - var arr1 = $schemaKeys; - if (arr1) { - var $propertyKey, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $propertyKey = arr1[i1 += 1]; - out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; - } - } - } - } - if ($pPropertyKeys.length) { - var arr2 = $pPropertyKeys; - if (arr2) { - var $pProperty, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $pProperty = arr2[$i += 1]; - out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; - } - } - } - out += ' ); if (isAdditional' + ($lvl) + ') { '; - } - if ($removeAdditional == 'all') { - out += ' delete ' + ($data) + '[' + ($key) + ']; '; - } else { - var $currentErrorPath = it.errorPath; - var $additionalProperty = '\' + ' + $key + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - } - 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'; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - $errSchemaPath = $currErrSchemaPath; - 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) + ' '; - } - 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) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - } - } - it.errorPath = $currentErrorPath; - } - if ($someProperties) { - out += ' } '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - var $useDefaults = it.opts.useDefaults && !it.compositeRule; - if ($schemaKeys.length) { - 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 ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : 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) + '; '; - } - if ($hasDefault) { - out += ' ' + ($code) + ' '; - } else { - if ($requiredHash && $requiredHash[$propertyKey]) { - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($nextValid) + ' = false; '; - var $currentErrorPath = it.errorPath, - $currErrSchemaPath = $errSchemaPath, - $missingProperty = it.util.escapeQuotes($propertyKey); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - $errSchemaPath = it.errSchemaPath + '/required'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - $errSchemaPath = $currErrSchemaPath; - it.errorPath = $currentErrorPath; - out += ' } else { '; - } else { - if ($breakOnError) { - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($nextValid) + ' = true; } else { '; - } else { - out += ' if (' + ($useData) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ' ) { '; - } - } - out += ' ' + ($code) + ' } '; - } - } - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if ($pPropertyKeys.length) { - var arr4 = $pPropertyKeys; - if (arr4) { - var $pProperty, i4 = -1, - l4 = arr4.length - 1; - while (i4 < l4) { - $pProperty = arr4[i4 += 1]; - var $sch = $pProperties[$pProperty]; - if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : 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 ($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) + ') { '; - } - 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 (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else ' + ($nextValid) + ' = true; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],42:[function(require,module,exports){ -'use strict'; -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.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : 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 { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - 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; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0 : it.util.schemaHasRules($propertySch, it.RULES.all)))) { - $required[$required.length] = $property; - } - } - } - } else { - var $required = $schema; - } - } - if ($isData || $required.length) { - var $currentErrorPath = it.errorPath, - $loopRequired = $isData || $required.length >= it.opts.loopRequired, - $ownProperties = it.opts.ownProperties; - if ($breakOnError) { - out += ' var missing' + ($lvl) + '; '; - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - out += ' var ' + ($valid) + ' = true; '; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += '; if (!' + ($valid) + ') break; } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } else { '; - } else { - out += ' if ( '; - var arr2 = $required; - if (arr2) { - var $propertyKey, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $propertyKey = arr2[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty($propertyKey), - $useData = $data + $prop; - out += ' ( ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; - } - } - out += ') { '; - var $propertyPath = 'missing' + $lvl, - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } else { '; - } - } else { - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - if ($isData) { - out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; - if ($isData) { - out += ' } '; - } - } else { - var arr3 = $required; - if (arr3) { - var $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 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); - } - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - } - } - } - } - it.errorPath = $currentErrorPath; - } else if ($breakOnError) { - out += ' if (true) {'; - } - return out; -} - -},{}],45:[function(require,module,exports){ -'use strict'; -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; - } - 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 { '; - } - out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; - var $itemType = it.schema.items && it.schema.items.type, - $typeIsArray = Array.isArray($itemType); - 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; '; - if ($typeIsArray) { - out += ' if (typeof item == \'string\') item = \'"\' + item; '; - } - out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; - } - out += ' } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - } else { - if ($breakOnError) { - out += ' if (true) { '; - } - } - return out; -} - -},{}],46:[function(require,module,exports){ -'use strict'; -module.exports = function generate_validate(it, $keyword, $ruleType) { - var out = ''; - var $async = it.schema.$async === true, - $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), - $id = it.self._getId(it.schema); - if (it.opts.strictKeywords) { - var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); - if ($unknownKwd) { - var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; - if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); - else throw new Error($keywordsMsg); - } - } - if (it.isTop) { - out += ' var validate = '; - if ($async) { - it.async = true; - out += 'async '; - } - out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; - if ($id && (it.opts.sourceCode || it.opts.processCode)) { - out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; - } - } - 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; - if (it.schema === false) { - if (it.isTop) { - $breakOnError = true; - } else { - out += ' var ' + ($valid) + ' = false; '; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'boolean schema is false\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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; '; - } - } - if (it.isTop) { - out += ' }; return validate; '; - } - return out; - } - 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]; - 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;'; - } - var $valid = 'valid' + $lvl, - $breakOnError = !it.opts.allErrors, - $closingBraces1 = '', - $closingBraces2 = ''; - var $errorKeyword; - var $typeSchema = it.schema.type, - $typeIsArray = Array.isArray($typeSchema); - 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; - } - } - if ($typeIsArray && $typeSchema.length == 1) { - $typeSchema = $typeSchema[0]; - $typeIsArray = false; - } - if (it.schema.$ref && $refKeywords) { - if (it.opts.extendRefs == 'fail') { - throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); - } else if (it.opts.extendRefs !== true) { - $refKeywords = false; - it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); - } - } - if (it.schema.$comment && it.opts.$comment) { - out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); - } - if ($typeSchema) { - if (it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); - } - var $rulesGroup = it.RULES.types[$typeSchema]; - if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type'; - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type', - $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; - out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; - if ($coerceToTypes) { - var $dataType = 'dataType' + $lvl, - $coerced = 'coerced' + $lvl; - out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; - if (it.opts.coerceTypes == 'array') { - out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; - } - out += ' var ' + ($coerced) + ' = undefined; '; - var $bracesCoercion = ''; - var arr1 = $coerceToTypes; - if (arr1) { - var $type, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $type = arr1[$i += 1]; - if ($i) { - out += ' if (' + ($coerced) + ' === undefined) { '; - $bracesCoercion += '}'; - } - if (it.opts.coerceTypes == 'array' && $type != 'array') { - out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; - } - if ($type == 'string') { - out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; - } else if ($type == 'number' || $type == 'integer') { - out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; - if ($type == 'integer') { - out += ' && !(' + ($data) + ' % 1)'; - } - 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) + ']; '; - } - } - } - out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } else { '; - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' ' + ($data) + ' = ' + ($coerced) + '; '; - if (!$dataLvl) { - out += 'if (' + ($parentData) + ' !== undefined)'; - } - out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - } - out += ' } '; - } - } - if (it.schema.$ref && !$refKeywords) { - out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; - if ($breakOnError) { - out += ' } if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } else { - var arr2 = it.RULES; - if (arr2) { - var $rulesGroup, i2 = -1, - l2 = arr2.length - 1; - while (i2 < l2) { - $rulesGroup = arr2[i2 += 1]; - if ($shouldUseGroup($rulesGroup)) { - if ($rulesGroup.type) { - out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; - } - 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; - if (arr4) { - var $sch, $i = -1, - l4 = arr4.length - 1; - while ($i < l4) { - $sch = arr4[$i += 1]; - if ($sch.default !== undefined) { - var $passData = $data + '[' + $i + ']'; - 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 += '; '; - } - } - } - } - } - } - var arr5 = $rulesGroup.rules; - if (arr5) { - var $rule, i5 = -1, - l5 = arr5.length - 1; - while (i5 < l5) { - $rule = arr5[i5 += 1]; - if ($shouldUseRule($rule)) { - var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); - if ($code) { - out += ' ' + ($code) + ' '; - if ($breakOnError) { - $closingBraces1 += '}'; - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces1) + ' '; - $closingBraces1 = ''; - } - if ($rulesGroup.type) { - out += ' } '; - 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 */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - 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++; '; - } - out += ' } '; - } - } - if ($breakOnError) { - out += ' if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces2) + ' '; - } - 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; '; - } - out += ' }; return validate;'; - } else { - out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; - } - out = it.util.cleanUpCode(out); - if ($top) { - out = it.util.finalCleanUpCode(out, $async); - } - - function $shouldUseGroup($rulesGroup) { - var rules = $rulesGroup.rules; - for (var i = 0; i < rules.length; i++) - if ($shouldUseRule(rules[i])) return true; - } - - function $shouldUseRule($rule) { - return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); - } - - function $ruleImplementsSomeKeyword($rule) { - var impl = $rule.implements; - for (var i = 0; i < impl.length; i++) - if (it.schema[impl[i]] !== undefined) return true; - } - return out; -} - -},{}],47:[function(require,module,exports){ -'use strict'; - -var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; -var customRuleCode = require('./dotjs/custom'); -var definitionSchema = require('./definition_schema'); - -module.exports = { - add: addKeyword, - get: getKeyword, - remove: removeKeyword, - validate: validateKeyword -}; - - -/** - * 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 - */ -function addKeyword(keyword, definition) { - /* jshint validthis: true */ - /* 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'); - - if (definition) { - this.validateKeyword(definition, true); - - var dataType = definition.type; - if (Array.isArray(dataType)) { - for (var i=0; i= 0.12 - * 3. Auto detected promise based on first sucessful require of - * known promise libraries. Note this is a last resort, as the - * loaded library is non-deterministic. node.js >= 0.12 will - * always use global.Promise over this priority list. - * 4. Throws error. - * - * For Browser: - * - * 1. Previous registration - * 2. window.Promise - * 3. Throws error. - * - * Options: - * - * Promise: Desired Promise constructor - * global: Boolean - Should the registration be cached in a global variable to - * allow cross dependency/bundle registration? (default true) - */ -module.exports = function(root, loadImplementation){ - return function register(implementation, opts){ - implementation = implementation || null - opts = opts || {} - // global registration unless explicitly {global: false} in options (default true) - var registerGlobal = opts.global !== false; - - // load any previous global registration - if(registered === null && registerGlobal){ - registered = root[REGISTRATION_KEY] || null - } - - if(registered !== null - && implementation !== null - && registered.implementation !== implementation){ - // Throw error if attempting to redefine implementation - throw new Error('any-promise already defined as "'+registered.implementation+ - '". You can only register an implementation before the first '+ - ' call to require("any-promise") and an implementation cannot be changed') - } - - if(registered === null){ - // use provided implementation - if(implementation !== null && typeof opts.Promise !== 'undefined'){ - registered = { - Promise: opts.Promise, - implementation: implementation - } - } else { - // require implementation if implementation is specified but not provided - registered = loadImplementation(implementation) - } - - if(registerGlobal){ - // register preference globally in case multiple installations - root[REGISTRATION_KEY] = registered - } - } - - return registered - } -} - -},{}],53:[function(require,module,exports){ -"use strict"; -module.exports = require('./loader')(window, loadImplementation) - -/** - * Browser specific loadImplementation. Always uses `window.Promise` - * - * To register a custom implementation, must register with `Promise` option. - */ -function loadImplementation(){ - if(typeof window.Promise === 'undefined'){ - throw new Error("any-promise browser requires a polyfill or explicit registration"+ - " e.g: require('any-promise/register/bluebird')") - } - return { - Promise: window.Promise, - implementation: 'window.Promise' - } -} - -},{"./loader":52}],54:[function(require,module,exports){ +},{}],9:[function(require,module,exports){ 'use strict'; module.exports = function (arr) { if (!Array.isArray(arr)) { @@ -7139,7 +655,7 @@ module.exports = function (arr) { return ret; }; -},{}],55:[function(require,module,exports){ +},{}],10:[function(require,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported @@ -7170,7 +686,7 @@ module.exports = function(arraybuffer, start, end) { return result.buffer; }; -},{}],56:[function(require,module,exports){ +},{}],11:[function(require,module,exports){ var asn1 = exports; asn1.bignum = require('bn.js'); @@ -7181,7 +697,7 @@ asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); -},{"./asn1/api":57,"./asn1/base":59,"./asn1/constants":63,"./asn1/decoders":65,"./asn1/encoders":68,"bn.js":171}],57:[function(require,module,exports){ +},{"./asn1/api":12,"./asn1/base":14,"./asn1/constants":18,"./asn1/decoders":20,"./asn1/encoders":23,"bn.js":135}],12:[function(require,module,exports){ var asn1 = require('../asn1'); var inherits = require('inherits'); @@ -7244,7 +760,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; -},{"../asn1":56,"inherits":453,"vm":1788}],58:[function(require,module,exports){ +},{"../asn1":11,"inherits":317,"vm":1523}],13:[function(require,module,exports){ var inherits = require('inherits'); var Reporter = require('../base').Reporter; var Buffer = require('buffer').Buffer; @@ -7362,7 +878,7 @@ EncoderBuffer.prototype.join = function join(out, offset) { return out; }; -},{"../base":59,"buffer":217,"inherits":453}],59:[function(require,module,exports){ +},{"../base":14,"buffer":181,"inherits":317}],14:[function(require,module,exports){ var base = exports; base.Reporter = require('./reporter').Reporter; @@ -7370,7 +886,7 @@ base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); -},{"./buffer":58,"./node":60,"./reporter":61}],60:[function(require,module,exports){ +},{"./buffer":13,"./node":15,"./reporter":16}],15:[function(require,module,exports){ var Reporter = require('../base').Reporter; var EncoderBuffer = require('../base').EncoderBuffer; var DecoderBuffer = require('../base').DecoderBuffer; @@ -8006,7 +1522,7 @@ Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); }; -},{"../base":59,"minimalistic-assert":1303}],61:[function(require,module,exports){ +},{"../base":14,"minimalistic-assert":1129}],16:[function(require,module,exports){ var inherits = require('inherits'); function Reporter(options) { @@ -8129,7 +1645,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) { return this; }; -},{"inherits":453}],62:[function(require,module,exports){ +},{"inherits":317}],17:[function(require,module,exports){ var constants = require('../constants'); exports.tagClass = { @@ -8173,7 +1689,7 @@ exports.tag = { }; exports.tagByName = constants._reverse(exports.tag); -},{"../constants":63}],63:[function(require,module,exports){ +},{"../constants":18}],18:[function(require,module,exports){ var constants = exports; // Helper @@ -8194,7 +1710,7 @@ constants._reverse = function reverse(map) { constants.der = require('./der'); -},{"./der":62}],64:[function(require,module,exports){ +},{"./der":17}],19:[function(require,module,exports){ var inherits = require('inherits'); var asn1 = require('../../asn1'); @@ -8520,13 +2036,13 @@ function derDecodeLen(buf, primitive, fail) { return len; } -},{"../../asn1":56,"inherits":453}],65:[function(require,module,exports){ +},{"../../asn1":11,"inherits":317}],20:[function(require,module,exports){ var decoders = exports; decoders.der = require('./der'); decoders.pem = require('./pem'); -},{"./der":64,"./pem":66}],66:[function(require,module,exports){ +},{"./der":19,"./pem":21}],21:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; @@ -8577,7 +2093,7 @@ PEMDecoder.prototype.decode = function decode(data, options) { return DERDecoder.prototype.decode.call(this, input, options); }; -},{"./der":64,"buffer":217,"inherits":453}],67:[function(require,module,exports){ +},{"./der":19,"buffer":181,"inherits":317}],22:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; @@ -8874,13 +2390,13 @@ function encodeTag(tag, primitive, cls, reporter) { return res; } -},{"../../asn1":56,"buffer":217,"inherits":453}],68:[function(require,module,exports){ +},{"../../asn1":11,"buffer":181,"inherits":317}],23:[function(require,module,exports){ var encoders = exports; encoders.der = require('./der'); encoders.pem = require('./pem'); -},{"./der":67,"./pem":69}],69:[function(require,module,exports){ +},{"./der":22,"./pem":24}],24:[function(require,module,exports){ var inherits = require('inherits'); var DEREncoder = require('./der'); @@ -8903,694 +2419,7 @@ PEMEncoder.prototype.encode = function encode(data, options) { return out.join('\n'); }; -},{"./der":67,"inherits":453}],70:[function(require,module,exports){ -// Copyright 2011 Mark Cavage All rights reserved. - - -module.exports = { - - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; - } - -}; - -},{}],71:[function(require,module,exports){ -// Copyright 2011 Mark Cavage All rights reserved. - -var errors = require('./errors'); -var types = require('./types'); - -var Reader = require('./reader'); -var Writer = require('./writer'); - - -// --- Exports - -module.exports = { - - Reader: Reader, - - Writer: Writer - -}; - -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} - -},{"./errors":70,"./reader":72,"./types":73,"./writer":74}],72:[function(require,module,exports){ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; - -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - - - -// --- API - -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; -} - -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); - -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); - -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { 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. - */ -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; -}; - - -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 - */ -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; - - 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; - 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; - } - - 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. - */ -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` - if (o === null) - return null; - - this._offset = o; - return seq; -}; - - -Reader.prototype.readInt = function () { - return this._readTag(ASN1.Integer); -}; - - -Reader.prototype.readBoolean = function () { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; - - -Reader.prototype.readEnumeration = function () { - return this._readTag(ASN1.Enumeration); -}; - - -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` - - 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) : ''; - - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - - return retbuf ? str : str.toString('utf8'); -}; - -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; - - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; - - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } - - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); - - return values.join('.'); -}; - - -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` - 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; - - 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 - -module.exports = Reader; - -},{"./errors":70,"./types":73,"assert":78,"safer-buffer":1594}],73:[function(require,module,exports){ -// 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 -}; - -},{}],74:[function(require,module,exports){ -// Copyright 2011 Mark Cavage All rights reserved. - -var assert = require('assert'); -var Buffer = require('safer-buffer').Buffer; -var ASN1 = require('./types'); -var errors = require('./errors'); - - -// --- Globals - -var newInvalidAsn1Error = errors.newInvalidAsn1Error; - -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 -}; - - -// --- Helpers - -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 - -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. - this._seq = []; -} - -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); - - return (this._buf.slice(0, this._offset)); - } -}); - -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); - - this._ensure(1); - this._buf[this._offset++] = b; -}; - - -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; - - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; - } - - if (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; - - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } - -}; - - -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; - - -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); -}; - - -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; - - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; - - -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); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; - } -}; - - -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); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; - - -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 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; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; - - -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)'); - } -}; - -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; - - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; - - -Writer.prototype.endSequence = function () { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; - - if (len <= 0x7f) { - this._shift(start, len, -2); - 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'); - } -}; - - -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); - 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); - this._buf = buf; - this._size = sz; - } -}; - - - -// --- Exported API - -module.exports = Writer; - -},{"./errors":70,"./types":73,"assert":78,"safer-buffer":1594}],75:[function(require,module,exports){ -// 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 - -module.exports = { - - Ber: Ber, - - BerReader: Ber.Reader, - - BerWriter: Ber.Writer - -}; - -},{"./ber/index":71}],76:[function(require,module,exports){ +},{"./der":22,"inherits":317}],25:[function(require,module,exports){ "use strict"; const hasBigInt64 = typeof BigUint64Array !== "undefined"; @@ -9916,222 +2745,7 @@ function demangle(exports, baseModule) { exports.demangle = demangle; -},{}],77:[function(require,module,exports){ -(function (Buffer,process){ -// Copyright (c) 2012, Mark Cavage. All rights reserved. -// Copyright 2015 Joyent, Inc. - -var assert = require('assert'); -var Stream = require('stream').Stream; -var util = require('util'); - - -///--- Globals - -/* JSSTYLED */ -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 _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 _getClass(arg) { - return (Object.prototype.toString.call(arg).slice(8, -1)); -} - -function noop() { - // Why even bother with asserts? -} - - -///--- Exports - -var types = { - bool: { - check: function (arg) { return typeof (arg) === 'boolean'; } - }, - func: { - check: function (arg) { return typeof (arg) === 'function'; } - }, - string: { - check: function (arg) { return typeof (arg) === 'string'; } - }, - object: { - check: function (arg) { - return typeof (arg) === 'object' && arg !== null; - } - }, - number: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg); - } - }, - finite: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); - } - }, - buffer: { - check: function (arg) { return Buffer.isBuffer(arg); }, - operator: 'Buffer.isBuffer' - }, - array: { - check: function (arg) { return Array.isArray(arg); }, - operator: 'Array.isArray' - }, - stream: { - check: function (arg) { return arg instanceof Stream; }, - operator: 'instanceof', - actual: _getClass - }, - date: { - check: function (arg) { return arg instanceof Date; }, - operator: 'instanceof', - actual: _getClass - }, - regexp: { - check: function (arg) { return arg instanceof RegExp; }, - operator: 'instanceof', - actual: _getClass - }, - uuid: { - check: function (arg) { - return typeof (arg) === 'string' && UUID_REGEXP.test(arg); - }, - operator: 'isUUID' - } -}; - -function _setExports(ndebug) { - var keys = Object.keys(types); - var out; - - /* re-export standard assert */ - if (process.env.NODE_NDEBUG) { - out = noop; - } else { - out = function (arg, msg) { - if (!arg) { - _toss(msg, 'true', arg); - } - }; - } - - /* standard checks */ - keys.forEach(function (k) { - if (ndebug) { - out[k] = noop; - return; - } - var type = types[k]; - out[k] = function (arg, msg) { - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); - - /* 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; - } - 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; - } - 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; - } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - 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); - } - } - }; - }); - - /* re-export built-in assertions */ - Object.keys(assert).forEach(function (k) { - if (k === 'AssertionError') { - out[k] = assert[k]; - return; - } - if (ndebug) { - out[k] = noop; - return; - } - out[k] = assert[k]; - }); - - /* export ourselves (for unit tests _only_) */ - out._setExports = _setExports; - - return out; -} - -module.exports = _setExports(process.env.NODE_NDEBUG); - -}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) -},{"../is-buffer/index.js":766,"_process":1438,"assert":78,"stream":1715,"util":1776}],78:[function(require,module,exports){ +},{}],26:[function(require,module,exports){ (function (global){ 'use strict'; @@ -10641,7 +3255,7 @@ var objectKeys = Object.keys || function (obj) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"object-assign":1388,"util/":81}],79:[function(require,module,exports){ +},{"object-assign":1226,"util/":29}],27:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -10666,14 +3280,14 @@ if (typeof Object.create === 'function') { } } -},{}],80:[function(require,module,exports){ +},{}],28:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],81:[function(require,module,exports){ +},{}],29:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -11263,7 +3877,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":80,"_process":1438,"inherits":79}],82:[function(require,module,exports){ +},{"./support/isBuffer":28,"_process":1258,"inherits":27}],30:[function(require,module,exports){ 'use strict' const toArray = async (iterator) => { @@ -11278,7 +3892,7 @@ const toArray = async (iterator) => { module.exports = toArray -},{}],83:[function(require,module,exports){ +},{}],31:[function(require,module,exports){ 'use strict' async function * batch (source, size) { @@ -11303,7 +3917,7 @@ async function * batch (source, size) { module.exports = batch -},{}],84:[function(require,module,exports){ +},{}],32:[function(require,module,exports){ 'use strict' const first = async (iterator) => { @@ -11314,7 +3928,7 @@ const first = async (iterator) => { module.exports = first -},{}],85:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ 'use strict' const last = async (iterator) => { @@ -11329,7 +3943,7 @@ const last = async (iterator) => { module.exports = last -},{}],86:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ const getIterator = require('get-iterator') const toIterable = require('pull-stream-to-async-iterator') @@ -11403,7 +4017,7 @@ toPull.sink = sink => { module.exports = toPull -},{"get-iterator":388,"pull-stream-to-async-iterator":1493}],87:[function(require,module,exports){ +},{"get-iterator":281,"pull-stream-to-async-iterator":1309}],35:[function(require,module,exports){ (function (process){ "use strict"; @@ -11531,7 +4145,7 @@ asyncIteratorToStream.obj = (iterable, options) => asyncIteratorToStream(iterabl }, options)); }).call(this,require('_process')) -},{"_process":1438,"readable-stream":102}],88:[function(require,module,exports){ +},{"_process":1258,"readable-stream":50}],36:[function(require,module,exports){ 'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } @@ -11660,7 +4274,7 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes; -},{}],89:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ (function (process){ 'use strict' @@ -11681,7 +4295,7 @@ module.exports.emitExperimentalWarning = process.emitWarning : noop; }).call(this,require('_process')) -},{"_process":1438}],90:[function(require,module,exports){ +},{"_process":1258}],38:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -11823,7 +4437,7 @@ Object.defineProperty(Duplex.prototype, 'destroyed', { } }); }).call(this,require('_process')) -},{"./_stream_readable":92,"./_stream_writable":94,"_process":1438,"inherits":453}],91:[function(require,module,exports){ +},{"./_stream_readable":40,"./_stream_writable":42,"_process":1258,"inherits":317}],39:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -11863,7 +4477,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":93,"inherits":453}],92:[function(require,module,exports){ +},{"./_stream_transform":41,"inherits":317}],40:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -12953,7 +5567,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":88,"../experimentalWarning":89,"./_stream_duplex":90,"./internal/streams/async_iterator":95,"./internal/streams/buffer_list":96,"./internal/streams/destroy":97,"./internal/streams/state":100,"./internal/streams/stream":101,"_process":1438,"buffer":217,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],93:[function(require,module,exports){ +},{"../errors":36,"../experimentalWarning":37,"./_stream_duplex":38,"./internal/streams/async_iterator":43,"./internal/streams/buffer_list":44,"./internal/streams/destroy":45,"./internal/streams/state":48,"./internal/streams/stream":49,"_process":1258,"buffer":181,"events":272,"inherits":317,"string_decoder/":52,"util":146}],41:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13155,7 +5769,7 @@ function done(stream, er, data) { if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } -},{"../errors":88,"./_stream_duplex":90,"inherits":453}],94:[function(require,module,exports){ +},{"../errors":36,"./_stream_duplex":38,"inherits":317}],42:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -13841,7 +6455,7 @@ Writable.prototype._destroy = function (err, cb) { cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":88,"./_stream_duplex":90,"./internal/streams/destroy":97,"./internal/streams/state":100,"./internal/streams/stream":101,"_process":1438,"buffer":217,"inherits":453,"util-deprecate":1773}],95:[function(require,module,exports){ +},{"../errors":36,"./_stream_duplex":38,"./internal/streams/destroy":45,"./internal/streams/state":48,"./internal/streams/stream":49,"_process":1258,"buffer":181,"inherits":317,"util-deprecate":1510}],43:[function(require,module,exports){ (function (process){ 'use strict'; @@ -14051,7 +6665,7 @@ var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterat module.exports = createReadableStreamAsyncIterator; }).call(this,require('_process')) -},{"./end-of-stream":98,"_process":1438}],96:[function(require,module,exports){ +},{"./end-of-stream":46,"_process":1258}],44:[function(require,module,exports){ 'use strict'; function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } @@ -14241,7 +6855,7 @@ function () { return BufferList; }(); -},{"buffer":217,"util":182}],97:[function(require,module,exports){ +},{"buffer":181,"util":146}],45:[function(require,module,exports){ (function (process){ 'use strict'; // undocumented cb() API, needed for core, not for public API @@ -14329,7 +6943,7 @@ module.exports = { undestroy: undestroy }; }).call(this,require('_process')) -},{"_process":1438}],98:[function(require,module,exports){ +},{"_process":1258}],46:[function(require,module,exports){ // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; @@ -14434,7 +7048,7 @@ function eos(stream, opts, callback) { } module.exports = eos; -},{"../../../errors":88}],99:[function(require,module,exports){ +},{"../../../errors":36}],47:[function(require,module,exports){ // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; @@ -14532,7 +7146,7 @@ function pipeline() { } module.exports = pipeline; -},{"../../../errors":88,"./end-of-stream":98}],100:[function(require,module,exports){ +},{"../../../errors":36,"./end-of-stream":46}],48:[function(require,module,exports){ 'use strict'; var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; @@ -14560,10 +7174,10 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) { module.exports = { getHighWaterMark: getHighWaterMark }; -},{"../../../errors":88}],101:[function(require,module,exports){ +},{"../../../errors":36}],49:[function(require,module,exports){ module.exports = require('events').EventEmitter; -},{"events":370}],102:[function(require,module,exports){ +},{"events":272}],50:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -14574,7 +7188,370 @@ 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'); -},{"./lib/_stream_duplex.js":90,"./lib/_stream_passthrough.js":91,"./lib/_stream_readable.js":92,"./lib/_stream_transform.js":93,"./lib/_stream_writable.js":94,"./lib/internal/streams/end-of-stream.js":98,"./lib/internal/streams/pipeline.js":99}],103:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":38,"./lib/_stream_passthrough.js":39,"./lib/_stream_readable.js":40,"./lib/_stream_transform.js":41,"./lib/_stream_writable.js":42,"./lib/internal/streams/end-of-stream.js":46,"./lib/internal/streams/pipeline.js":47}],51:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +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) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +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) + } else { + buf.fill(fill) + } + } 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":181}],52:[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'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":51}],53:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -14685,7 +7662,7 @@ function rethrow(error) { throw error; } module.exports = exports['default']; -},{"./internal/initialParams":124,"./internal/setImmediate":133,"lodash/isObject":1285}],104:[function(require,module,exports){ +},{"./internal/initialParams":74,"./internal/setImmediate":83,"lodash/isObject":1114}],54:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -14747,7 +7724,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); module.exports = exports['default']; -},{"./internal/createTester":116,"./internal/doParallel":118,"./internal/findGetResult":122,"lodash/identity":1278}],105:[function(require,module,exports){ +},{"./internal/createTester":66,"./internal/doParallel":68,"./internal/findGetResult":72,"lodash/identity":1107}],55:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -14796,7 +7773,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); module.exports = exports['default']; -},{"./internal/createTester":116,"./internal/doParallelLimit":119,"./internal/findGetResult":122,"lodash/identity":1278}],106:[function(require,module,exports){ +},{"./internal/createTester":66,"./internal/doParallelLimit":69,"./internal/findGetResult":72,"lodash/identity":1107}],56:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -14879,7 +7856,7 @@ function eachLimit(coll, iteratee, callback) { (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } module.exports = exports['default']; -},{"./eachOf":108,"./internal/withoutIndex":135,"./internal/wrapAsync":136}],107:[function(require,module,exports){ +},{"./eachOf":58,"./internal/withoutIndex":85,"./internal/wrapAsync":86}],57:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -14925,7 +7902,7 @@ function eachLimit(coll, limit, iteratee, callback) { (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } module.exports = exports['default']; -},{"./internal/eachOfLimit":120,"./internal/withoutIndex":135,"./internal/wrapAsync":136}],108:[function(require,module,exports){ +},{"./internal/eachOfLimit":70,"./internal/withoutIndex":85,"./internal/wrapAsync":86}],58:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15037,7 +8014,7 @@ var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); * }); */ module.exports = exports['default']; -},{"./eachOfLimit":109,"./internal/breakLoop":115,"./internal/doLimit":117,"./internal/once":128,"./internal/onlyOnce":129,"./internal/wrapAsync":136,"lodash/isArrayLike":1281,"lodash/noop":1291}],109:[function(require,module,exports){ +},{"./eachOfLimit":59,"./internal/breakLoop":65,"./internal/doLimit":67,"./internal/once":78,"./internal/onlyOnce":79,"./internal/wrapAsync":86,"lodash/isArrayLike":1110,"lodash/noop":1120}],59:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15079,7 +8056,7 @@ function eachOfLimit(coll, limit, iteratee, callback) { (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); } module.exports = exports['default']; -},{"./internal/eachOfLimit":120,"./internal/wrapAsync":136}],110:[function(require,module,exports){ +},{"./internal/eachOfLimit":70,"./internal/wrapAsync":86}],60:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15115,7 +8092,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); module.exports = exports['default']; -},{"./eachOfLimit":109,"./internal/doLimit":117}],111:[function(require,module,exports){ +},{"./eachOfLimit":59,"./internal/doLimit":67}],61:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15153,7 +8130,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); module.exports = exports['default']; -},{"./eachLimit":107,"./internal/doLimit":117}],112:[function(require,module,exports){ +},{"./eachLimit":57,"./internal/doLimit":67}],62:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15204,7 +8181,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); module.exports = exports['default']; -},{"./internal/createTester":116,"./internal/doParallel":118,"./internal/notId":127}],113:[function(require,module,exports){ +},{"./internal/createTester":66,"./internal/doParallel":68,"./internal/notId":77}],63:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15250,7 +8227,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)(_filter2.default); module.exports = exports['default']; -},{"./internal/doParallel":118,"./internal/filter":121}],114:[function(require,module,exports){ +},{"./internal/doParallel":68,"./internal/filter":71}],64:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15339,7 +8316,7 @@ DLL.prototype.remove = function (testFn) { return this; }; module.exports = exports["default"]; -},{}],115:[function(require,module,exports){ +},{}],65:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15349,7 +8326,7 @@ Object.defineProperty(exports, "__esModule", { // See #1064, #1293 exports.default = {}; module.exports = exports["default"]; -},{}],116:[function(require,module,exports){ +},{}],66:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15394,7 +8371,7 @@ function _createTester(check, getResult) { }; } module.exports = exports['default']; -},{"./breakLoop":115,"lodash/noop":1291}],117:[function(require,module,exports){ +},{"./breakLoop":65,"lodash/noop":1120}],67:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15407,7 +8384,7 @@ function doLimit(fn, limit) { }; } module.exports = exports["default"]; -},{}],118:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15431,7 +8408,7 @@ function doParallel(fn) { }; } module.exports = exports['default']; -},{"../eachOf":108,"./wrapAsync":136}],119:[function(require,module,exports){ +},{"../eachOf":58,"./wrapAsync":86}],69:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15455,7 +8432,7 @@ function doParallelLimit(fn) { }; } module.exports = exports['default']; -},{"./eachOfLimit":120,"./wrapAsync":136}],120:[function(require,module,exports){ +},{"./eachOfLimit":70,"./wrapAsync":86}],70:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15530,7 +8507,7 @@ function _eachOfLimit(limit) { }; } module.exports = exports['default']; -},{"./breakLoop":115,"./iterator":125,"./once":128,"./onlyOnce":129,"lodash/noop":1291}],121:[function(require,module,exports){ +},{"./breakLoop":65,"./iterator":75,"./once":78,"./onlyOnce":79,"lodash/noop":1120}],71:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15606,7 +8583,7 @@ function _filter(eachfn, coll, iteratee, callback) { filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); } module.exports = exports['default']; -},{"./wrapAsync":136,"lodash/_arrayMap":1222,"lodash/_baseProperty":1233,"lodash/isArrayLike":1281,"lodash/noop":1291}],122:[function(require,module,exports){ +},{"./wrapAsync":86,"lodash/_arrayMap":1051,"lodash/_baseProperty":1062,"lodash/isArrayLike":1110,"lodash/noop":1120}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15617,7 +8594,7 @@ function _findGetResult(v, x) { return x; } module.exports = exports["default"]; -},{}],123:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15631,7 +8608,7 @@ exports.default = function (coll) { var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; module.exports = exports['default']; -},{}],124:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15653,7 +8630,7 @@ var _slice2 = _interopRequireDefault(_slice); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; -},{"./slice":134}],125:[function(require,module,exports){ +},{"./slice":84}],75:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15712,7 +8689,7 @@ function iterator(coll) { return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); } module.exports = exports['default']; -},{"./getIterator":123,"lodash/isArrayLike":1281,"lodash/keys":1289}],126:[function(require,module,exports){ +},{"./getIterator":73,"lodash/isArrayLike":1110,"lodash/keys":1118}],76:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15748,7 +8725,7 @@ function _asyncMap(eachfn, arr, iteratee, callback) { }); } module.exports = exports['default']; -},{"./wrapAsync":136,"lodash/noop":1291}],127:[function(require,module,exports){ +},{"./wrapAsync":86,"lodash/noop":1120}],77:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15759,7 +8736,7 @@ function notId(v) { return !v; } module.exports = exports["default"]; -},{}],128:[function(require,module,exports){ +},{}],78:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15775,7 +8752,7 @@ function once(fn) { }; } module.exports = exports["default"]; -},{}],129:[function(require,module,exports){ +},{}],79:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15791,7 +8768,7 @@ function onlyOnce(fn) { }; } module.exports = exports["default"]; -},{}],130:[function(require,module,exports){ +},{}],80:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -15834,7 +8811,7 @@ function _parallel(eachfn, tasks, callback) { }); } module.exports = exports['default']; -},{"./slice":134,"./wrapAsync":136,"lodash/isArrayLike":1281,"lodash/noop":1291}],131:[function(require,module,exports){ +},{"./slice":84,"./wrapAsync":86,"lodash/isArrayLike":1110,"lodash/noop":1120}],81:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16039,7 +9016,7 @@ function queue(worker, concurrency, payload) { return q; } module.exports = exports['default']; -},{"./DoublyLinkedList":114,"./onlyOnce":129,"./setImmediate":133,"./wrapAsync":136,"lodash/_baseIndexOf":1227,"lodash/isArray":1280,"lodash/noop":1291}],132:[function(require,module,exports){ +},{"./DoublyLinkedList":64,"./onlyOnce":79,"./setImmediate":83,"./wrapAsync":86,"lodash/_baseIndexOf":1056,"lodash/isArray":1109,"lodash/noop":1120}],82:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16061,7 +9038,7 @@ function reject(eachfn, arr, iteratee, callback) { }, callback); } module.exports = exports['default']; -},{"./filter":121}],133:[function(require,module,exports){ +},{"./filter":71}],83:[function(require,module,exports){ (function (process,setImmediate){ 'use strict'; @@ -16106,7 +9083,7 @@ if (hasSetImmediate) { exports.default = wrap(_defer); }).call(this,require('_process'),require("timers").setImmediate) -},{"./slice":134,"_process":1438,"timers":1749}],134:[function(require,module,exports){ +},{"./slice":84,"_process":1258,"timers":1500}],84:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -16123,7 +9100,7 @@ function slice(arrayLike, start) { return newArr; } module.exports = exports["default"]; -},{}],135:[function(require,module,exports){ +},{}],85:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -16136,7 +9113,7 @@ function _withoutIndex(iteratee) { }; } module.exports = exports["default"]; -},{}],136:[function(require,module,exports){ +},{}],86:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16162,7 +9139,7 @@ function wrapAsync(asyncFn) { exports.default = wrapAsync; exports.isAsync = isAsync; -},{"../asyncify":103}],137:[function(require,module,exports){ +},{"../asyncify":53}],87:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16217,7 +9194,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)(_map2.default); module.exports = exports['default']; -},{"./internal/doParallel":118,"./internal/map":126}],138:[function(require,module,exports){ +},{"./internal/doParallel":68,"./internal/map":76}],88:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16255,7 +9232,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallelLimit2.default)(_map2.default); module.exports = exports['default']; -},{"./internal/doParallelLimit":119,"./internal/map":126}],139:[function(require,module,exports){ +},{"./internal/doParallelLimit":69,"./internal/map":76}],89:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16292,7 +9269,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doLimit2.default)(_mapLimit2.default, 1); module.exports = exports['default']; -},{"./internal/doLimit":117,"./mapLimit":138}],140:[function(require,module,exports){ +},{"./internal/doLimit":67,"./mapLimit":88}],90:[function(require,module,exports){ (function (process,setImmediate){ 'use strict'; @@ -16346,7 +9323,7 @@ if (_setImmediate.hasNextTick) { exports.default = (0, _setImmediate.wrap)(_defer); module.exports = exports['default']; }).call(this,require('_process'),require("timers").setImmediate) -},{"./internal/setImmediate":133,"_process":1438,"timers":1749}],141:[function(require,module,exports){ +},{"./internal/setImmediate":83,"_process":1258,"timers":1500}],91:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16437,7 +9414,7 @@ function parallelLimit(tasks, callback) { (0, _parallel2.default)(_eachOf2.default, tasks, callback); } module.exports = exports['default']; -},{"./eachOf":108,"./internal/parallel":130}],142:[function(require,module,exports){ +},{"./eachOf":58,"./internal/parallel":80}],92:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16568,7 +9545,7 @@ module.exports = exports['default']; * console.log('finished processing bar'); * }); */ -},{"./internal/queue":131,"./internal/wrapAsync":136}],143:[function(require,module,exports){ +},{"./internal/queue":81,"./internal/wrapAsync":86}],93:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16614,7 +9591,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)(_reject2.default); module.exports = exports['default']; -},{"./internal/doParallel":118,"./internal/reject":132}],144:[function(require,module,exports){ +},{"./internal/doParallel":68,"./internal/reject":82}],94:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16771,7 +9748,7 @@ function retry(opts, task, callback) { retryAttempt(); } module.exports = exports['default']; -},{"./internal/wrapAsync":136,"lodash/constant":1275,"lodash/noop":1291}],145:[function(require,module,exports){ +},{"./internal/wrapAsync":86,"lodash/constant":1104,"lodash/noop":1120}],95:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16857,7 +9834,7 @@ function series(tasks, callback) { (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); } module.exports = exports['default']; -},{"./eachOfSeries":110,"./internal/parallel":130}],146:[function(require,module,exports){ +},{"./eachOfSeries":60,"./internal/parallel":80}],96:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16903,7 +9880,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = _setImmediate2.default; module.exports = exports['default']; -},{"./internal/setImmediate":133}],147:[function(require,module,exports){ +},{"./internal/setImmediate":83}],97:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -16956,7 +9933,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); module.exports = exports['default']; -},{"./internal/createTester":116,"./internal/doParallel":118,"lodash/identity":1278}],148:[function(require,module,exports){ +},{"./internal/createTester":66,"./internal/doParallel":68,"lodash/identity":1107}],98:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17000,7 +9977,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); module.exports = exports['default']; -},{"./internal/createTester":116,"./internal/doParallelLimit":119,"lodash/identity":1278}],149:[function(require,module,exports){ +},{"./internal/createTester":66,"./internal/doParallelLimit":69,"lodash/identity":1107}],99:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17039,7 +10016,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); module.exports = exports['default']; -},{"./internal/doLimit":117,"./someLimit":148}],150:[function(require,module,exports){ +},{"./internal/doLimit":67,"./someLimit":98}],100:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17129,7 +10106,7 @@ function timeout(asyncFn, milliseconds, info) { }); } module.exports = exports['default']; -},{"./internal/initialParams":124,"./internal/wrapAsync":136}],151:[function(require,module,exports){ +},{"./internal/initialParams":74,"./internal/wrapAsync":86}],101:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17211,7 +10188,7 @@ function tryEach(tasks, callback) { }); } module.exports = exports['default']; -},{"./eachSeries":111,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/noop":1291}],152:[function(require,module,exports){ +},{"./eachSeries":61,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/noop":1120}],102:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17325,7 +10302,7 @@ module.exports = exports['default']; * callback(null, 'done'); * } */ -},{"./internal/once":128,"./internal/onlyOnce":129,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/isArray":1280,"lodash/noop":1291}],153:[function(require,module,exports){ +},{"./internal/once":78,"./internal/onlyOnce":79,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/isArray":1109,"lodash/noop":1120}],103:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -17398,655 +10375,7 @@ function whilst(test, iteratee, callback) { _iteratee(next); } module.exports = exports['default']; -},{"./internal/onlyOnce":129,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/noop":1291}],154:[function(require,module,exports){ - -/*! - * 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. - */ - -/** - * Module dependencies. - */ - -var crypto = require('crypto') - , parse = require('url').parse - ; - -/** - * Valid keys. - */ - -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 - */ - -function authorization (options) { - return 'AWS ' + options.key + ':' + sign(options) -} - -module.exports = authorization -module.exports.authorization = authorization - -/** - * Simple HMAC-SHA1 Wrapper - * - * @param {Object} options - * @return {String} - * @api private - */ - -function hmacSha1 (options) { - return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') -} - -module.exports.hmacSha1 = hmacSha1 - -/** - * Create a base64 sha1 HMAC for `options`. - * - * @param {Object} options - * @return {String} - * @api private - */ - -function sign (options) { - options.message = stringToSign(options) - return hmacSha1(options) -} -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 - */ - -function signQuery (options) { - options.message = queryStringToSign(options) - return hmacSha1(options) -} -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 - */ - -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') -} -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 - */ - -function queryStringToSign (options){ - return 'GET\n\n\n' + options.date + '\n' + options.resource -} -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 - */ - -function canonicalizeHeaders (headers) { - var buf = [] - , fields = Object.keys(headers) - ; - 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) - } - return buf.sort().join('\n') -} -module.exports.canonicalizeHeaders = canonicalizeHeaders - -/** - * Perform the following: - * - * - ignore non sub-resources - * - sort lexicographically - * - * @param {String} resource - * @return {String} - * @api private - */ - -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('&') : '') -} -module.exports.canonicalizeResource = canonicalizeResource - -},{"crypto":236,"url":1769}],155:[function(require,module,exports){ -(function (process,Buffer){ -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 - -function hmac(key, string, encoding) { - return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) -} - -function hash(string, encoding) { - return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) -} - -// This function assumes the string has already been percent encoded -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] } -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 - if (this.service === 'email') this.service = 'ses' - - if (!request.method && request.body) - request.method = 'POST' - - 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 - } - if (!request.hostname && !request.host) - request.hostname = headers.Host || headers.host - - this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' -} - -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 - if (hostParts[1] === 'es') - hostParts = hostParts.reverse() - - return hostParts -} - -// http://docs.aws.amazon.com/general/latest/gr/rande.html -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 -} - -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' -} - -RequestSigner.prototype.prepareRequest = function() { - this.parsePath() - - var request = this.request, headers = request.headers, query - - 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() - } - - delete headers.Authorization - delete headers.authorization - } -} - -RequestSigner.prototype.sign = function() { - if (!this.parsedPath) this.prepareRequest() - - if (this.request.signQuery) { - this.parsedPath.query['X-Amz-Signature'] = this.signature() - } else { - this.request.headers.Authorization = this.authHeader() - } - - this.request.path = this.formatPath() - - return this.request -} - -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 - if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) - } - return this.datetime -} - -RequestSigner.prototype.getDate = function() { - return this.getDateTime().substr(0, 8) -} - -RequestSigner.prototype.authHeader = function() { - return [ - 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), - 'SignedHeaders=' + this.signedHeaders(), - 'Signature=' + this.signature(), - ].join(', ') -} - -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) - 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) - } - return hmac(kCredentials, this.stringToSign(), 'hex') -} - -RequestSigner.prototype.stringToSign = function() { - return [ - 'AWS4-HMAC-SHA256', - this.getDateTime(), - this.credentialString(), - hash(this.canonicalString(), 'hex'), - ].join('\n') -} - -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 - - 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') - } - - 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 - }, {}))) - } - 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))) - } - return path - }, []).join('/') - if (pathStr[0] !== '/') pathStr = '/' + pathStr - if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') - } - - return [ - this.request.method || 'GET', - pathStr, - queryStr, - this.canonicalHeaders() + '\n', - this.signedHeaders(), - bodyHash, - ].join('\n') -} - -RequestSigner.prototype.canonicalHeaders = function() { - var headers = this.request.headers - function trimAll(header) { - return header.toString().trim().replace(/\s+/g, ' ') - } - 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') -} - -RequestSigner.prototype.signedHeaders = function() { - return Object.keys(this.request.headers) - .map(function(key) { return key.toLowerCase() }) - .sort() - .join(';') -} - -RequestSigner.prototype.credentialString = function() { - return [ - this.getDate(), - this.region, - this.service, - 'aws4_request', - ].join('/') -} - -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, - } -} - -RequestSigner.prototype.parsePath = function() { - var path = this.request.path || '/', - queryIx = path.indexOf('?'), - query = null - - 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 - if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { - path = path.split('/').map(function(piece) { - return encodeURIComponent(decodeURIComponent(piece)) - }).join('/') - } - - this.parsedPath = { - path: path, - query: query, - } -} - -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 - if (query[''] != null) delete query[''] - - return path + '?' + encodeRfc3986(querystring.stringify(query)) -} - -aws4.RequestSigner = RequestSigner - -aws4.sign = function(request, credentials) { - return new RequestSigner(request, credentials).sign() -} - -}).call(this,require('_process'),require("buffer").Buffer) -},{"./lru":156,"_process":1438,"buffer":217,"crypto":236,"querystring":1547,"url":1769}],156:[function(require,module,exports){ -module.exports = function(size) { - return new LruCache(size) -} - -function LruCache(size) { - this.capacity = size | 0 - this.map = Object.create(null) - this.list = new DoublyLinkedList() -} - -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 (node != null) { - node.val = val - } else { - if (!this.capacity) this.prune() - if (!this.capacity) return false - node = new DoublyLinkedNode(key, val) - this.map[key] = node - this.capacity-- - } - this.used(node) - return true -} - -LruCache.prototype.used = function(node) { - this.list.moveToFront(node) -} - -LruCache.prototype.prune = function() { - var node = this.list.pop() - if (node != null) { - delete this.map[node.key] - this.capacity++ - } -} - - -function DoublyLinkedList() { - this.firstNode = null - this.lastNode = null -} - -DoublyLinkedList.prototype.moveToFront = function(node) { - if (this.firstNode == node) return - - this.remove(node) - - 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 - } -} - -DoublyLinkedList.prototype.pop = function() { - var lastNode = this.lastNode - if (lastNode != null) { - this.remove(lastNode) - } - return lastNode -} - -DoublyLinkedList.prototype.remove = function(node) { - if (this.firstNode == node) { - this.firstNode = node.next - } else if (node.prev != null) { - node.prev.next = node.next - } - if (this.lastNode == node) { - this.lastNode = node.prev - } else if (node.next != null) { - node.next.prev = node.prev - } -} - - -function DoublyLinkedNode(key, val) { - this.key = key - this.val = val - this.prev = null - this.next = null -} - -},{}],157:[function(require,module,exports){ +},{"./internal/onlyOnce":79,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/noop":1120}],104:[function(require,module,exports){ /** * Expose `Backoff`. @@ -18133,7 +10462,7 @@ Backoff.prototype.setJitter = function(jitter){ }; -},{}],158:[function(require,module,exports){ +},{}],105:[function(require,module,exports){ 'use strict' // base-x encoding / decoding // Copyright (c) 2018 base-x contributors @@ -18255,7 +10584,7 @@ function base (ALPHABET) { } module.exports = base -},{"safe-buffer":1593}],159:[function(require,module,exports){ +},{"safe-buffer":1371}],106:[function(require,module,exports){ var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' var RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV' var CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' @@ -18313,7 +10642,7 @@ module.exports = function base32Encode (buffer, variant, options) { return output } -},{}],160:[function(require,module,exports){ +},{}],107:[function(require,module,exports){ "use strict"; /** @@ -18627,7 +10956,7 @@ exports.crockford = crockford; exports.rfc4648 = rfc4648; exports.base32hex = base32hex; -},{}],161:[function(require,module,exports){ +},{}],108:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer @@ -18696,7 +11025,7 @@ exports.base32hex = base32hex; }; })(); -},{}],162:[function(require,module,exports){ +},{}],109:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -18764,8 +11093,7 @@ function toByteArray (b64) { ? validLen - 4 : validLen - var i - for (i = 0; i < len; i += 4) { + for (var i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | @@ -18850,565 +11178,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],163:[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. - * - * Credit for the actual porting work goes to: - * Devi Mandiri - */ - -/* - * 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. - */ - -/* - * 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. - */ - -/* - * 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 - -var BLF_J = 0; - -var Blowfish = function() { - 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]); -}; - -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]]); -}; - -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - 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 t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; - -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]; - 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]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; - -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; -}; - -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); - } - BLF_J = 0; - - 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]; - } - } -}; - -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; - - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - - 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]; - } - - 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]; - } - } - BLF_J = 0; -}; - -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; - -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; - -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; - -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" - - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } - - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); - - 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]; - } -}; - -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); - - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; - - crypto_hash_sha512(sha2pass, pass, passlen); - - 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); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; - - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } - - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } - - return 0; -}; - -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf -}; - -},{"tweetnacl":1762}],164:[function(require,module,exports){ +},{}],110:[function(require,module,exports){ ;(function (globalObject) { 'use strict'; @@ -22312,7 +14082,7 @@ module.exports = { } })(this); -},{}],165:[function(require,module,exports){ +},{}],111:[function(require,module,exports){ // 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 @@ -22427,7 +14197,427 @@ module.exports = { encode: encode } -},{"safe-buffer":1593}],166:[function(require,module,exports){ +},{"safe-buffer":1371}],112:[function(require,module,exports){ +(function (Buffer){ +'use strict' +var DuplexStream = require('readable-stream').Duplex + , util = require('util') + +function BufferList (callback) { + if (!(this instanceof BufferList)) + return new BufferList(callback) + + this._bufs = [] + this.length = 0 + + if (typeof callback == 'function') { + this._callback = callback + + var piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) + + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + } else { + this.append(callback) + } + + DuplexStream.call(this) +} + + +util.inherits(BufferList, DuplexStream) + + +BufferList.prototype._offset = function _offset (offset) { + var tot = 0, i = 0, _t + if (offset === 0) return [ 0, 0 ] + for (; i < this._bufs.length; i++) { + _t = tot + this._bufs[i].length + if (offset < _t || i == this._bufs.length - 1) { + return [ i, offset - tot ] + } + tot = _t + } +} + +BufferList.prototype._reverseOffset = function (blOffset) { + var bufferId = blOffset[0] + var offset = blOffset[1] + for (var i = 0; i < bufferId; i++) { + offset += this._bufs[i].length + } + return offset +} + +BufferList.prototype.append = function append (buf) { + var i = 0 + + if (Buffer.isBuffer(buf)) { + this._appendBuffer(buf) + } else if (Array.isArray(buf)) { + for (; i < buf.length; i++) + this.append(buf[i]) + } else if (buf instanceof BufferList) { + // unwrap argument into individual BufferLists + for (; i < buf._bufs.length; i++) + this.append(buf._bufs[i]) + } else if (buf != null) { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf == 'number') + buf = buf.toString() + + this._appendBuffer(Buffer.from(buf)) + } + + return this +} + + +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} + + +BufferList.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) + + if (typeof callback == 'function') + callback() +} + + +BufferList.prototype._read = function _read (size) { + if (!this.length) + return this.push(null) + + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} + + +BufferList.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) + + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} + + +BufferList.prototype.get = function get (index) { + if (index > this.length || index < 0) { + return undefined + } + var offset = this._offset(index) + return this._bufs[offset[0]][offset[1]] +} + + +BufferList.prototype.slice = function slice (start, end) { + if (typeof start == 'number' && start < 0) + start += this.length + if (typeof end == 'number' && end < 0) + end += this.length + return this.copy(null, 0, start, end) +} + + +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart != 'number' || srcStart < 0) + srcStart = 0 + if (typeof srcEnd != 'number' || srcEnd > this.length) + srcEnd = this.length + if (srcStart >= this.length) + return dst || Buffer.alloc(0) + if (srcEnd <= 0) + return dst || Buffer.alloc(0) + + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i + + // copy/slice everything + if (srcStart === 0 && srcEnd == this.length) { + if (!copy) { // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } + + // copy, need to copy individual buffers + for (i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } + + return dst + } + + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } + + if (!copy) // a slice, we need something to copy in to + dst = Buffer.allocUnsafe(len) + + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + break + } + + bufoff += l + bytes -= l + + if (start) + start = 0 + } + + return dst +} + +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = typeof end !== 'number' ? this.length : end + + if (start < 0) + start += this.length + if (end < 0) + end += this.length + + if (start === end) { + return new BufferList() + } + var startOffset = this._offset(start) + , endOffset = this._offset(end) + , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + + if (endOffset[1] == 0) + buffers.pop() + else + buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) + + if (startOffset[1] != 0) + buffers[0] = buffers[0].slice(startOffset[1]) + + return new BufferList(buffers) +} + +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} + +BufferList.prototype.consume = function consume (bytes) { + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break + } + } + return this +} + + +BufferList.prototype.duplicate = function duplicate () { + var i = 0 + , copy = new BufferList() + + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) + + return copy +} + + +BufferList.prototype._destroy = function _destroy (err, cb) { + this._bufs.length = 0 + this.length = 0 + cb(err) +} + + +BufferList.prototype.indexOf = function (search, offset, encoding) { + if (encoding === undefined && typeof offset === 'string') { + encoding = offset + offset = undefined + } + if (typeof search === 'function' || Array.isArray(search)) { + throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') + } else if (typeof search === 'number') { + search = Buffer.from([search]) + } else if (typeof search === 'string') { + search = Buffer.from(search, encoding) + } else if (search instanceof BufferList) { + search = search.slice() + } else if (!Buffer.isBuffer(search)) { + search = Buffer.from(search) + } + + offset = Number(offset || 0) + if (isNaN(offset)) { + offset = 0 + } + + if (offset < 0) { + offset = this.length + offset + } + + if (offset < 0) { + offset = 0 + } + + if (search.length === 0) { + return offset > this.length ? this.length : offset + } + + var blOffset = this._offset(offset) + var blIndex = blOffset[0] // index of which internal buffer we're working on + var buffOffset = blOffset[1] // offset of the internal buffer we're working on + + // scan over each buffer + for (blIndex; blIndex < this._bufs.length; blIndex++) { + var buff = this._bufs[blIndex] + while(buffOffset < buff.length) { + var availableWindow = buff.length - buffOffset + if (availableWindow >= search.length) { + var nativeSearchResult = buff.indexOf(search, buffOffset) + if (nativeSearchResult !== -1) { + return this._reverseOffset([blIndex, nativeSearchResult]) + } + buffOffset = buff.length - search.length + 1 // end of native search window + } else { + var revOffset = this._reverseOffset([blIndex, buffOffset]) + if (this._match(revOffset, search)) { + return revOffset + } + buffOffset++ + } + } + buffOffset = 0 + } + return -1 +} + +BufferList.prototype._match = function(offset, search) { + if (this.length - offset < search.length) { + return false + } + for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { + if(this.get(offset + searchOffset) !== search[searchOffset]){ + return false + } + } + return true +} + + +;(function () { + var methods = { + 'readDoubleBE' : 8 + , 'readDoubleLE' : 8 + , 'readFloatBE' : 4 + , 'readFloatLE' : 4 + , 'readInt32BE' : 4 + , 'readInt32LE' : 4 + , 'readUInt32BE' : 4 + , 'readUInt32LE' : 4 + , 'readInt16BE' : 2 + , 'readInt16LE' : 2 + , 'readUInt16BE' : 2 + , 'readUInt16LE' : 2 + , 'readInt8' : 1 + , 'readUInt8' : 1 + , 'readIntBE' : null + , 'readIntLE' : null + , 'readUIntBE' : null + , 'readUIntLE' : null + } + + for (var m in methods) { + (function (m) { + if (methods[m] === null) { + BufferList.prototype[m] = function (offset, byteLength) { + return this.slice(offset, offset + byteLength)[m](0, byteLength) + } + } + else { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) + } + } + }(m)) + } +}()) + + +module.exports = BufferList + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"readable-stream":127,"util":1512}],113:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],114:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],115:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":117,"./_stream_writable":119,"_process":1258,"dup":38,"inherits":317}],116:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":118,"dup":39,"inherits":317}],117:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":113,"../experimentalWarning":114,"./_stream_duplex":115,"./internal/streams/async_iterator":120,"./internal/streams/buffer_list":121,"./internal/streams/destroy":122,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":129,"util":146}],118:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":113,"./_stream_duplex":115,"dup":41,"inherits":317}],119:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":113,"./_stream_duplex":115,"./internal/streams/destroy":122,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],120:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":123,"_process":1258,"dup":43}],121:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],122:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],123:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":113,"dup":46}],124:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":113,"./end-of-stream":123,"dup":47}],125:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":113,"dup":48}],126:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],127:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":115,"./lib/_stream_passthrough.js":116,"./lib/_stream_readable.js":117,"./lib/_stream_transform.js":118,"./lib/_stream_writable.js":119,"./lib/internal/streams/end-of-stream.js":123,"./lib/internal/streams/pipeline.js":124,"dup":50}],128:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],129:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":128}],130:[function(require,module,exports){ // Blake2B in pure Javascript // Adapted from the reference implementation in RFC7693 // Ported to Javascript by DC - https://github.com/dcposch @@ -22702,7 +14892,7 @@ module.exports = { blake2bFinal: blake2bFinal } -},{"./util":169}],167:[function(require,module,exports){ +},{"./util":133}],131:[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 @@ -22894,7 +15084,7 @@ module.exports = { blake2sFinal: blake2sFinal } -},{"./util":169}],168:[function(require,module,exports){ +},{"./util":133}],132:[function(require,module,exports){ var b2b = require('./blake2b') var b2s = require('./blake2s') @@ -22911,7 +15101,7 @@ module.exports = { blake2sFinal: b2s.blake2sFinal } -},{"./blake2b":166,"./blake2s":167}],169:[function(require,module,exports){ +},{"./blake2b":130,"./blake2s":131}],133:[function(require,module,exports){ (function (Buffer){ var ERROR_MSG_INPUT = 'Input must be an string, Buffer or Uint8Array' @@ -22996,7 +15186,7 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],170:[function(require,module,exports){ +},{"buffer":181}],134:[function(require,module,exports){ /** * Create a blob builder even when vendor prefixes exist */ @@ -23004,7 +15194,7 @@ module.exports = { var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : - typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : + typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : false; /** @@ -23098,7 +15288,7 @@ module.exports = (function() { } })(); -},{}],171:[function(require,module,exports){ +},{}],135:[function(require,module,exports){ (function (module, exports) { 'use strict'; @@ -26527,7 +18717,7 @@ module.exports = (function() { }; })(typeof module === 'undefined' || module, this); -},{"buffer":182}],172:[function(require,module,exports){ +},{"buffer":146}],136:[function(require,module,exports){ 'use strict' const Bignumber = require('bignumber.js').BigNumber @@ -26602,7 +18792,7 @@ exports.PARENT = { UTF8_STRING: 5 } -},{"bignumber.js":164}],173:[function(require,module,exports){ +},{"bignumber.js":110}],137:[function(require,module,exports){ module.exports = function decodeAsm (stdlib, foreign, buffer) { 'use asm' @@ -27939,7 +20129,7 @@ module.exports = function decodeAsm (stdlib, foreign, buffer) { } } -},{}],174:[function(require,module,exports){ +},{}],138:[function(require,module,exports){ (function (global,Buffer){ 'use strict' @@ -28564,7 +20754,7 @@ Decoder.decodeFirst = Decoder.decode module.exports = Decoder }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./constants":172,"./decoder.asm":173,"./simple":178,"./tagged":179,"./utils":180,"bignumber.js":164,"buffer":217,"ieee754":451,"iso-url":802}],175:[function(require,module,exports){ +},{"./constants":136,"./decoder.asm":137,"./simple":142,"./tagged":143,"./utils":144,"bignumber.js":110,"buffer":181,"ieee754":315,"iso-url":641}],139:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -28747,7 +20937,7 @@ function collectObject (val) { } }).call(this,require("buffer").Buffer) -},{"./decoder":174,"./utils":180,"buffer":217}],176:[function(require,module,exports){ +},{"./decoder":138,"./utils":144,"buffer":181}],140:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -29271,7 +21461,7 @@ class Encoder { module.exports = Encoder }).call(this,require("buffer").Buffer) -},{"./constants":172,"./utils":180,"bignumber.js":164,"buffer":217,"iso-url":802}],177:[function(require,module,exports){ +},{"./constants":136,"./utils":144,"bignumber.js":110,"buffer":181,"iso-url":641}],141:[function(require,module,exports){ 'use strict' // exports.Commented = require('./commented') @@ -29295,7 +21485,7 @@ exports.leveldb = { name: 'cbor' } -},{"./decoder":174,"./diagnose":175,"./encoder":176,"./simple":178,"./tagged":179}],178:[function(require,module,exports){ +},{"./decoder":138,"./diagnose":139,"./encoder":140,"./simple":142,"./tagged":143}],142:[function(require,module,exports){ 'use strict' const constants = require('./constants') @@ -29404,7 +21594,7 @@ class Simple { module.exports = Simple -},{"./constants":172}],179:[function(require,module,exports){ +},{"./constants":136}],143:[function(require,module,exports){ 'use strict' /** @@ -29484,7 +21674,7 @@ class Tagged { module.exports = Tagged -},{}],180:[function(require,module,exports){ +},{}],144:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -29661,7 +21851,7 @@ exports.nextPowerOf2 = (n) => { } }).call(this,require("buffer").Buffer) -},{"./constants":172,"bignumber.js":164,"buffer":217}],181:[function(require,module,exports){ +},{"./constants":136,"bignumber.js":110,"buffer":181}],145:[function(require,module,exports){ var r; module.exports = function rand(len) { @@ -29728,9 +21918,9 @@ if (typeof self === 'object') { } } -},{"crypto":182}],182:[function(require,module,exports){ +},{"crypto":146}],146:[function(require,module,exports){ -},{}],183:[function(require,module,exports){ +},{}],147:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js @@ -29960,7 +22150,7 @@ AES.prototype.scrub = function () { module.exports.AES = AES -},{"safe-buffer":1593}],184:[function(require,module,exports){ +},{"safe-buffer":1371}],148:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') @@ -30079,7 +22269,7 @@ StreamCipher.prototype.setAAD = function setAAD (buf) { module.exports = StreamCipher -},{"./aes":183,"./ghash":188,"./incr32":189,"buffer-xor":216,"cipher-base":223,"inherits":453,"safe-buffer":1593}],185:[function(require,module,exports){ +},{"./aes":147,"./ghash":152,"./incr32":153,"buffer-xor":180,"cipher-base":186,"inherits":317,"safe-buffer":1371}],149:[function(require,module,exports){ var ciphers = require('./encrypter') var deciphers = require('./decrypter') var modes = require('./modes/list.json') @@ -30094,7 +22284,7 @@ exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers -},{"./decrypter":186,"./encrypter":187,"./modes/list.json":197}],186:[function(require,module,exports){ +},{"./decrypter":150,"./encrypter":151,"./modes/list.json":161}],150:[function(require,module,exports){ var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var MODES = require('./modes') @@ -30220,7 +22410,7 @@ function createDecipher (suite, password) { exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv -},{"./aes":183,"./authCipher":184,"./modes":196,"./streamCipher":199,"cipher-base":223,"evp_bytestokey":371,"inherits":453,"safe-buffer":1593}],187:[function(require,module,exports){ +},{"./aes":147,"./authCipher":148,"./modes":160,"./streamCipher":163,"cipher-base":186,"evp_bytestokey":273,"inherits":317,"safe-buffer":1371}],151:[function(require,module,exports){ var MODES = require('./modes') var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer @@ -30336,7 +22526,7 @@ function createCipher (suite, password) { exports.createCipheriv = createCipheriv exports.createCipher = createCipher -},{"./aes":183,"./authCipher":184,"./modes":196,"./streamCipher":199,"cipher-base":223,"evp_bytestokey":371,"inherits":453,"safe-buffer":1593}],188:[function(require,module,exports){ +},{"./aes":147,"./authCipher":148,"./modes":160,"./streamCipher":163,"cipher-base":186,"evp_bytestokey":273,"inherits":317,"safe-buffer":1371}],152:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var ZEROES = Buffer.alloc(16, 0) @@ -30427,7 +22617,7 @@ GHASH.prototype.final = function (abl, bl) { module.exports = GHASH -},{"safe-buffer":1593}],189:[function(require,module,exports){ +},{"safe-buffer":1371}],153:[function(require,module,exports){ function incr32 (iv) { var len = iv.length var item @@ -30444,7 +22634,7 @@ function incr32 (iv) { } module.exports = incr32 -},{}],190:[function(require,module,exports){ +},{}],154:[function(require,module,exports){ var xor = require('buffer-xor') exports.encrypt = function (self, block) { @@ -30463,7 +22653,7 @@ exports.decrypt = function (self, block) { return xor(out, pad) } -},{"buffer-xor":216}],191:[function(require,module,exports){ +},{"buffer-xor":180}],155:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var xor = require('buffer-xor') @@ -30498,7 +22688,7 @@ exports.encrypt = function (self, data, decrypt) { return out } -},{"buffer-xor":216,"safe-buffer":1593}],192:[function(require,module,exports){ +},{"buffer-xor":180,"safe-buffer":1371}],156:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { @@ -30542,7 +22732,7 @@ exports.encrypt = function (self, chunk, decrypt) { return out } -},{"safe-buffer":1593}],193:[function(require,module,exports){ +},{"safe-buffer":1371}],157:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { @@ -30569,7 +22759,7 @@ exports.encrypt = function (self, chunk, decrypt) { return out } -},{"safe-buffer":1593}],194:[function(require,module,exports){ +},{"safe-buffer":1371}],158:[function(require,module,exports){ var xor = require('buffer-xor') var Buffer = require('safe-buffer').Buffer var incr32 = require('../incr32') @@ -30601,7 +22791,7 @@ exports.encrypt = function (self, chunk) { return xor(chunk, pad) } -},{"../incr32":189,"buffer-xor":216,"safe-buffer":1593}],195:[function(require,module,exports){ +},{"../incr32":153,"buffer-xor":180,"safe-buffer":1371}],159:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } @@ -30610,7 +22800,7 @@ exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } -},{}],196:[function(require,module,exports){ +},{}],160:[function(require,module,exports){ var modeModules = { ECB: require('./ecb'), CBC: require('./cbc'), @@ -30630,7 +22820,7 @@ for (var key in modes) { module.exports = modes -},{"./cbc":190,"./cfb":191,"./cfb1":192,"./cfb8":193,"./ctr":194,"./ecb":195,"./list.json":197,"./ofb":198}],197:[function(require,module,exports){ +},{"./cbc":154,"./cfb":155,"./cfb1":156,"./cfb8":157,"./ctr":158,"./ecb":159,"./list.json":161,"./ofb":162}],161:[function(require,module,exports){ module.exports={ "aes-128-ecb": { "cipher": "AES", @@ -30823,7 +23013,7 @@ module.exports={ } } -},{}],198:[function(require,module,exports){ +},{}],162:[function(require,module,exports){ (function (Buffer){ var xor = require('buffer-xor') @@ -30843,7 +23033,7 @@ exports.encrypt = function (self, chunk) { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"buffer-xor":216}],199:[function(require,module,exports){ +},{"buffer":181,"buffer-xor":180}],163:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') @@ -30872,7 +23062,7 @@ StreamCipher.prototype._final = function () { module.exports = StreamCipher -},{"./aes":183,"cipher-base":223,"inherits":453,"safe-buffer":1593}],200:[function(require,module,exports){ +},{"./aes":147,"cipher-base":186,"inherits":317,"safe-buffer":1371}],164:[function(require,module,exports){ var DES = require('browserify-des') var aes = require('browserify-aes/browser') var aesModes = require('browserify-aes/modes') @@ -30941,7 +23131,7 @@ exports.createDecipher = exports.Decipher = createDecipher exports.createDecipheriv = exports.Decipheriv = createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers -},{"browserify-aes/browser":185,"browserify-aes/modes":196,"browserify-des":201,"browserify-des/modes":202,"evp_bytestokey":371}],201:[function(require,module,exports){ +},{"browserify-aes/browser":149,"browserify-aes/modes":160,"browserify-des":165,"browserify-des/modes":166,"evp_bytestokey":273}],165:[function(require,module,exports){ var CipherBase = require('cipher-base') var des = require('des.js') var inherits = require('inherits') @@ -30993,7 +23183,7 @@ DES.prototype._final = function () { return Buffer.from(this._des.final()) } -},{"cipher-base":223,"des.js":265,"inherits":453,"safe-buffer":1593}],202:[function(require,module,exports){ +},{"cipher-base":186,"des.js":222,"inherits":317,"safe-buffer":1371}],166:[function(require,module,exports){ exports['des-ecb'] = { key: 8, iv: 0 @@ -31019,7 +23209,7 @@ exports['des-ede'] = { iv: 0 } -},{}],203:[function(require,module,exports){ +},{}],167:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); var randomBytes = require('randombytes'); @@ -31063,10 +23253,10 @@ function getr(priv) { } }).call(this,require("buffer").Buffer) -},{"bn.js":171,"buffer":217,"randombytes":1552}],204:[function(require,module,exports){ +},{"bn.js":135,"buffer":181,"randombytes":1366}],168:[function(require,module,exports){ module.exports = require('./browser/algorithms.json') -},{"./browser/algorithms.json":205}],205:[function(require,module,exports){ +},{"./browser/algorithms.json":169}],169:[function(require,module,exports){ module.exports={ "sha224WithRSAEncryption": { "sign": "rsa", @@ -31220,7 +23410,7 @@ module.exports={ } } -},{}],206:[function(require,module,exports){ +},{}],170:[function(require,module,exports){ module.exports={ "1.3.132.0.10": "secp256k1", "1.3.132.0.33": "p224", @@ -31230,7 +23420,7 @@ module.exports={ "1.3.132.0.35": "p521" } -},{}],207:[function(require,module,exports){ +},{}],171:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash') var stream = require('stream') @@ -31325,7 +23515,7 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"./algorithms.json":205,"./sign":208,"./verify":209,"buffer":217,"create-hash":232,"inherits":453,"stream":1715}],208:[function(require,module,exports){ +},{"./algorithms.json":169,"./sign":172,"./verify":173,"buffer":181,"create-hash":193,"inherits":317,"stream":1459}],172:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var createHmac = require('create-hmac') @@ -31474,7 +23664,7 @@ module.exports.getKey = getKey module.exports.makeKey = makeKey }).call(this,require("buffer").Buffer) -},{"./curves.json":206,"bn.js":171,"browserify-rsa":203,"buffer":217,"create-hmac":234,"elliptic":282,"parse-asn1":1421}],209:[function(require,module,exports){ +},{"./curves.json":170,"bn.js":135,"browserify-rsa":167,"buffer":181,"create-hmac":195,"elliptic":236,"parse-asn1":1243}],173:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var BN = require('bn.js') @@ -31561,1043 +23751,558 @@ function checkValue (b, q) { module.exports = verify }).call(this,require("buffer").Buffer) -},{"./curves.json":206,"bn.js":171,"buffer":217,"elliptic":282,"parse-asn1":1421}],210:[function(require,module,exports){ -(function (process,Buffer){ -'use strict'; -/* eslint camelcase: "off" */ - -var assert = require('assert'); - -var Zstream = require('pako/lib/zlib/zstream'); -var zlib_deflate = require('pako/lib/zlib/deflate.js'); -var zlib_inflate = require('pako/lib/zlib/inflate.js'); -var constants = require('pako/lib/zlib/constants'); - -for (var key in constants) { - exports[key] = constants[key]; -} - -// zlib modes -exports.NONE = 0; -exports.DEFLATE = 1; -exports.INFLATE = 2; -exports.GZIP = 3; -exports.GUNZIP = 4; -exports.DEFLATERAW = 5; -exports.INFLATERAW = 6; -exports.UNZIP = 7; - -var GZIP_HEADER_ID1 = 0x1f; -var GZIP_HEADER_ID2 = 0x8b; - -/** - * Emulate Node's zlib C++ layer for use by the JS layer in index.js - */ -function Zlib(mode) { - if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { - throw new TypeError('Bad argument'); - } - - this.dictionary = null; - this.err = 0; - this.flush = 0; - this.init_done = false; - this.level = 0; - this.memLevel = 0; - this.mode = mode; - this.strategy = 0; - this.windowBits = 0; - this.write_in_progress = false; - this.pending_close = false; - this.gzip_id_bytes_read = 0; -} - -Zlib.prototype.close = function () { - if (this.write_in_progress) { - this.pending_close = true; - return; - } - - this.pending_close = false; - - assert(this.init_done, 'close before init'); - assert(this.mode <= exports.UNZIP); - - if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { - zlib_deflate.deflateEnd(this.strm); - } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { - zlib_inflate.inflateEnd(this.strm); - } - - this.mode = exports.NONE; - - this.dictionary = null; -}; - -Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { - return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); -}; - -Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { - return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); -}; - -Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { - assert.equal(arguments.length, 8); - - assert(this.init_done, 'write before init'); - assert(this.mode !== exports.NONE, 'already finalized'); - assert.equal(false, this.write_in_progress, 'write already in progress'); - assert.equal(false, this.pending_close, 'close is pending'); - - this.write_in_progress = true; - - assert.equal(false, flush === undefined, 'must provide flush value'); - - this.write_in_progress = true; - - if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { - throw new Error('Invalid flush value'); - } - - if (input == null) { - input = Buffer.alloc(0); - in_len = 0; - in_off = 0; - } - - this.strm.avail_in = in_len; - this.strm.input = input; - this.strm.next_in = in_off; - this.strm.avail_out = out_len; - this.strm.output = out; - this.strm.next_out = out_off; - this.flush = flush; - - if (!async) { - // sync version - this._process(); - - if (this._checkError()) { - return this._afterSync(); - } - return; - } - - // async version - var self = this; - process.nextTick(function () { - self._process(); - self._after(); - }); - - return this; -}; - -Zlib.prototype._afterSync = function () { - var avail_out = this.strm.avail_out; - var avail_in = this.strm.avail_in; - - this.write_in_progress = false; - - return [avail_in, avail_out]; -}; - -Zlib.prototype._process = function () { - var next_expected_header_byte = null; - - // If the avail_out is left at 0, then it means that it ran out - // of room. If there was avail_out left over, then it means - // that all of the input was consumed. - switch (this.mode) { - case exports.DEFLATE: - case exports.GZIP: - case exports.DEFLATERAW: - this.err = zlib_deflate.deflate(this.strm, this.flush); - break; - case exports.UNZIP: - if (this.strm.avail_in > 0) { - next_expected_header_byte = this.strm.next_in; - } - - switch (this.gzip_id_bytes_read) { - case 0: - if (next_expected_header_byte === null) { - break; - } - - if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { - this.gzip_id_bytes_read = 1; - next_expected_header_byte++; - - if (this.strm.avail_in === 1) { - // The only available byte was already read. - break; - } - } else { - this.mode = exports.INFLATE; - break; - } - - // fallthrough - case 1: - if (next_expected_header_byte === null) { - break; - } - - if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { - this.gzip_id_bytes_read = 2; - this.mode = exports.GUNZIP; - } else { - // There is no actual difference between INFLATE and INFLATERAW - // (after initialization). - this.mode = exports.INFLATE; - } - - break; - default: - throw new Error('invalid number of gzip magic number bytes read'); - } - - // fallthrough - case exports.INFLATE: - case exports.GUNZIP: - case exports.INFLATERAW: - this.err = zlib_inflate.inflate(this.strm, this.flush - - // If data was encoded with dictionary - );if (this.err === exports.Z_NEED_DICT && this.dictionary) { - // Load it - this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); - if (this.err === exports.Z_OK) { - // And try to decode again - this.err = zlib_inflate.inflate(this.strm, this.flush); - } else if (this.err === exports.Z_DATA_ERROR) { - // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. - // Make it possible for After() to tell a bad dictionary from bad - // input. - this.err = exports.Z_NEED_DICT; - } - } - while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { - // Bytes remain in input buffer. Perhaps this is another compressed - // member in the same archive, or just trailing garbage. - // Trailing zero bytes are okay, though, since they are frequently - // used for padding. - - this.reset(); - this.err = zlib_inflate.inflate(this.strm, this.flush); - } - break; - default: - throw new Error('Unknown mode ' + this.mode); - } -}; - -Zlib.prototype._checkError = function () { - // Acceptable error states depend on the type of zlib stream. - switch (this.err) { - case exports.Z_OK: - case exports.Z_BUF_ERROR: - if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { - this._error('unexpected end of file'); - return false; - } - break; - case exports.Z_STREAM_END: - // normal statuses, not fatal - break; - case exports.Z_NEED_DICT: - if (this.dictionary == null) { - this._error('Missing dictionary'); - } else { - this._error('Bad dictionary'); - } - return false; - default: - // something else. - this._error('Zlib error'); - return false; - } - - return true; -}; - -Zlib.prototype._after = function () { - if (!this._checkError()) { - return; - } - - var avail_out = this.strm.avail_out; - var avail_in = this.strm.avail_in; - - this.write_in_progress = false; - - // call the write() cb - this.callback(avail_in, avail_out); - - if (this.pending_close) { - this.close(); - } -}; - -Zlib.prototype._error = function (message) { - if (this.strm.msg) { - message = this.strm.msg; - } - this.onerror(message, this.err - - // no hope of rescue. - );this.write_in_progress = false; - if (this.pending_close) { - this.close(); - } -}; - -Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { - assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); - - assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); - assert(level >= -1 && level <= 9, 'invalid compression level'); - - assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); - - assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); - - this._init(level, windowBits, memLevel, strategy, dictionary); - this._setDictionary(); -}; - -Zlib.prototype.params = function () { - throw new Error('deflateParams Not supported'); -}; - -Zlib.prototype.reset = function () { - this._reset(); - this._setDictionary(); -}; - -Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { - this.level = level; - this.windowBits = windowBits; - this.memLevel = memLevel; - this.strategy = strategy; - - this.flush = exports.Z_NO_FLUSH; - - this.err = exports.Z_OK; - - if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { - this.windowBits += 16; - } - - if (this.mode === exports.UNZIP) { - this.windowBits += 32; - } - - if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { - this.windowBits = -1 * this.windowBits; - } - - this.strm = new Zstream(); - - switch (this.mode) { - case exports.DEFLATE: - case exports.GZIP: - case exports.DEFLATERAW: - this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); - break; - case exports.INFLATE: - case exports.GUNZIP: - case exports.INFLATERAW: - case exports.UNZIP: - this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); - break; - default: - throw new Error('Unknown mode ' + this.mode); - } - - if (this.err !== exports.Z_OK) { - this._error('Init error'); - } - - this.dictionary = dictionary; - - this.write_in_progress = false; - this.init_done = true; -}; - -Zlib.prototype._setDictionary = function () { - if (this.dictionary == null) { - return; - } - - this.err = exports.Z_OK; - - switch (this.mode) { - case exports.DEFLATE: - case exports.DEFLATERAW: - this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); - break; - default: - break; - } - - if (this.err !== exports.Z_OK) { - this._error('Failed to set dictionary'); - } -}; - -Zlib.prototype._reset = function () { - this.err = exports.Z_OK; - - switch (this.mode) { - case exports.DEFLATE: - case exports.DEFLATERAW: - case exports.GZIP: - this.err = zlib_deflate.deflateReset(this.strm); - break; - case exports.INFLATE: - case exports.INFLATERAW: - case exports.GUNZIP: - this.err = zlib_inflate.inflateReset(this.strm); - break; - default: - break; - } - - if (this.err !== exports.Z_OK) { - this._error('Failed to reset stream'); - } -}; - -exports.Zlib = Zlib; -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":1438,"assert":78,"buffer":217,"pako/lib/zlib/constants":1408,"pako/lib/zlib/deflate.js":1410,"pako/lib/zlib/inflate.js":1412,"pako/lib/zlib/zstream":1416}],211:[function(require,module,exports){ -(function (process){ -'use strict'; - -var Buffer = require('buffer').Buffer; -var Transform = require('stream').Transform; -var binding = require('./binding'); -var util = require('util'); -var assert = require('assert').ok; -var kMaxLength = require('buffer').kMaxLength; -var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; - -// zlib doesn't provide these, so kludge them in following the same -// const naming scheme zlib uses. -binding.Z_MIN_WINDOWBITS = 8; -binding.Z_MAX_WINDOWBITS = 15; -binding.Z_DEFAULT_WINDOWBITS = 15; - -// fewer than 64 bytes per chunk is stupid. -// technically it could work with as few as 8, but even 64 bytes -// is absurdly low. Usually a MB or more is best. -binding.Z_MIN_CHUNK = 64; -binding.Z_MAX_CHUNK = Infinity; -binding.Z_DEFAULT_CHUNK = 16 * 1024; - -binding.Z_MIN_MEMLEVEL = 1; -binding.Z_MAX_MEMLEVEL = 9; -binding.Z_DEFAULT_MEMLEVEL = 8; - -binding.Z_MIN_LEVEL = -1; -binding.Z_MAX_LEVEL = 9; -binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; - -// expose all the zlib constants -var bkeys = Object.keys(binding); -for (var bk = 0; bk < bkeys.length; bk++) { - var bkey = bkeys[bk]; - if (bkey.match(/^Z/)) { - Object.defineProperty(exports, bkey, { - enumerable: true, value: binding[bkey], writable: false - }); - } -} - -// translation table for return codes. -var codes = { - Z_OK: binding.Z_OK, - Z_STREAM_END: binding.Z_STREAM_END, - Z_NEED_DICT: binding.Z_NEED_DICT, - Z_ERRNO: binding.Z_ERRNO, - Z_STREAM_ERROR: binding.Z_STREAM_ERROR, - Z_DATA_ERROR: binding.Z_DATA_ERROR, - Z_MEM_ERROR: binding.Z_MEM_ERROR, - Z_BUF_ERROR: binding.Z_BUF_ERROR, - Z_VERSION_ERROR: binding.Z_VERSION_ERROR -}; - -var ckeys = Object.keys(codes); -for (var ck = 0; ck < ckeys.length; ck++) { - var ckey = ckeys[ck]; - codes[codes[ckey]] = ckey; -} - -Object.defineProperty(exports, 'codes', { - enumerable: true, value: Object.freeze(codes), writable: false -}); - -exports.Deflate = Deflate; -exports.Inflate = Inflate; -exports.Gzip = Gzip; -exports.Gunzip = Gunzip; -exports.DeflateRaw = DeflateRaw; -exports.InflateRaw = InflateRaw; -exports.Unzip = Unzip; - -exports.createDeflate = function (o) { - return new Deflate(o); -}; - -exports.createInflate = function (o) { - return new Inflate(o); -}; - -exports.createDeflateRaw = function (o) { - return new DeflateRaw(o); -}; - -exports.createInflateRaw = function (o) { - return new InflateRaw(o); -}; - -exports.createGzip = function (o) { - return new Gzip(o); -}; - -exports.createGunzip = function (o) { - return new Gunzip(o); -}; - -exports.createUnzip = function (o) { - return new Unzip(o); -}; - -// Convenience methods. -// compress/decompress a string or buffer in one step. -exports.deflate = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new Deflate(opts), buffer, callback); -}; - -exports.deflateSync = function (buffer, opts) { - return zlibBufferSync(new Deflate(opts), buffer); -}; - -exports.gzip = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new Gzip(opts), buffer, callback); -}; - -exports.gzipSync = function (buffer, opts) { - return zlibBufferSync(new Gzip(opts), buffer); -}; - -exports.deflateRaw = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new DeflateRaw(opts), buffer, callback); -}; - -exports.deflateRawSync = function (buffer, opts) { - return zlibBufferSync(new DeflateRaw(opts), buffer); -}; - -exports.unzip = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new Unzip(opts), buffer, callback); -}; - -exports.unzipSync = function (buffer, opts) { - return zlibBufferSync(new Unzip(opts), buffer); -}; - -exports.inflate = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new Inflate(opts), buffer, callback); -}; - -exports.inflateSync = function (buffer, opts) { - return zlibBufferSync(new Inflate(opts), buffer); -}; - -exports.gunzip = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new Gunzip(opts), buffer, callback); -}; - -exports.gunzipSync = function (buffer, opts) { - return zlibBufferSync(new Gunzip(opts), buffer); -}; - -exports.inflateRaw = function (buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new InflateRaw(opts), buffer, callback); -}; - -exports.inflateRawSync = function (buffer, opts) { - return zlibBufferSync(new InflateRaw(opts), buffer); -}; - -function zlibBuffer(engine, buffer, callback) { - var buffers = []; - var nread = 0; - - engine.on('error', onError); - engine.on('end', onEnd); - - engine.end(buffer); - flow(); - - function flow() { - var chunk; - while (null !== (chunk = engine.read())) { - buffers.push(chunk); - nread += chunk.length; - } - engine.once('readable', flow); - } - - function onError(err) { - engine.removeListener('end', onEnd); - engine.removeListener('readable', flow); - callback(err); - } - - function onEnd() { - var buf; - var err = null; - - if (nread >= kMaxLength) { - err = new RangeError(kRangeErrorMessage); - } else { - buf = Buffer.concat(buffers, nread); - } - - buffers = []; - engine.close(); - callback(err, buf); - } -} - -function zlibBufferSync(engine, buffer) { - if (typeof buffer === 'string') buffer = Buffer.from(buffer); - - if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); - - var flushFlag = engine._finishFlushFlag; - - return engine._processChunk(buffer, flushFlag); -} - -// generic zlib -// minimal 2-byte header -function Deflate(opts) { - if (!(this instanceof Deflate)) return new Deflate(opts); - Zlib.call(this, opts, binding.DEFLATE); -} - -function Inflate(opts) { - if (!(this instanceof Inflate)) return new Inflate(opts); - Zlib.call(this, opts, binding.INFLATE); -} - -// gzip - bigger header, same deflate compression -function Gzip(opts) { - if (!(this instanceof Gzip)) return new Gzip(opts); - Zlib.call(this, opts, binding.GZIP); -} - -function Gunzip(opts) { - if (!(this instanceof Gunzip)) return new Gunzip(opts); - Zlib.call(this, opts, binding.GUNZIP); -} - -// raw - no header -function DeflateRaw(opts) { - if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); - Zlib.call(this, opts, binding.DEFLATERAW); -} - -function InflateRaw(opts) { - if (!(this instanceof InflateRaw)) return new InflateRaw(opts); - Zlib.call(this, opts, binding.INFLATERAW); -} - -// auto-detect header. -function Unzip(opts) { - if (!(this instanceof Unzip)) return new Unzip(opts); - Zlib.call(this, opts, binding.UNZIP); -} - -function isValidFlushFlag(flag) { - return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; -} - -// the Zlib class they all inherit from -// This thing manages the queue of requests, and returns -// true or false if there is anything in the queue when -// you call the .write() method. - -function Zlib(opts, mode) { - var _this = this; - - this._opts = opts = opts || {}; - this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; - - Transform.call(this, opts); - - if (opts.flush && !isValidFlushFlag(opts.flush)) { - throw new Error('Invalid flush flag: ' + opts.flush); - } - if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { - throw new Error('Invalid flush flag: ' + opts.finishFlush); - } - - this._flushFlag = opts.flush || binding.Z_NO_FLUSH; - this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; - - if (opts.chunkSize) { - if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { - throw new Error('Invalid chunk size: ' + opts.chunkSize); - } - } - - if (opts.windowBits) { - if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { - throw new Error('Invalid windowBits: ' + opts.windowBits); - } - } - - if (opts.level) { - if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { - throw new Error('Invalid compression level: ' + opts.level); - } - } - - if (opts.memLevel) { - if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { - throw new Error('Invalid memLevel: ' + opts.memLevel); - } - } - - if (opts.strategy) { - if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { - throw new Error('Invalid strategy: ' + opts.strategy); - } - } - - if (opts.dictionary) { - if (!Buffer.isBuffer(opts.dictionary)) { - throw new Error('Invalid dictionary: it should be a Buffer instance'); - } - } - - this._handle = new binding.Zlib(mode); - - var self = this; - this._hadError = false; - this._handle.onerror = function (message, errno) { - // there is no way to cleanly recover. - // continuing only obscures problems. - _close(self); - self._hadError = true; - - var error = new Error(message); - error.errno = errno; - error.code = exports.codes[errno]; - self.emit('error', error); - }; - - var level = exports.Z_DEFAULT_COMPRESSION; - if (typeof opts.level === 'number') level = opts.level; - - var strategy = exports.Z_DEFAULT_STRATEGY; - if (typeof opts.strategy === 'number') strategy = opts.strategy; - - this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); - - this._buffer = Buffer.allocUnsafe(this._chunkSize); - this._offset = 0; - this._level = level; - this._strategy = strategy; - - this.once('end', this.close); - - Object.defineProperty(this, '_closed', { - get: function () { - return !_this._handle; - }, - configurable: true, - enumerable: true - }); -} - -util.inherits(Zlib, Transform); - -Zlib.prototype.params = function (level, strategy, callback) { - if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { - throw new RangeError('Invalid compression level: ' + level); - } - if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { - throw new TypeError('Invalid strategy: ' + strategy); - } - - if (this._level !== level || this._strategy !== strategy) { - var self = this; - this.flush(binding.Z_SYNC_FLUSH, function () { - assert(self._handle, 'zlib binding closed'); - self._handle.params(level, strategy); - if (!self._hadError) { - self._level = level; - self._strategy = strategy; - if (callback) callback(); - } - }); - } else { - process.nextTick(callback); - } -}; - -Zlib.prototype.reset = function () { - assert(this._handle, 'zlib binding closed'); - return this._handle.reset(); -}; - -// This is the _flush function called by the transform class, -// internally, when the last chunk has been written. -Zlib.prototype._flush = function (callback) { - this._transform(Buffer.alloc(0), '', callback); -}; - -Zlib.prototype.flush = function (kind, callback) { - var _this2 = this; - - var ws = this._writableState; - - if (typeof kind === 'function' || kind === undefined && !callback) { - callback = kind; - kind = binding.Z_FULL_FLUSH; - } - - if (ws.ended) { - if (callback) process.nextTick(callback); - } else if (ws.ending) { - if (callback) this.once('end', callback); - } else if (ws.needDrain) { - if (callback) { - this.once('drain', function () { - return _this2.flush(kind, callback); - }); - } - } else { - this._flushFlag = kind; - this.write(Buffer.alloc(0), '', callback); - } -}; - -Zlib.prototype.close = function (callback) { - _close(this, callback); - process.nextTick(emitCloseNT, this); -}; - -function _close(engine, callback) { - if (callback) process.nextTick(callback); - - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) return; - - engine._handle.close(); - engine._handle = null; -} - -function emitCloseNT(self) { - self.emit('close'); -} - -Zlib.prototype._transform = function (chunk, encoding, cb) { - var flushFlag; - var ws = this._writableState; - var ending = ws.ending || ws.ended; - var last = ending && (!chunk || ws.length === chunk.length); - - if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); - - if (!this._handle) return cb(new Error('zlib binding closed')); - - // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag - // (or whatever flag was provided using opts.finishFlush). - // If it's explicitly flushing at some other time, then we use - // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression - // goodness. - if (last) flushFlag = this._finishFlushFlag;else { - flushFlag = this._flushFlag; - // once we've flushed the last of the queue, stop flushing and - // go back to the normal behavior. - if (chunk.length >= ws.length) { - this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; - } - } - - this._processChunk(chunk, flushFlag, cb); -}; - -Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { - var availInBefore = chunk && chunk.length; - var availOutBefore = this._chunkSize - this._offset; - var inOff = 0; - - var self = this; - - var async = typeof cb === 'function'; - - if (!async) { - var buffers = []; - var nread = 0; - - var error; - this.on('error', function (er) { - error = er; - }); - - assert(this._handle, 'zlib binding closed'); - do { - var res = this._handle.writeSync(flushFlag, chunk, // in - inOff, // in_off - availInBefore, // in_len - this._buffer, // out - this._offset, //out_off - availOutBefore); // out_len - } while (!this._hadError && callback(res[0], res[1])); - - if (this._hadError) { - throw error; - } - - if (nread >= kMaxLength) { - _close(this); - throw new RangeError(kRangeErrorMessage); - } - - var buf = Buffer.concat(buffers, nread); - _close(this); - - return buf; - } - - assert(this._handle, 'zlib binding closed'); - var req = this._handle.write(flushFlag, chunk, // in - inOff, // in_off - availInBefore, // in_len - this._buffer, // out - this._offset, //out_off - availOutBefore); // out_len - - req.buffer = chunk; - req.callback = callback; - - function callback(availInAfter, availOutAfter) { - // When the callback is used in an async write, the callback's - // context is the `req` object that was created. The req object - // is === this._handle, and that's why it's important to null - // out the values after they are done being used. `this._handle` - // can stay in memory longer than the callback and buffer are needed. - if (this) { - this.buffer = null; - this.callback = null; - } - - if (self._hadError) return; - - var have = availOutBefore - availOutAfter; - assert(have >= 0, 'have should not go down'); - - if (have > 0) { - var out = self._buffer.slice(self._offset, self._offset + have); - self._offset += have; - // serve some output to the consumer. - if (async) { - self.push(out); - } else { - buffers.push(out); - nread += out.length; - } - } - - // exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || self._offset >= self._chunkSize) { - availOutBefore = self._chunkSize; - self._offset = 0; - self._buffer = Buffer.allocUnsafe(self._chunkSize); - } - - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += availInBefore - availInAfter; - availInBefore = availInAfter; - - if (!async) return true; - - var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); - newReq.callback = callback; // this same function - newReq.buffer = chunk; - return; - } - - if (!async) return false; - - // finished with the chunk. - cb(); - } -}; - -util.inherits(Deflate, Zlib); -util.inherits(Inflate, Zlib); -util.inherits(Gzip, Zlib); -util.inherits(Gunzip, Zlib); -util.inherits(DeflateRaw, Zlib); -util.inherits(InflateRaw, Zlib); -util.inherits(Unzip, Zlib); -}).call(this,require('_process')) -},{"./binding":210,"_process":1438,"assert":78,"buffer":217,"stream":1715,"util":1776}],212:[function(require,module,exports){ -arguments[4][182][0].apply(exports,arguments) -},{"dup":182}],213:[function(require,module,exports){ +},{"./curves.json":170,"bn.js":135,"buffer":181,"elliptic":236,"parse-asn1":1243}],174:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],175:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":176}],176:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],177:[function(require,module,exports){ var basex = require('base-x') var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' module.exports = basex(ALPHABET) -},{"base-x":158}],214:[function(require,module,exports){ +},{"base-x":105}],178:[function(require,module,exports){ var bufferIndexOf = require('buffer-indexof'); module.exports = function(buf,splitBuf,includeDelim){ - + var search = -1 , lines = [] , move = includeDelim?splitBuf.length:0 @@ -32609,7 +24314,7 @@ module.exports = function(buf,splitBuf,includeDelim){ } lines.push(buf); - + return lines; } @@ -32617,10 +24322,10 @@ module.exports = function(buf,splitBuf,includeDelim){ -},{"buffer-indexof":215}],215:[function(require,module,exports){ +},{"buffer-indexof":179}],179:[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 */ { module.exports = KeyTransformDatastore -},{"pull-stream":1495}],240:[function(require,module,exports){ +},{"pull-stream":1311}],201:[function(require,module,exports){ /* @flow */ 'use strict' @@ -36689,7 +27835,7 @@ class MountDatastore /* :: */ { module.exports = MountDatastore -},{"./keytransform":239,"async/each":106,"interface-datastore":458,"pull-many":1476,"pull-stream":1495}],241:[function(require,module,exports){ +},{"./keytransform":200,"async/each":56,"interface-datastore":322,"pull-many":1293,"pull-stream":1311}],202:[function(require,module,exports){ /* @flow */ 'use strict' @@ -36745,7 +27891,7 @@ class NamespaceDatastore/* :: */ extends KeytransformDatastore /* :: */ { module.exports = TieredDatastore -},{"async/each":106,"async/whilst":153,"interface-datastore":458}],246:[function(require,module,exports){ +},{"async/each":56,"async/whilst":103,"interface-datastore":322}],207:[function(require,module,exports){ (function (Buffer){ /* @flow */ 'use strict' @@ -37437,7 +28583,7 @@ class LevelDatastore { module.exports = LevelDatastore }).call(this,require("buffer").Buffer) -},{"buffer":217,"encoding-down":298,"interface-datastore":458,"leveldown":862,"levelup":872,"pull-stream":1495}],247:[function(require,module,exports){ +},{"buffer":181,"encoding-down":252,"interface-datastore":322,"leveldown":700,"levelup":713,"pull-stream":1311}],208:[function(require,module,exports){ (function (process){ /* eslint-env browser */ @@ -37705,7 +28851,7 @@ formatters.j = function (v) { }; }).call(this,require('_process')) -},{"./common":248,"_process":1438}],248:[function(require,module,exports){ +},{"./common":209,"_process":1258}],209:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser @@ -37973,7 +29119,7 @@ function setup(env) { module.exports = setup; -},{"ms":250}],249:[function(require,module,exports){ +},{"ms":1136}],210:[function(require,module,exports){ 'use strict'; function createError(msg, code, props) { @@ -37997,171 +29143,7 @@ function createError(msg, code, props) { module.exports = createError; -},{}],250:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - -},{}],251:[function(require,module,exports){ +},{}],211:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -38469,7 +29451,7 @@ class DatastorePubsub { exports = module.exports = DatastorePubsub }).call(this,require("buffer").Buffer) -},{"./utils":252,"assert":78,"buffer":217,"debug":247,"err-code":249,"interface-datastore":458}],252:[function(require,module,exports){ +},{"./utils":212,"assert":26,"buffer":181,"debug":208,"err-code":210,"interface-datastore":322}],212:[function(require,module,exports){ 'use strict' const multibase = require('multibase') @@ -38502,38 +29484,28 @@ module.exports.topicToKey = (topic) => { return multibase.decode(key).toString() } -},{"err-code":249,"multibase":1322}],253:[function(require,module,exports){ +},{"err-code":210,"multibase":1148}],213:[function(require,module,exports){ (function (process){ +"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); } + +/* eslint-env browser */ + /** * 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(); - +exports.storage = localstorage(); /** * Colors. */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - +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']; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known @@ -38541,79 +29513,65 @@ exports.colors = [ * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ +// eslint-disable-next-line complexity 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') { + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; - } + } // Internet Explorer and Edge do not support colors. - // is webkit? http://stackoverflow.com/a/16459606/376773 + + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } // 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+)/)); + + + 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. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - /** * Colorize log arguments if enabled. * * @api public */ + function formatArgs(args) { - var useColors = this.useColors; + args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; + if (!this.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 + 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 + var index = 0; var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if (match === '%%') { + return; + } + index++; - if ('%c' === match) { - // we only are interested in the *last* %c + + if (match === '%c') { + // 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". @@ -38621,14 +29579,14 @@ function formatArgs(args) { * @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); -} +function log() { + var _console; + + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments); +} /** * Save `namespaces`. * @@ -38636,16 +29594,18 @@ function log() { * @api private */ + function save(namespaces) { try { - if (null == namespaces) { - exports.storage.removeItem('debug'); + if (namespaces) { + exports.storage.setItem('debug', namespaces); } else { - exports.storage.debug = namespaces; + exports.storage.removeItem('debug'); } - } catch(e) {} + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } } - /** * Load `namespaces`. * @@ -38653,26 +29613,23 @@ function save(namespaces) { * @api private */ + function load() { var r; - try { - r = exports.storage.debug; - } catch(e) {} + try { + r = exports.storage.getItem('debug'); + } catch (error) {} // Swallow + // XXX (@Qix-) should we be logging these? // 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; } return r; } - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - /** * Localstorage attempts to return the localstorage. * @@ -38684,314 +29641,285 @@ exports.enable(load()); * @api private */ + function localstorage() { try { - return window.localStorage; - } catch (e) {} + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = require('./common')(exports); +var formatters = module.exports.formatters; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + + }).call(this,require('_process')) -},{"./debug":254,"_process":1438}],254:[function(require,module,exports){ +},{"./common":214,"_process":1258}],214:[function(require,module,exports){ +"use strict"; /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. - * - * Expose `debug()` as the module. */ +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + Object.keys(env).forEach(function (key) { + createDebug[key] = env[key]; + }); + /** + * Active `debug` instances. + */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); + createDebug.instances = []; + /** + * The currently active debug mode names, and names to skip. + */ -/** - * The currently active debug mode names, and names to skip. - */ + createDebug.names = []; + createDebug.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". + */ -exports.names = []; -exports.skips = []; + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ -/** - * 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". - */ + function selectColor(namespace) { + var hash = 0; -exports.formatters = {}; + for (var i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + function createDebug(namespace) { + var prevTime; -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - 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; - - // 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]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // 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); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; + function debug() { + // Disabled? + if (!debug.enabled) { + return; } - return match; - }); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } + var self = debug; // Set `diff` timestamp - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); + var curr = Number(new Date()); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } // Apply any `formatters` transformations - return debug; -} -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + 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; + } -function enable(namespaces) { - exports.save(namespaces); + index++; + var formatter = createDebug.formatters[format]; - exports.names = []; - exports.skips = []; + if (typeof formatter === 'function') { + var val = args[index]; + match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + args.splice(index, 1); + index--; + } - 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 + '$')); + return match; + }); // Apply env-specific formatting (colors, etc.) + + createDebug.formatArgs.call(self, args); + var logFn = self.log || createDebug.log; + logFn.apply(self, args); } - } -} -/** - * Disable debug output. - * - * @api public - */ + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + // env-specific initialization logic for debug instances -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; + if (typeof createDebug.init === 'function') { + createDebug.init(debug); } + + createDebug.instances.push(debug); + return debug; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { + + function destroy() { + var index = createDebug.instances.indexOf(this); + + if (index !== -1) { + createDebug.instances.splice(index, 1); return true; } + + return false; } - return false; + + function extend(namespace, delimiter) { + return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + + + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.names = []; + createDebug.skips = []; + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + var instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + /** + * Disable debug output. + * + * @api public + */ + + + function disable() { + createDebug.enable(''); + } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + + + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + var i; + var len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + + + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + + return val; + } + + createDebug.enable(createDebug.load()); + return createDebug; } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ +module.exports = setup; -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} -},{"ms":1310}],255:[function(require,module,exports){ -'use strict'; -var token = '%[a-f0-9]{2}'; -var singleMatcher = new RegExp(token, 'gi'); -var multiMatcher = new RegExp('(' + token + ')+', 'gi'); - -function decodeComponents(components, split) { - try { - // Try to decode the entire string first - return decodeURIComponent(components.join('')); - } catch (err) { - // Do nothing - } - - if (components.length === 1) { - return components; - } - - split = split || 1; - - // Split the array in 2 parts - var left = components.slice(0, split); - var right = components.slice(split); - - return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); -} - -function decode(input) { - try { - return decodeURIComponent(input); - } catch (err) { - var tokens = input.match(singleMatcher); - - for (var i = 1; i < tokens.length; i++) { - input = decodeComponents(tokens, i).join(''); - - tokens = input.match(singleMatcher); - } - - return input; - } -} - -function customDecodeURIComponent(input) { - // Keep track of all the replacements and prefill the map with the `BOM` - var replaceMap = { - '%FE%FF': '\uFFFD\uFFFD', - '%FF%FE': '\uFFFD\uFFFD' - }; - - var match = multiMatcher.exec(input); - while (match) { - try { - // Decode as big chunks as possible - replaceMap[match[0]] = decodeURIComponent(match[0]); - } catch (err) { - var result = decode(match[0]); - - if (result !== match[0]) { - replaceMap[match[0]] = result; - } - } - - match = multiMatcher.exec(input); - } - - // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else - replaceMap['%C2'] = '\uFFFD'; - - var entries = Object.keys(replaceMap); - - for (var i = 0; i < entries.length; i++) { - // Replace all decoded components - var key = entries[i]; - input = input.replace(new RegExp(key, 'g'), replaceMap[key]); - } - - return input; -} - -module.exports = function (encodedURI) { - if (typeof encodedURI !== 'string') { - throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); - } - - try { - encodedURI = encodedURI.replace(/\+/g, ' '); - - // Try the built in decoder first - return decodeURIComponent(encodedURI); - } catch (err) { - // Fallback to a more advanced decoder - return customDecodeURIComponent(encodedURI); - } -}; - -},{}],256:[function(require,module,exports){ +},{"ms":1136}],215:[function(require,module,exports){ (function (Buffer){ /*! * @description Recursive object extending @@ -39145,12 +30073,12 @@ var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { }; }).call(this,require("buffer").Buffer) -},{"buffer":217}],257:[function(require,module,exports){ +},{"buffer":181}],216:[function(require,module,exports){ var AbstractIterator = require('abstract-leveldown').AbstractIterator var inherits = require('inherits') -function DeferredIterator (options) { - AbstractIterator.call(this, options) +function DeferredIterator (db, options) { + AbstractIterator.call(this, db) this._options = options this._iterator = null @@ -39184,7 +30112,7 @@ DeferredIterator.prototype.seek = function () { module.exports = DeferredIterator -},{"abstract-leveldown":262,"inherits":453}],258:[function(require,module,exports){ +},{"abstract-leveldown":6,"inherits":317}],217:[function(require,module,exports){ var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN var inherits = require('inherits') var DeferredIterator = require('./deferred-iterator') @@ -39192,7 +30120,16 @@ var deferrables = 'put get del batch clear'.split(' ') var optionalDeferrables = 'approximateSize compactRange'.split(' ') function DeferredLevelDOWN (db) { - AbstractLevelDOWN.call(this, '') + AbstractLevelDOWN.call(this, db.supports || {}) + + // TODO (future major): remove this fallback; db must have manifest that + // declares approximateSize and compactRange in additionalMethods. + optionalDeferrables.forEach(function (m) { + if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) { + this.supports.additionalMethods[m] = true + } + }, this) + this._db = db this._operations = [] closed(this) @@ -39238,11 +30175,9 @@ function open (self) { return this._db[m].apply(this._db, arguments) } }) - optionalDeferrables.forEach(function (m) { - if (typeof self._db[m] === 'function') { - self[m] = function () { - return this._db[m].apply(this._db, arguments) - } + Object.keys(self.supports.additionalMethods).forEach(function (m) { + self[m] = function () { + return this._db[m].apply(this._db, arguments) } }) } @@ -39253,15 +30188,13 @@ function closed (self) { this._operations.push({ method: m, args: arguments }) } }) - optionalDeferrables.forEach(function (m) { - if (typeof self._db[m] === 'function') { - self[m] = function () { - this._operations.push({ method: m, args: arguments }) - } + Object.keys(self.supports.additionalMethods).forEach(function (m) { + self[m] = function () { + this._operations.push({ method: m, args: arguments }) } }) self._iterator = function (options) { - var it = new DeferredIterator(options) + var it = new DeferredIterator(self, options) this._operations.push({ iterator: it }) return it } @@ -39278,326 +30211,7 @@ DeferredLevelDOWN.prototype._serializeValue = function (value) { module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator -},{"./deferred-iterator":257,"abstract-leveldown":262,"inherits":453}],259:[function(require,module,exports){ -arguments[4][3][0].apply(exports,arguments) -},{"dup":3}],260:[function(require,module,exports){ -arguments[4][4][0].apply(exports,arguments) -},{"_process":1438,"dup":4}],261:[function(require,module,exports){ -(function (Buffer,process){ -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(' ') - -function AbstractLevelDOWN () { - this.status = 'new' -} - -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - var oldStatus = this.status - - if (typeof options === 'function') callback = options - - 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() - }) -} - -AbstractLevelDOWN.prototype._open = function (options, callback) { - process.nextTick(callback) -} - -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() - }) -} - -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) -} - -AbstractLevelDOWN.prototype._get = function (key, options, callback) { - process.nextTick(function () { callback(new Error('NotFound')) }) -} - -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) -} - -AbstractLevelDOWN.prototype._put = function (key, value, options, callback) { - process.nextTick(callback) -} - -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) -} - -AbstractLevelDOWN.prototype._del = function (key, options, callback) { - process.nextTick(callback) -} - -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`')) - } - - var e = xtend(array[i]) - - 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) - 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) - } - - serialized[i] = e - } - - this._batch(serialized, options, callback) -} - -AbstractLevelDOWN.prototype._batch = function (array, options, callback) { - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.clear = function (options, callback) { - if (typeof options === 'function') { - callback = options - } else if (typeof callback !== 'function') { - throw new Error('clear() requires a callback argument') - } - - options = cleanRangeOptions(this, options) - options.reverse = !!options.reverse - options.limit = 'limit' in options ? options.limit : -1 - - this._clear(options, callback) -} - -AbstractLevelDOWN.prototype._clear = function (options, callback) { - // Avoid setupIteratorOptions, would serialize range options a second time. - options.keys = true - options.values = false - options.keyAsBuffer = true - options.valueAsBuffer = true - - var iterator = this._iterator(options) - var emptyOptions = {} - var self = this - - var next = function (err) { - if (err) { - return iterator.end(function () { - callback(err) - }) - } - - iterator.next(function (err, key) { - if (err) return next(err) - if (key === undefined) return iterator.end(callback) - - // This could be optimized by using a batch, but the default _clear - // is not meant to be fast. Implementations have more room to optimize - // if they override _clear. Note: using _del bypasses key serialization. - self._del(key, emptyOptions, next) - }) - } - - next() -} - -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 -} - -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) - } - - result[k] = opt - } - - return result -} - -function isRangeOption (k) { - return rangeOptions.indexOf(k) !== -1 -} - -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options !== 'object' || options === null) options = {} - options = this._setupIteratorOptions(options) - return this._iterator(options) -} - -AbstractLevelDOWN.prototype._iterator = function (options) { - return new AbstractIterator(this) -} - -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} - -AbstractLevelDOWN.prototype._serializeKey = function (key) { - return key -} - -AbstractLevelDOWN.prototype._serializeValue = function (value) { - return value -} - -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') - } -} - -AbstractLevelDOWN.prototype._checkValue = function (value) { - if (value === null || value === undefined) { - return new Error('value cannot be `null` or `undefined`') - } -} - -module.exports = AbstractLevelDOWN - -}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":766,"./abstract-chained-batch":259,"./abstract-iterator":260,"_process":1438,"xtend":1860}],262:[function(require,module,exports){ -arguments[4][6][0].apply(exports,arguments) -},{"./abstract-chained-batch":259,"./abstract-iterator":260,"./abstract-leveldown":261,"dup":6}],263:[function(require,module,exports){ +},{"./deferred-iterator":216,"abstract-leveldown":6,"inherits":317}],218:[function(require,module,exports){ 'use strict'; var keys = require('object-keys'); @@ -39657,116 +30271,184 @@ defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; -},{"object-keys":1390}],264:[function(require,module,exports){ -var Stream = require('stream').Stream; -var util = require('util'); +},{"object-keys":220}],219:[function(require,module,exports){ +'use strict'; -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; } -util.inherits(DelayedStream, Stream); +module.exports = keysShim; -DelayedStream.create = function(source, options) { - var delayedStream = new this(); +},{"./isArguments":221}],220:[function(require,module,exports){ +'use strict'; - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); - delayedStream.source = source; +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; +var originalKeys = Object.keys; - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } - - return delayedStream; +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; }; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); +module.exports = keysShim; -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); +},{"./implementation":219,"./isArguments":221}],221:[function(require,module,exports){ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; }; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } - - this.source.resume(); -}; - -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; - -DelayedStream.prototype.release = function() { - this._released = true; - - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; - -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; - -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } - - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } - - this._bufferedEvents.push(args); -}; - -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } - - if (this.dataSize <= this.maxDataSize) { - return; - } - - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; - -},{"stream":1715,"util":1776}],265:[function(require,module,exports){ +},{}],222:[function(require,module,exports){ 'use strict'; exports.utils = require('./des/utils'); @@ -39775,7 +30457,7 @@ exports.DES = require('./des/des'); exports.CBC = require('./des/cbc'); exports.EDE = require('./des/ede'); -},{"./des/cbc":266,"./des/cipher":267,"./des/des":268,"./des/ede":269,"./des/utils":270}],266:[function(require,module,exports){ +},{"./des/cbc":223,"./des/cipher":224,"./des/des":225,"./des/ede":226,"./des/utils":227}],223:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -39842,7 +30524,7 @@ proto._update = function _update(inp, inOff, out, outOff) { } }; -},{"inherits":453,"minimalistic-assert":1303}],267:[function(require,module,exports){ +},{"inherits":317,"minimalistic-assert":1129}],224:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -39985,7 +30667,7 @@ Cipher.prototype._finalDecrypt = function _finalDecrypt() { return this._unpad(out); }; -},{"minimalistic-assert":1303}],268:[function(require,module,exports){ +},{"minimalistic-assert":1129}],225:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -40130,7 +30812,7 @@ DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { utils.rip(l, r, out, off); }; -},{"../des":265,"inherits":453,"minimalistic-assert":1303}],269:[function(require,module,exports){ +},{"../des":222,"inherits":317,"minimalistic-assert":1129}],226:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -40187,7 +30869,7 @@ EDE.prototype._update = function _update(inp, inOff, out, outOff) { EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; -},{"../des":265,"inherits":453,"minimalistic-assert":1303}],270:[function(require,module,exports){ +},{"../des":222,"inherits":317,"minimalistic-assert":1129}],227:[function(require,module,exports){ 'use strict'; exports.readUInt32BE = function readUInt32BE(bytes, off) { @@ -40445,11 +31127,11 @@ exports.padSplit = function padSplit(num, size, group) { return out.join(' '); }; -},{}],271:[function(require,module,exports){ +},{}],228:[function(require,module,exports){ module.exports = false; -},{}],272:[function(require,module,exports){ +},{}],229:[function(require,module,exports){ (function (Buffer){ var generatePrime = require('./lib/generatePrime') var primes = require('./lib/primes.json') @@ -40495,7 +31177,7 @@ exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffi exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman }).call(this,require("buffer").Buffer) -},{"./lib/dh":273,"./lib/generatePrime":274,"./lib/primes.json":275,"buffer":217}],273:[function(require,module,exports){ +},{"./lib/dh":230,"./lib/generatePrime":231,"./lib/primes.json":232,"buffer":181}],230:[function(require,module,exports){ (function (Buffer){ var BN = require('bn.js'); var MillerRabin = require('miller-rabin'); @@ -40663,7 +31345,7 @@ function formatReturnValue(bn, enc) { } }).call(this,require("buffer").Buffer) -},{"./generatePrime":274,"bn.js":171,"buffer":217,"miller-rabin":1299,"randombytes":1552}],274:[function(require,module,exports){ +},{"./generatePrime":231,"bn.js":135,"buffer":181,"miller-rabin":1128,"randombytes":1366}],231:[function(require,module,exports){ var randomBytes = require('randombytes'); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; @@ -40770,7 +31452,7 @@ function findPrime(bits, gen) { } -},{"bn.js":171,"miller-rabin":1299,"randombytes":1552}],275:[function(require,module,exports){ +},{"bn.js":135,"miller-rabin":1128,"randombytes":1366}],232:[function(require,module,exports){ module.exports={ "modp1": { "gen": "02", @@ -40805,11 +31487,11 @@ module.exports={ "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } } -},{}],276:[function(require,module,exports){ +},{}],233:[function(require,module,exports){ !function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=function(t,n,e,i,o){for(n=n.split?n.split("."):n,i=0;i= len) ? hex : unstupid("0"+hex,len); -} - -exports.ECKey = function(curve, key, isPublic) -{ - var priv; - var c = curve(); - var n = c.getN(); - var bytes = Math.floor(n.bitLength()/8); - - if(key) - { - if(isPublic) - { - var curve = c.getCurve(); -// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format -// var y = key.slice(bytes+1); -// this.P = new ECPointFp(curve, -// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), -// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); - this.P = curve.decodePointHex(key.toString("hex")); - }else{ - if(key.length != bytes) return false; - priv = new BigInteger(key.toString("hex"), 16); - } - }else{ - var n1 = n.subtract(BigInteger.ONE); - var r = new BigInteger(crypto.randomBytes(n.bitLength())); - priv = r.mod(n1).add(BigInteger.ONE); - this.P = c.getG().multiply(priv); - } - if(this.P) - { -// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); -// this.PublicKey = Buffer.from("04"+pubhex,"hex"); - this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); - } - if(priv) - { - this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); - this.deriveSharedSecret = function(key) - { - if(!key || !key.P) return false; - var S = key.P.multiply(priv); - return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); - } - } -} - - -},{"./lib/ec.js":280,"./lib/sec.js":281,"crypto":236,"jsbn":825,"safer-buffer":1594}],280:[function(require,module,exports){ -// Basic Javascript Elliptic Curve implementation -// Ported loosely from BouncyCastle's Java EC code -// Only Fp curves implemented for now - -// Requires jsbn.js and jsbn2.js -var BigInteger = require('jsbn').BigInteger -var Barrett = BigInteger.prototype.Barrett - -// ---------------- -// ECFieldElementFp - -// constructor -function ECFieldElementFp(q,x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; -} - -function feFpEquals(other) { - if(other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); -} - -function feFpToBigInteger() { - return this.x; -} - -function feFpNegate() { - return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); -} - -function feFpAdd(b) { - return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); -} - -function feFpSubtract(b) { - return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); -} - -function feFpMultiply(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); -} - -function feFpSquare() { - return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); -} - -function feFpDivide(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); -} - -ECFieldElementFp.prototype.equals = feFpEquals; -ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; -ECFieldElementFp.prototype.negate = feFpNegate; -ECFieldElementFp.prototype.add = feFpAdd; -ECFieldElementFp.prototype.subtract = feFpSubtract; -ECFieldElementFp.prototype.multiply = feFpMultiply; -ECFieldElementFp.prototype.square = feFpSquare; -ECFieldElementFp.prototype.divide = feFpDivide; - -// ---------------- -// ECPointFp - -// constructor -function ECPointFp(curve,x,y,z) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if(z == null) { - this.z = BigInteger.ONE; - } - else { - this.z = z; - } - this.zinv = null; - //TODO: compression flag -} - -function pointFpGetX() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} - -function pointFpGetY() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} - -function pointFpEquals(other) { - if(other == this) return true; - if(this.isInfinity()) return other.isInfinity(); - if(other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); - if(!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); - return v.equals(BigInteger.ZERO); -} - -function pointFpIsInfinity() { - if((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); -} - -function pointFpNegate() { - return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); -} - -function pointFpAdd(b) { - if(this.isInfinity()) return b; - if(b.isInfinity()) return this; - - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); - - if(BigInteger.ZERO.equals(v)) { - if(BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } - - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); - - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); - - // 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.q); - // 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.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} - -function pointFpTwice() { - if(this.isInfinity()) return this; - if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if(!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); - } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // 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.q); - // 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.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} - -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -function pointFpMultiply(k) { - if(this.isInfinity()) return this; - if(k.signum() == 0) return this.curve.getInfinity(); - - var e = k; - var h = e.multiply(new BigInteger("3")); - - var neg = this.negate(); - var R = this; - - var i; - for(i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); - - var hBit = h.testBit(i); - var eBit = e.testBit(i); - - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } - - return R; -} - -// Compute this*j + x*k (simultaneous multiplication) -function pointFpMultiplyTwo(j,x,k) { - var i; - if(j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; - - var R = this.curve.getInfinity(); - var both = this.add(x); - while(i >= 0) { - R = R.twice(); - if(j.testBit(i)) { - if(k.testBit(i)) { - R = R.add(both); - } - else { - R = R.add(this); - } - } - else { - if(k.testBit(i)) { - R = R.add(x); - } - } - --i; - } - - return R; -} - -ECPointFp.prototype.getX = pointFpGetX; -ECPointFp.prototype.getY = pointFpGetY; -ECPointFp.prototype.equals = pointFpEquals; -ECPointFp.prototype.isInfinity = pointFpIsInfinity; -ECPointFp.prototype.negate = pointFpNegate; -ECPointFp.prototype.add = pointFpAdd; -ECPointFp.prototype.twice = pointFpTwice; -ECPointFp.prototype.multiply = pointFpMultiply; -ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; - -// ---------------- -// ECCurveFp - -// constructor -function ECCurveFp(q,a,b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ECPointFp(this, null, null); - this.reducer = new Barrett(this.q); -} - -function curveFpGetQ() { - return this.q; -} - -function curveFpGetA() { - return this.a; -} - -function curveFpGetB() { - return this.b; -} - -function curveFpEquals(other) { - if(other == this) return true; - return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); -} - -function curveFpGetInfinity() { - return this.infinity; -} - -function curveFpFromBigInteger(x) { - return new ECFieldElementFp(this.q, x); -} - -function curveReduce(x) { - this.reducer.reduce(x); -} - -// for now, work with hex strings because they're easier in JS -function curveFpDecodePointHex(s) { - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - case 3: - // point compression not supported yet - return null; - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); - - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - - default: // unsupported - return null; - } -} - -function curveFpEncodePointHex(p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; -} - -ECCurveFp.prototype.getQ = curveFpGetQ; -ECCurveFp.prototype.getA = curveFpGetA; -ECCurveFp.prototype.getB = curveFpGetB; -ECCurveFp.prototype.equals = curveFpEquals; -ECCurveFp.prototype.getInfinity = curveFpGetInfinity; -ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; -ECCurveFp.prototype.reduce = curveReduce; -//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; -ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; - -// from: https://github.com/kaielvin/jsbn-ec-point-compression -ECCurveFp.prototype.decodePointHex = function(s) -{ - var yIsEven; - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - yIsEven = false; - case 3: - if(yIsEven == undefined) yIsEven = true; - var len = s.length - 2; - var xHex = s.substr(2, len); - var x = this.fromBigInteger(new BigInteger(xHex,16)); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); - - if (beta == null) throw "Invalid point compression"; - - var betaValue = beta.toBigInteger(); - if (betaValue.testBit(0) != yIsEven) - { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ECPointFp(this,x,beta); - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); - - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - - default: // unsupported - return null; - } -} -ECCurveFp.prototype.encodeCompressedPointHex = function(p) -{ - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) - xHex = "0" + xHex; - var yPrefix; - if(p.getY().toBigInteger().isEven()) yPrefix = "02"; - else yPrefix = "03"; - - return yPrefix + xHex; -} - - -ECFieldElementFp.prototype.getR = function() -{ - if(this.r != undefined) return this.r; - - this.r = null; - var bitLength = this.q.bitLength(); - if (bitLength > 128) - { - var firstWord = this.q.shiftRight(bitLength - 64); - if (firstWord.intValue() == -1) - { - this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); - } - } - return this.r; -} -ECFieldElementFp.prototype.modMult = function(x1,x2) -{ - return this.modReduce(x1.multiply(x2)); -} -ECFieldElementFp.prototype.modReduce = function(x) -{ - if (this.getR() != null) - { - var qLen = q.bitLength(); - while (x.bitLength() > (qLen + 1)) - { - var u = x.shiftRight(qLen); - var v = x.subtract(u.shiftLeft(qLen)); - if (!this.getR().equals(BigInteger.ONE)) - { - u = u.multiply(this.getR()); - } - x = u.add(v); - } - while (x.compareTo(q) >= 0) - { - x = x.subtract(q); - } - } - else - { - x = x.mod(q); - } - return x; -} -ECFieldElementFp.prototype.sqrt = function() -{ - if (!this.q.testBit(0)) throw "unsupported"; - - // p mod 4 == 3 - if (this.q.testBit(1)) - { - var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); - return z.square().equals(this) ? z : null; - } - - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); - - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) - { - return null; - } - - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); - - var Q = this.x; - var fourQ = modDouble(modDouble(Q)); - - var U, V; - do - { - var P; - do - { - P = new BigInteger(this.q.bitLength(), new SecureRandom()); - } - while (P.compareTo(this.q) >= 0 - || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); - - var result = this.lucasSequence(P, Q, k); - U = result[0]; - V = result[1]; - - if (this.modMult(V, V).equals(fourQ)) - { - // Integer division by 2, mod q - if (V.testBit(0)) - { - V = V.add(q); - } - - V = V.shiftRight(1); - - return new ECFieldElementFp(q,V); - } - } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); - - return null; -} -ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) -{ - var n = k.bitLength(); - var s = k.getLowestSetBit(); - - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; - - for (var j = n - 1; j >= s + 1; --j) - { - Ql = this.modMult(Ql, Qh); - - if (k.testBit(j)) - { - Qh = this.modMult(Ql, Q); - Uh = this.modMult(Uh, Vh); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); - } - else - { - Qh = Ql; - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - } - } - - Ql = this.modMult(Ql, Qh); - Qh = this.modMult(Ql, Q); - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Ql = this.modMult(Ql, Qh); - - for (var j = 1; j <= s; ++j) - { - Uh = this.modMult(Uh, Vl); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - Ql = this.modMult(Ql, Ql); - } - - return [ Uh, Vl ]; -} - -var exports = { - ECCurveFp: ECCurveFp, - ECPointFp: ECPointFp, - ECFieldElementFp: ECFieldElementFp -} - -module.exports = exports - -},{"jsbn":825}],281:[function(require,module,exports){ -// Named EC curves - -// Requires ec.js, jsbn.js, and jsbn2.js -var BigInteger = require('jsbn').BigInteger -var ECCurveFp = require('./ec.js').ECCurveFp - - -// ---------------- -// X9ECParameters - -// constructor -function X9ECParameters(curve,g,n,h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; -} - -function x9getCurve() { - return this.curve; -} - -function x9getG() { - return this.g; -} - -function x9getN() { - return this.n; -} - -function x9getH() { - return this.h; -} - -X9ECParameters.prototype.getCurve = x9getCurve; -X9ECParameters.prototype.getG = x9getG; -X9ECParameters.prototype.getN = x9getN; -X9ECParameters.prototype.getH = x9getH; - -// ---------------- -// SECNamedCurves - -function fromHex(s) { return new BigInteger(s, 16); } - -function secp128r1() { - // p = 2^128 - 2^97 - 1 - var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); - //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); - var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "161FF7528B899B2D0C28607CA52C5B86" - + "CF5AC8395BAFEB13C02DA292DDED7A83"); - return new X9ECParameters(curve, G, n, h); -} - -function secp160k1() { - // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); - var a = BigInteger.ZERO; - var b = fromHex("7"); - //byte[] S = null; - var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" - + "938CF935318FDCED6BC28286531733C3F03C4FEE"); - return new X9ECParameters(curve, G, n, h); -} - -function secp160r1() { - // p = 2^160 - 2^31 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); - var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); - //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); - var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "4A96B5688EF573284664698968C38BB913CBFC82" - + "23A628553168947D59DCC912042351377AC5FB32"); - return new X9ECParameters(curve, G, n, h); -} - -function secp192k1() { - // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); - var a = BigInteger.ZERO; - var b = fromHex("3"); - //byte[] S = null; - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" - + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); - return new X9ECParameters(curve, G, n, h); -} - -function secp192r1() { - // p = 2^192 - 2^64 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); - var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); - //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" - + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); - return new X9ECParameters(curve, G, n, h); -} - -function secp224r1() { - // p = 2^224 - 2^96 + 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); - var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); - //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" - + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); - return new X9ECParameters(curve, G, n, h); -} - -function secp256r1() { - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 - var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); - //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); - var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" - + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); - return new X9ECParameters(curve, G, n, h); -} - -// TODO: make this into a proper hashtable -function getSECCurveByName(name) { - if(name == "secp128r1") return secp128r1(); - if(name == "secp160k1") return secp160k1(); - if(name == "secp160r1") return secp160r1(); - if(name == "secp192k1") return secp192k1(); - if(name == "secp192r1") return secp192r1(); - if(name == "secp224r1") return secp224r1(); - if(name == "secp256r1") return secp256r1(); - return null; -} - -module.exports = { - "secp128r1":secp128r1, - "secp160k1":secp160k1, - "secp160r1":secp160r1, - "secp192k1":secp192k1, - "secp192r1":secp192r1, - "secp224r1":secp224r1, - "secp256r1":secp256r1 -} - -},{"./ec.js":280,"jsbn":825}],282:[function(require,module,exports){ +},{}],236:[function(require,module,exports){ 'use strict'; var elliptic = exports; @@ -41723,7 +31610,7 @@ elliptic.curves = require('./elliptic/curves'); elliptic.ec = require('./elliptic/ec'); elliptic.eddsa = require('./elliptic/eddsa'); -},{"../package.json":297,"./elliptic/curve":285,"./elliptic/curves":288,"./elliptic/ec":289,"./elliptic/eddsa":292,"./elliptic/utils":296,"brorand":181}],283:[function(require,module,exports){ +},{"../package.json":251,"./elliptic/curve":239,"./elliptic/curves":242,"./elliptic/ec":243,"./elliptic/eddsa":246,"./elliptic/utils":250,"brorand":145}],237:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -42099,7 +31986,7 @@ BasePoint.prototype.dblp = function dblp(k) { return r; }; -},{"../utils":296,"bn.js":171}],284:[function(require,module,exports){ +},{"../utils":250,"bn.js":135}],238:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -42533,7 +32420,7 @@ Point.prototype.eqXToP = function eqXToP(x) { Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; -},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],285:[function(require,module,exports){ +},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],239:[function(require,module,exports){ 'use strict'; var curve = exports; @@ -42543,7 +32430,7 @@ curve.short = require('./short'); curve.mont = require('./mont'); curve.edwards = require('./edwards'); -},{"./base":283,"./edwards":284,"./mont":286,"./short":287}],286:[function(require,module,exports){ +},{"./base":237,"./edwards":238,"./mont":240,"./short":241}],240:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -42723,7 +32610,7 @@ Point.prototype.getX = function getX() { return this.x.fromRed(); }; -},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],287:[function(require,module,exports){ +},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],241:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -43662,7 +33549,7 @@ JPoint.prototype.isInfinity = function isInfinity() { return this.z.cmpn(0) === 0; }; -},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],288:[function(require,module,exports){ +},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],242:[function(require,module,exports){ 'use strict'; var curves = exports; @@ -43870,7 +33757,7 @@ defineCurve('secp256k1', { ] }); -},{"./curve":285,"./precomputed/secp256k1":295,"./utils":296,"hash.js":424}],289:[function(require,module,exports){ +},{"./curve":239,"./precomputed/secp256k1":249,"./utils":250,"hash.js":294}],243:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44113,7 +34000,7 @@ EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { throw new Error('Unable to find valid recovery factor'); }; -},{"../curves":288,"../utils":296,"./key":290,"./signature":291,"bn.js":171,"brorand":181,"hmac-drbg":440}],290:[function(require,module,exports){ +},{"../curves":242,"../utils":250,"./key":244,"./signature":245,"bn.js":135,"brorand":145,"hmac-drbg":310}],244:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44233,7 +34120,7 @@ KeyPair.prototype.inspect = function inspect() { ' pub: ' + (this.pub && this.pub.inspect()) + ' >'; }; -},{"../utils":296,"bn.js":171}],291:[function(require,module,exports){ +},{"../utils":250,"bn.js":135}],245:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44369,7 +34256,7 @@ Signature.prototype.toDER = function toDER(enc) { return utils.encode(res, enc); }; -},{"../utils":296,"bn.js":171}],292:[function(require,module,exports){ +},{"../utils":250,"bn.js":135}],246:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); @@ -44489,7 +34376,7 @@ EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; -},{"../curves":288,"../utils":296,"./key":293,"./signature":294,"hash.js":424}],293:[function(require,module,exports){ +},{"../curves":242,"../utils":250,"./key":247,"./signature":248,"hash.js":294}],247:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -44586,7 +34473,7 @@ KeyPair.prototype.getPublic = function getPublic(enc) { module.exports = KeyPair; -},{"../utils":296}],294:[function(require,module,exports){ +},{"../utils":250}],248:[function(require,module,exports){ 'use strict'; var BN = require('bn.js'); @@ -44653,7 +34540,7 @@ Signature.prototype.toHex = function toHex() { module.exports = Signature; -},{"../utils":296,"bn.js":171}],295:[function(require,module,exports){ +},{"../utils":250,"bn.js":135}],249:[function(require,module,exports){ module.exports = { doubles: { step: 4, @@ -45435,7 +35322,7 @@ module.exports = { } }; -},{}],296:[function(require,module,exports){ +},{}],250:[function(require,module,exports){ 'use strict'; var utils = exports; @@ -45557,51 +35444,45 @@ function intFromLE(bytes) { utils.intFromLE = intFromLE; -},{"bn.js":171,"minimalistic-assert":1303,"minimalistic-crypto-utils":1304}],297:[function(require,module,exports){ +},{"bn.js":135,"minimalistic-assert":1129,"minimalistic-crypto-utils":1130}],251:[function(require,module,exports){ module.exports={ "_args": [ [ - "elliptic@^6.0.0", - "/var/www/html/ethoFSV2/node_modules/browserify-sign" + "elliptic@6.5.1", + "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet" ] ], - "_from": "elliptic@>=6.0.0 <7.0.0", - "_hasShrinkwrap": false, + "_from": "elliptic@6.5.1", "_id": "elliptic@6.5.1", - "_inCache": true, - "_installable": true, + "_inBundle": false, + "_integrity": "sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==", "_location": "/elliptic", - "_nodeVersion": "12.2.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/elliptic_6.5.1_1567564470143_0.35768573259267966" - }, - "_npmUser": { - "email": "fedor@indutny.com", - "name": "indutny" - }, - "_npmVersion": "6.11.2", "_phantomChildren": {}, "_requested": { + "type": "version", + "registry": true, + "raw": "elliptic@6.5.1", "name": "elliptic", - "raw": "elliptic@^6.0.0", - "rawSpec": "^6.0.0", - "scope": null, - "spec": ">=6.0.0 <7.0.0", - "type": "range" + "escapedName": "elliptic", + "rawSpec": "6.5.1", + "saveSpec": null, + "fetchSpec": "6.5.1" }, "_requiredBy": [ "/browserify-sign", - "/create-ecdh" + "/create-ecdh", + "/eth-lib", + "/secp256k1", + "/tiny-secp256k1", + "/web3-eth-accounts/eth-lib", + "/web3-utils/eth-lib" ], "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz", - "_shasum": "c380f5f909bf1b9b4428d028cd18d3b0efd6b52b", - "_shrinkwrap": null, - "_spec": "elliptic@^6.0.0", - "_where": "/var/www/html/ethoFSV2/node_modules/browserify-sign", + "_spec": "6.5.1", + "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet", "author": { - "email": "fedor@indutny.com", - "name": "Fedor Indutny" + "name": "Fedor Indutny", + "email": "fedor@indutny.com" }, "bugs": { "url": "https://github.com/indutny/elliptic/issues" @@ -45632,34 +35513,19 @@ module.exports={ "jshint": "^2.6.0", "mocha": "^6.1.4" }, - "directories": {}, - "dist": { - "fileCount": 17, - "integrity": "sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdbyK2CRA9TVsSAnZWagAAZR0P/jpSTQHkhgrh51Ql5iEp\nk19ZPvn6rvDRJdjPBgZfimuE8jYbzRrqEk0O8OJvWJAgBUz7RGcWsYjXEb0v\ncapOYnS9iL7EGmrZm/zIk2wB4K4vqbY1brh1WSGtZPJOotaTebfrepkUcqrk\nr2ZDg5YryX+gMD2QjumRSb3xXHbQukPvM9cc5WF5ZRaEzgQxRwtwwqzNejs1\np1DzKTNqBWzDGyl3NRdNPO8sEfcaf8LCyCu85OEFR1B7HytR1TH2B1uX7bNb\n82pw62BtmFbafa3VmFxeYk6Yqi5dHXUqsqLIGAsJJyaRsVOyLe/BuT7dHWgX\nEh8bQP4quLm2WZFIIRSUml4QXHiviMyUHfYITg05T/ODZejseHy65LYGgTsS\nQtsu+tDv+a4h+2FWNfkeVyinkEMNetlp+vPkSKVFeNLbCRFTR9ufgZqLn2IL\nnxpLdHLt9y6HaWDSSWwUwUYnK7WRiF8zP1cNRqZWyf7IPLHyRruwpkUFk9/u\nc6J3IgBQpgXfLxxXJTqqDvENmmMGtcJRWN0wtDLWNcYhm5f2px9m5vdxIj0U\nQn+6IZMgxTPsuA4w3iyagWbl/xtuEEw2XZUB++TztGfUtMImRFNEOqI3LO6V\n9CnJKpeVDPckXgDBwHJF9w6ywriLQKyR9rG8hl+nlonSbohg2hdQdB7TTeWJ\n1/J0\r\n=uYn+\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "c380f5f909bf1b9b4428d028cd18d3b0efd6b52b", - "tarball": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz", - "unpackedSize": 118051 - }, - "gitHead": "71e4e8e2f5b8f0bdbfbe106c72cc9fbc746d3d60", + "files": [ + "lib" + ], "homepage": "https://github.com/indutny/elliptic", "keywords": [ - "Cryptography", "EC", "Elliptic", - "curve" + "curve", + "Cryptography" ], "license": "MIT", "main": "lib/elliptic.js", - "maintainers": [ - { - "name": "indutny", - "email": "fedor@indutny.com" - } - ], "name": "elliptic", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+ssh://git@github.com/indutny/elliptic.git" @@ -45675,7 +35541,7 @@ module.exports={ "version": "6.5.1" } -},{}],298:[function(require,module,exports){ +},{}],252:[function(require,module,exports){ 'use strict' var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN @@ -45684,12 +35550,35 @@ var AbstractIterator = require('abstract-leveldown').AbstractIterator var inherits = require('inherits') var Codec = require('level-codec') var EncodingError = require('level-errors').EncodingError +var rangeMethods = ['approximateSize', 'compactRange'] module.exports = DB.default = DB function DB (db, opts) { if (!(this instanceof DB)) return new DB(db, opts) - AbstractLevelDOWN.call(this, '') + + var manifest = db.supports || {} + var additionalMethods = manifest.additionalMethods || {} + + AbstractLevelDOWN.call(this, manifest) + + this.supports.encodings = true + this.supports.additionalMethods = {} + + rangeMethods.forEach(function (m) { + // TODO (future major): remove this fallback + var fallback = typeof db[m] === 'function' + + if (additionalMethods[m] || fallback) { + this.supports.additionalMethods[m] = true + + this[m] = function (start, end, opts, cb) { + start = this.codec.encodeKey(start, opts) + end = this.codec.encodeKey(end, opts) + return this.db[m](start, end, opts, cb) + } + } + }, this) opts = opts || {} if (typeof opts.keyEncoding === 'undefined') opts.keyEncoding = 'utf8' @@ -45701,6 +35590,8 @@ function DB (db, opts) { inherits(DB, AbstractLevelDOWN) +DB.prototype.type = 'encoding-down' + DB.prototype._serializeKey = DB.prototype._serializeValue = function (datum) { return datum @@ -45760,12 +35651,6 @@ DB.prototype._clear = function (opts, callback) { this.db.clear(opts, callback) } -DB.prototype.approximateSize = function (start, end, opts, cb) { - start = this.codec.encodeKey(start, opts) - end = this.codec.encodeKey(end, opts) - return this.db.approximateSize(start, end, opts, cb) -} - function Iterator (db, opts) { AbstractIterator.call(this, db) this.codec = db.codec @@ -45836,8 +35721,7 @@ Batch.prototype._write = function (opts, cb) { this.batch.write(opts, cb) } -},{"abstract-leveldown":6,"inherits":453,"level-codec":843,"level-errors":845}],299:[function(require,module,exports){ -(function (process){ +},{"abstract-leveldown":6,"inherits":317,"level-codec":677,"level-errors":679}],253:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -45860,7 +35744,6 @@ var eos = function(stream, opts, callback) { var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); @@ -45885,13 +35768,8 @@ var eos = function(stream, opts, callback) { }; var onclose = function() { - process.nextTick(onclosenexttick); - }; - - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + 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')); }; var onrequest = function() { @@ -45916,7 +35794,6 @@ var eos = function(stream, opts, callback) { stream.on('close', onclose); return function() { - cancelled = true; stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); @@ -45933,8 +35810,7 @@ var eos = function(stream, opts, callback) { module.exports = eos; -}).call(this,require('_process')) -},{"_process":1438,"once":1394}],300:[function(require,module,exports){ +},{"once":1228}],254:[function(require,module,exports){ module.exports = require('./socket'); @@ -45946,7 +35822,7 @@ module.exports = require('./socket'); */ module.exports.parser = require('engine.io-parser'); -},{"./socket":301,"engine.io-parser":312}],301:[function(require,module,exports){ +},{"./socket":255,"engine.io-parser":265}],255:[function(require,module,exports){ /** * Module dependencies. */ @@ -46696,7 +36572,7 @@ Socket.prototype.filterUpgrades = function (upgrades) { return filteredUpgrades; }; -},{"./transport":302,"./transports/index":303,"component-emitter":227,"debug":309,"engine.io-parser":312,"indexof":452,"parseqs":1423,"parseuri":1424}],302:[function(require,module,exports){ +},{"./transport":256,"./transports/index":257,"component-emitter":189,"debug":263,"engine.io-parser":265,"indexof":316,"parseqs":1244,"parseuri":1245}],256:[function(require,module,exports){ /** * Module dependencies. */ @@ -46859,7 +36735,7 @@ Transport.prototype.onClose = function () { this.emit('close'); }; -},{"component-emitter":227,"engine.io-parser":312}],303:[function(require,module,exports){ +},{"component-emitter":189,"engine.io-parser":265}],257:[function(require,module,exports){ /** * Module dependencies */ @@ -46914,7 +36790,7 @@ function polling (opts) { } } -},{"./polling-jsonp":304,"./polling-xhr":305,"./websocket":307,"xmlhttprequest-ssl":308}],304:[function(require,module,exports){ +},{"./polling-jsonp":258,"./polling-xhr":259,"./websocket":261,"xmlhttprequest-ssl":262}],258:[function(require,module,exports){ (function (global){ /** * Module requirements. @@ -47157,7 +37033,7 @@ JSONPPolling.prototype.doWrite = function (data, fn) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./polling":306,"component-inherit":228}],305:[function(require,module,exports){ +},{"./polling":260,"component-inherit":190}],259:[function(require,module,exports){ /* global attachEvent */ /** @@ -47576,7 +37452,7 @@ function unloadHandler () { } } -},{"./polling":306,"component-emitter":227,"component-inherit":228,"debug":309,"xmlhttprequest-ssl":308}],306:[function(require,module,exports){ +},{"./polling":260,"component-emitter":189,"component-inherit":190,"debug":263,"xmlhttprequest-ssl":262}],260:[function(require,module,exports){ /** * Module dependencies. */ @@ -47823,7 +37699,7 @@ Polling.prototype.uri = function () { return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; -},{"../transport":302,"component-inherit":228,"debug":309,"engine.io-parser":312,"parseqs":1423,"xmlhttprequest-ssl":308,"yeast":1862}],307:[function(require,module,exports){ +},{"../transport":256,"component-inherit":190,"debug":263,"engine.io-parser":265,"parseqs":1244,"xmlhttprequest-ssl":262,"yeast":1529}],261:[function(require,module,exports){ (function (Buffer){ /** * Module dependencies. @@ -48122,7 +37998,7 @@ WS.prototype.check = function () { }; }).call(this,require("buffer").Buffer) -},{"../transport":302,"buffer":217,"component-inherit":228,"debug":309,"engine.io-parser":312,"parseqs":1423,"ws":182,"yeast":1862}],308:[function(require,module,exports){ +},{"../transport":256,"buffer":181,"component-inherit":190,"debug":263,"engine.io-parser":265,"parseqs":1244,"ws":146,"yeast":1529}],262:[function(require,module,exports){ // browser shim for xmlhttprequest module var hasCORS = require('has-cors'); @@ -48161,13 +38037,11 @@ module.exports = function (opts) { } }; -},{"has-cors":421}],309:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":310,"_process":1438,"dup":247}],310:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":311}],311:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],312:[function(require,module,exports){ +},{"has-cors":292}],263:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":264,"_process":1258,"dup":208}],264:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],265:[function(require,module,exports){ /** * Module dependencies. */ @@ -48774,7 +38648,7 @@ exports.decodePayloadAsBinary = function (data, binaryType, callback) { }); }; -},{"./keys":313,"./utf8":314,"after":7,"arraybuffer.slice":55,"base64-arraybuffer":161,"blob":170,"has-binary2":419}],313:[function(require,module,exports){ +},{"./keys":266,"./utf8":267,"after":8,"arraybuffer.slice":10,"base64-arraybuffer":108,"blob":134,"has-binary2":290}],266:[function(require,module,exports){ /** * Gets the keys for an object. @@ -48795,7 +38669,7 @@ module.exports = Object.keys || function keys (obj){ return arr; }; -},{}],314:[function(require,module,exports){ +},{}],267:[function(require,module,exports){ /*! https://mths.be/utf8js v2.1.2 by @mathias */ var stringFromCharCode = String.fromCharCode; @@ -49007,7 +38881,7 @@ module.exports = { decode: utf8decode }; -},{}],315:[function(require,module,exports){ +},{}],268:[function(require,module,exports){ 'use strict'; function createError(err, code, props) { @@ -49034,7 +38908,7 @@ function createError(err, code, props) { module.exports = createError; -},{}],316:[function(require,module,exports){ +},{}],269:[function(require,module,exports){ var prr = require('prr') function init (type, message, cause) { @@ -49093,7 +38967,7 @@ module.exports = function (errno) { } } -},{"prr":1455}],317:[function(require,module,exports){ +},{"prr":1275}],270:[function(require,module,exports){ var all = module.exports.all = [ { errno: -2, @@ -49408,8857 +39282,7 @@ all.forEach(function (error) { module.exports.custom = require('./custom')(module.exports) module.exports.create = module.exports.custom.createError -},{"./custom":316}],318:[function(require,module,exports){ -'use strict'; - -/* globals - Atomics, - SharedArrayBuffer, -*/ - -var undefined; // eslint-disable-line no-shadow-restricted-names - -var ThrowTypeError = Object.getOwnPropertyDescriptor - ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }()) - : function () { throw new TypeError(); }; - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var generator; // = function * () {}; -var generatorFunction = generator ? getProto(generator) : undefined; -var asyncFn; // async function() {}; -var asyncFunction = asyncFn ? asyncFn.constructor : undefined; -var asyncGen; // async function * () {}; -var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; -var asyncGenIterator = asyncGen ? asyncGen() : undefined; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '$ %Array%': Array, - '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, - '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '$ %ArrayPrototype%': Array.prototype, - '$ %ArrayProto_entries%': Array.prototype.entries, - '$ %ArrayProto_forEach%': Array.prototype.forEach, - '$ %ArrayProto_keys%': Array.prototype.keys, - '$ %ArrayProto_values%': Array.prototype.values, - '$ %AsyncFromSyncIteratorPrototype%': undefined, - '$ %AsyncFunction%': asyncFunction, - '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, - '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, - '$ %AsyncGeneratorFunction%': asyncGenFunction, - '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, - '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, - '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '$ %Boolean%': Boolean, - '$ %BooleanPrototype%': Boolean.prototype, - '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, - '$ %Date%': Date, - '$ %DatePrototype%': Date.prototype, - '$ %decodeURI%': decodeURI, - '$ %decodeURIComponent%': decodeURIComponent, - '$ %encodeURI%': encodeURI, - '$ %encodeURIComponent%': encodeURIComponent, - '$ %Error%': Error, - '$ %ErrorPrototype%': Error.prototype, - '$ %eval%': eval, // eslint-disable-line no-eval - '$ %EvalError%': EvalError, - '$ %EvalErrorPrototype%': EvalError.prototype, - '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, - '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, - '$ %Function%': Function, - '$ %FunctionPrototype%': Function.prototype, - '$ %Generator%': generator ? getProto(generator()) : undefined, - '$ %GeneratorFunction%': generatorFunction, - '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, - '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, - '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, - '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, - '$ %isFinite%': isFinite, - '$ %isNaN%': isNaN, - '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '$ %JSON%': JSON, - '$ %JSONParse%': JSON.parse, - '$ %Map%': typeof Map === 'undefined' ? undefined : Map, - '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, - '$ %Math%': Math, - '$ %Number%': Number, - '$ %NumberPrototype%': Number.prototype, - '$ %Object%': Object, - '$ %ObjectPrototype%': Object.prototype, - '$ %ObjProto_toString%': Object.prototype.toString, - '$ %ObjProto_valueOf%': Object.prototype.valueOf, - '$ %parseFloat%': parseFloat, - '$ %parseInt%': parseInt, - '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, - '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, - '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, - '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, - '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, - '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '$ %RangeError%': RangeError, - '$ %RangeErrorPrototype%': RangeError.prototype, - '$ %ReferenceError%': ReferenceError, - '$ %ReferenceErrorPrototype%': ReferenceError.prototype, - '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '$ %RegExp%': RegExp, - '$ %RegExpPrototype%': RegExp.prototype, - '$ %Set%': typeof Set === 'undefined' ? undefined : Set, - '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, - '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, - '$ %String%': String, - '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '$ %StringPrototype%': String.prototype, - '$ %Symbol%': hasSymbols ? Symbol : undefined, - '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, - '$ %SyntaxError%': SyntaxError, - '$ %SyntaxErrorPrototype%': SyntaxError.prototype, - '$ %ThrowTypeError%': ThrowTypeError, - '$ %TypedArray%': TypedArray, - '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, - '$ %TypeError%': TypeError, - '$ %TypeErrorPrototype%': TypeError.prototype, - '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, - '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, - '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, - '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, - '$ %URIError%': URIError, - '$ %URIErrorPrototype%': URIError.prototype, - '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, - '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new TypeError('"allowMissing" argument must be a boolean'); - } - - var key = '$ ' + name; - if (!(key in INTRINSICS)) { - throw new SyntaxError('intrinsic ' + name + ' does not exist!'); - } - - // istanbul ignore if // hopefully this is impossible to test :-) - if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { - throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - return INTRINSICS[key]; -}; - -},{}],319:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('./GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $String = GetIntrinsic('%String%'); -var $Number = GetIntrinsic('%Number%'); - -var assertRecord = require('./helpers/assertRecord'); -var isPropertyDescriptor = require('./helpers/isPropertyDescriptor'); -var $isNaN = require('./helpers/isNaN'); -var $isFinite = require('./helpers/isFinite'); - -var sign = require('./helpers/sign'); -var mod = require('./helpers/mod'); - -var IsCallable = require('is-callable'); -var toPrimitive = require('es-to-primitive/es5'); - -var has = require('has'); - -var callBind = require('./helpers/callBind'); -var strSlice = callBind($String.prototype.slice); - -var isPrefixOf = function isPrefixOf(prefix, string) { - if (prefix === string) { - return true; - } - if (prefix.length > string.length) { - return false; - } - return strSlice(string, 0, prefix.length) === prefix; -}; - -// https://es5.github.io/#x9 -var ES5 = { - ToPrimitive: toPrimitive, - - ToBoolean: function ToBoolean(value) { - return !!value; - }, - ToNumber: function ToNumber(value) { - return +value; // eslint-disable-line no-implicit-coercion - }, - ToInteger: function ToInteger(value) { - var number = this.ToNumber(value); - if ($isNaN(number)) { return 0; } - if (number === 0 || !$isFinite(number)) { return number; } - return sign(number) * Math.floor(Math.abs(number)); - }, - ToInt32: function ToInt32(x) { - return this.ToNumber(x) >> 0; - }, - ToUint32: function ToUint32(x) { - return this.ToNumber(x) >>> 0; - }, - ToUint16: function ToUint16(value) { - var number = this.ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = sign(number) * Math.floor(Math.abs(number)); - return mod(posInt, 0x10000); - }, - ToString: function ToString(value) { - return $String(value); - }, - ToObject: function ToObject(value) { - this.CheckObjectCoercible(value); - return $Object(value); - }, - CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { - /* jshint eqnull:true */ - if (value == null) { - throw new $TypeError(optMessage || 'Cannot call method on ' + value); - } - return value; - }, - IsCallable: IsCallable, - SameValue: function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); - }, - - // https://www.ecma-international.org/ecma-262/5.1/#sec-8 - Type: function Type(x) { - if (x === null) { - return 'Null'; - } - if (typeof x === 'undefined') { - return 'Undefined'; - } - if (typeof x === 'function' || typeof x === 'object') { - return 'Object'; - } - if (typeof x === 'number') { - return 'Number'; - } - if (typeof x === 'boolean') { - return 'Boolean'; - } - if (typeof x === 'string') { - return 'String'; - } - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor(this, Desc); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 - IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 - IsDataDescriptor: function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 - IsGenericDescriptor: function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { - return true; - } - - return false; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 - FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (this.IsDataDescriptor(Desc)) { - return { - value: Desc['[[Value]]'], - writable: !!Desc['[[Writable]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else if (this.IsAccessorDescriptor(Desc)) { - return { - get: Desc['[[Get]]'], - set: Desc['[[Set]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else { - throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); - } - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { - if (this.Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = this.ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; - }, - - // https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 - 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) { - var xType = this.Type(x); - var yType = this.Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (xType === 'Boolean') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (yType === 'Boolean') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number') && yType === 'Object') { - return this['Abstract Equality Comparison'](x, this.ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number')) { - return this['Abstract Equality Comparison'](this.ToPrimitive(x), y); - } - return false; - }, - - // https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - 'Strict Equality Comparison': function StrictEqualityComparison(x, y) { - var xType = this.Type(x); - var yType = this.Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 - }, - - // https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - // eslint-disable-next-line max-statements - 'Abstract Relational Comparison': function AbstractRelationalComparison(x, y, LeftFirst) { - if (this.Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = this.ToPrimitive(x, $Number); - py = this.ToPrimitive(y, $Number); - } else { - py = this.ToPrimitive(y, $Number); - px = this.ToPrimitive(x, $Number); - } - var bothStrings = this.Type(px) === 'String' && this.Type(py) === 'String'; - if (!bothStrings) { - var nx = this.ToNumber(px); - var ny = this.ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f - } -}; - -module.exports = ES5; - -},{"./GetIntrinsic":318,"./helpers/assertRecord":320,"./helpers/callBind":321,"./helpers/isFinite":322,"./helpers/isNaN":323,"./helpers/isPropertyDescriptor":324,"./helpers/mod":325,"./helpers/sign":326,"es-to-primitive/es5":327,"has":422,"is-callable":767}],320:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var has = require('has'); - -var predicates = { - // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - 'Property Descriptor': function isPropertyDescriptor(ES, Desc) { - if (ES.Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - var isData = has(Desc, '[[Value]]'); - var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); - if (isData && IsAccessor) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; - } -}; - -module.exports = function assertRecord(ES, recordType, argumentName, value) { - var predicate = predicates[recordType]; - if (typeof predicate !== 'function') { - throw new $SyntaxError('unknown record type: ' + recordType); - } - if (!predicate(ES, value)) { - throw new $TypeError(argumentName + ' must be a ' + recordType); - } -}; - -},{"../GetIntrinsic":318,"has":422}],321:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $apply = $Function.apply; -var $call = $Function.call; - -module.exports = function callBind() { - return bind.apply($call, arguments); -}; - -module.exports.apply = function applyBind() { - return bind.apply($apply, arguments); -}; - -},{"../GetIntrinsic":318,"function-bind":386}],322:[function(require,module,exports){ -'use strict'; - -var $isNaN = Number.isNaN || function (a) { return a !== a; }; - -module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; - -},{}],323:[function(require,module,exports){ -'use strict'; - -module.exports = Number.isNaN || function isNaN(a) { - return a !== a; -}; - -},{}],324:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); -var $TypeError = GetIntrinsic('%TypeError%'); - -module.exports = function IsPropertyDescriptor(ES, Desc) { - if (ES.Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; -}; - -},{"../GetIntrinsic":318,"has":422}],325:[function(require,module,exports){ -'use strict'; - -module.exports = function mod(number, modulo) { - var remain = number % modulo; - return Math.floor(remain >= 0 ? remain : remain + modulo); -}; - -},{}],326:[function(require,module,exports){ -'use strict'; - -module.exports = function sign(number) { - return number >= 0 ? 1 : -1; -}; - -},{}],327:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; - -var isPrimitive = require('./helpers/isPrimitive'); - -var isCallable = require('is-callable'); - -// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 -var ES5internalSlots = { - '[[DefaultValue]]': function (O) { - var actualHint; - if (arguments.length > 1) { - actualHint = arguments[1]; - } else { - actualHint = toStr.call(O) === '[object Date]' ? String : Number; - } - - if (actualHint === String || actualHint === Number) { - var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; - var value, i; - for (i = 0; i < methods.length; ++i) { - if (isCallable(O[methods[i]])) { - value = O[methods[i]](); - if (isPrimitive(value)) { - return value; - } - } - } - throw new TypeError('No default value'); - } - throw new TypeError('invalid [[DefaultValue]] hint supplied'); - } -}; - -// http://ecma-international.org/ecma-262/5.1/#sec-9.1 -module.exports = function ToPrimitive(input) { - if (isPrimitive(input)) { - return input; - } - if (arguments.length > 1) { - return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); - } - return ES5internalSlots['[[DefaultValue]]'](input); -}; - -},{"./helpers/isPrimitive":328,"is-callable":767}],328:[function(require,module,exports){ -module.exports = function isPrimitive(value) { - return value === null || (typeof value !== 'function' && typeof value !== 'object'); -}; - -},{}],329:[function(require,module,exports){ -module.exports = (function () { - if (this) return this; - - // Unexpected strict mode (may happen if e.g. bundled into ESM module), be nice - - // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis - // In all ES5+ engines global object inherits from Object.prototype - // (if you approached one that doesn't please report) - Object.defineProperty(Object.prototype, "__global__", { - get: function () { return this; }, - configurable: true - }); - try { return __global__; } - finally { delete Object.prototype.__global__; } -})(); - -},{}],330:[function(require,module,exports){ -(function (Buffer){ -var sha3 = require('js-sha3').keccak_256 -var uts46 = require('idna-uts46-hx') - -function namehash (inputName) { - // Reject empty names: - var node = '' - for (var i = 0; i < 32; i++) { - node += '00' - } - - name = normalize(inputName) - - if (name) { - var labels = name.split('.') - - for(var i = labels.length - 1; i >= 0; i--) { - var labelSha = sha3(labels[i]) - node = sha3(new Buffer(node + labelSha, 'hex')) - } - } - - return '0x' + node -} - -function normalize(name) { - return name ? uts46.toUnicode(name, {useStd3ASCII: true, transitional: false}) : name -} - -exports.hash = namehash -exports.normalize = normalize - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"idna-uts46-hx":450,"js-sha3":331}],331:[function(require,module,exports){ -(function (process,global){ -/** - * [js-sha3]{@link https://github.com/emn178/js-sha3} - * - * @version 0.5.7 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2015-2016 - * @license MIT - */ -/*jslint bitwise: true */ -(function () { - 'use strict'; - - var root = typeof window === 'object' ? window : {}; - var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; - if (NODE_JS) { - root = global; - } - var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports; - var HEX_CHARS = '0123456789abcdef'.split(''); - var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; - var KECCAK_PADDING = [1, 256, 65536, 16777216]; - var PADDING = [6, 1536, 393216, 100663296]; - var SHIFT = [0, 8, 16, 24]; - var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, - 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, - 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, - 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, - 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - var BITS = [224, 256, 384, 512]; - var SHAKE_BITS = [128, 256]; - var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; - - var createOutputMethod = function (bits, padding, outputType) { - return function (message) { - return new Keccak(bits, padding, bits).update(message)[outputType](); - }; - }; - - var createShakeOutputMethod = function (bits, padding, outputType) { - return function (message, outputBits) { - return new Keccak(bits, padding, outputBits).update(message)[outputType](); - }; - }; - - var createMethod = function (bits, padding) { - var method = createOutputMethod(bits, padding, 'hex'); - method.create = function () { - return new Keccak(bits, padding, bits); - }; - method.update = function (message) { - return method.create().update(message); - }; - for (var i = 0; i < OUTPUT_TYPES.length; ++i) { - var type = OUTPUT_TYPES[i]; - method[type] = createOutputMethod(bits, padding, type); - } - return method; - }; - - var createShakeMethod = function (bits, padding) { - var method = createShakeOutputMethod(bits, padding, 'hex'); - method.create = function (outputBits) { - return new Keccak(bits, padding, outputBits); - }; - method.update = function (message, outputBits) { - return method.create(outputBits).update(message); - }; - for (var i = 0; i < OUTPUT_TYPES.length; ++i) { - var type = OUTPUT_TYPES[i]; - method[type] = createShakeOutputMethod(bits, padding, type); - } - return method; - }; - - var algorithms = [ - {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, - {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, - {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} - ]; - - var methods = {}, methodNames = []; - - for (var i = 0; i < algorithms.length; ++i) { - var algorithm = algorithms[i]; - var bits = algorithm.bits; - for (var j = 0; j < bits.length; ++j) { - var methodName = algorithm.name +'_' + bits[j]; - methodNames.push(methodName); - methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); - } - } - - function Keccak(bits, padding, outputBits) { - this.blocks = []; - this.s = []; - this.padding = padding; - this.outputBits = outputBits; - this.reset = true; - this.block = 0; - this.start = 0; - this.blockCount = (1600 - (bits << 1)) >> 5; - this.byteCount = this.blockCount << 2; - this.outputBlocks = outputBits >> 5; - this.extraBytes = (outputBits & 31) >> 3; - - for (var i = 0; i < 50; ++i) { - this.s[i] = 0; - } - } - - Keccak.prototype.update = function (message) { - var notString = typeof message !== 'string'; - if (notString && message.constructor === ArrayBuffer) { - message = new Uint8Array(message); - } - var length = message.length, blocks = this.blocks, byteCount = this.byteCount, - blockCount = this.blockCount, index = 0, s = this.s, i, code; - - while (index < length) { - if (this.reset) { - this.reset = false; - blocks[0] = this.block; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - if (notString) { - for (i = this.start; index < length && i < byteCount; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; - } - } else { - for (i = this.start; index < length && i < byteCount; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else { - code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - } - } - this.lastByteIndex = i; - if (i >= byteCount) { - this.start = i - byteCount; - this.block = blocks[blockCount]; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - this.reset = true; - } else { - this.start = i; - } - } - return this; - }; - - Keccak.prototype.finalize = function () { - var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; - blocks[i >> 2] |= this.padding[i & 3]; - if (this.lastByteIndex === this.byteCount) { - blocks[0] = blocks[blockCount]; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - blocks[blockCount - 1] |= 0x80000000; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - }; - - Keccak.prototype.toString = Keccak.prototype.hex = function () { - this.finalize(); - - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, - extraBytes = this.extraBytes, i = 0, j = 0; - var hex = '', block; - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - block = s[i]; - hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + - HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + - HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + - HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; - } - if (j % blockCount === 0) { - f(s); - i = 0; - } - } - if (extraBytes) { - block = s[i]; - if (extraBytes > 0) { - hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; - } - if (extraBytes > 1) { - hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; - } - if (extraBytes > 2) { - hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; - } - } - return hex; - }; - - Keccak.prototype.arrayBuffer = function () { - this.finalize(); - - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, - extraBytes = this.extraBytes, i = 0, j = 0; - var bytes = this.outputBits >> 3; - var buffer; - if (extraBytes) { - buffer = new ArrayBuffer((outputBlocks + 1) << 2); - } else { - buffer = new ArrayBuffer(bytes); - } - var array = new Uint32Array(buffer); - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - array[j] = s[i]; - } - if (j % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - array[i] = s[i]; - buffer = buffer.slice(0, bytes); - } - return buffer; - }; - - Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; - - Keccak.prototype.digest = Keccak.prototype.array = function () { - this.finalize(); - - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, - extraBytes = this.extraBytes, i = 0, j = 0; - var array = [], offset, block; - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - offset = j << 2; - block = s[i]; - array[offset] = block & 0xFF; - array[offset + 1] = (block >> 8) & 0xFF; - array[offset + 2] = (block >> 16) & 0xFF; - array[offset + 3] = (block >> 24) & 0xFF; - } - if (j % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - offset = j << 2; - block = s[i]; - if (extraBytes > 0) { - array[offset] = block & 0xFF; - } - if (extraBytes > 1) { - array[offset + 1] = (block >> 8) & 0xFF; - } - if (extraBytes > 2) { - array[offset + 2] = (block >> 16) & 0xFF; - } - } - return array; - }; - - var f = function (s) { - var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, - b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, - b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, - b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - for (n = 0; n < 48; n += 2) { - c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; - c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; - c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; - c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; - c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; - c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; - c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; - c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; - c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; - c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - - h = c8 ^ ((c2 << 1) | (c3 >>> 31)); - l = c9 ^ ((c3 << 1) | (c2 >>> 31)); - s[0] ^= h; - s[1] ^= l; - s[10] ^= h; - s[11] ^= l; - s[20] ^= h; - s[21] ^= l; - s[30] ^= h; - s[31] ^= l; - s[40] ^= h; - s[41] ^= l; - h = c0 ^ ((c4 << 1) | (c5 >>> 31)); - l = c1 ^ ((c5 << 1) | (c4 >>> 31)); - s[2] ^= h; - s[3] ^= l; - s[12] ^= h; - s[13] ^= l; - s[22] ^= h; - s[23] ^= l; - s[32] ^= h; - s[33] ^= l; - s[42] ^= h; - s[43] ^= l; - h = c2 ^ ((c6 << 1) | (c7 >>> 31)); - l = c3 ^ ((c7 << 1) | (c6 >>> 31)); - s[4] ^= h; - s[5] ^= l; - s[14] ^= h; - s[15] ^= l; - s[24] ^= h; - s[25] ^= l; - s[34] ^= h; - s[35] ^= l; - s[44] ^= h; - s[45] ^= l; - h = c4 ^ ((c8 << 1) | (c9 >>> 31)); - l = c5 ^ ((c9 << 1) | (c8 >>> 31)); - s[6] ^= h; - s[7] ^= l; - s[16] ^= h; - s[17] ^= l; - s[26] ^= h; - s[27] ^= l; - s[36] ^= h; - s[37] ^= l; - s[46] ^= h; - s[47] ^= l; - h = c6 ^ ((c0 << 1) | (c1 >>> 31)); - l = c7 ^ ((c1 << 1) | (c0 >>> 31)); - s[8] ^= h; - s[9] ^= l; - s[18] ^= h; - s[19] ^= l; - s[28] ^= h; - s[29] ^= l; - s[38] ^= h; - s[39] ^= l; - s[48] ^= h; - s[49] ^= l; - - b0 = s[0]; - b1 = s[1]; - b32 = (s[11] << 4) | (s[10] >>> 28); - b33 = (s[10] << 4) | (s[11] >>> 28); - b14 = (s[20] << 3) | (s[21] >>> 29); - b15 = (s[21] << 3) | (s[20] >>> 29); - b46 = (s[31] << 9) | (s[30] >>> 23); - b47 = (s[30] << 9) | (s[31] >>> 23); - b28 = (s[40] << 18) | (s[41] >>> 14); - b29 = (s[41] << 18) | (s[40] >>> 14); - b20 = (s[2] << 1) | (s[3] >>> 31); - b21 = (s[3] << 1) | (s[2] >>> 31); - b2 = (s[13] << 12) | (s[12] >>> 20); - b3 = (s[12] << 12) | (s[13] >>> 20); - b34 = (s[22] << 10) | (s[23] >>> 22); - b35 = (s[23] << 10) | (s[22] >>> 22); - b16 = (s[33] << 13) | (s[32] >>> 19); - b17 = (s[32] << 13) | (s[33] >>> 19); - b48 = (s[42] << 2) | (s[43] >>> 30); - b49 = (s[43] << 2) | (s[42] >>> 30); - b40 = (s[5] << 30) | (s[4] >>> 2); - b41 = (s[4] << 30) | (s[5] >>> 2); - b22 = (s[14] << 6) | (s[15] >>> 26); - b23 = (s[15] << 6) | (s[14] >>> 26); - b4 = (s[25] << 11) | (s[24] >>> 21); - b5 = (s[24] << 11) | (s[25] >>> 21); - b36 = (s[34] << 15) | (s[35] >>> 17); - b37 = (s[35] << 15) | (s[34] >>> 17); - b18 = (s[45] << 29) | (s[44] >>> 3); - b19 = (s[44] << 29) | (s[45] >>> 3); - b10 = (s[6] << 28) | (s[7] >>> 4); - b11 = (s[7] << 28) | (s[6] >>> 4); - b42 = (s[17] << 23) | (s[16] >>> 9); - b43 = (s[16] << 23) | (s[17] >>> 9); - b24 = (s[26] << 25) | (s[27] >>> 7); - b25 = (s[27] << 25) | (s[26] >>> 7); - b6 = (s[36] << 21) | (s[37] >>> 11); - b7 = (s[37] << 21) | (s[36] >>> 11); - b38 = (s[47] << 24) | (s[46] >>> 8); - b39 = (s[46] << 24) | (s[47] >>> 8); - b30 = (s[8] << 27) | (s[9] >>> 5); - b31 = (s[9] << 27) | (s[8] >>> 5); - b12 = (s[18] << 20) | (s[19] >>> 12); - b13 = (s[19] << 20) | (s[18] >>> 12); - b44 = (s[29] << 7) | (s[28] >>> 25); - b45 = (s[28] << 7) | (s[29] >>> 25); - b26 = (s[38] << 8) | (s[39] >>> 24); - b27 = (s[39] << 8) | (s[38] >>> 24); - b8 = (s[48] << 14) | (s[49] >>> 18); - b9 = (s[49] << 14) | (s[48] >>> 18); - - s[0] = b0 ^ (~b2 & b4); - s[1] = b1 ^ (~b3 & b5); - s[10] = b10 ^ (~b12 & b14); - s[11] = b11 ^ (~b13 & b15); - s[20] = b20 ^ (~b22 & b24); - s[21] = b21 ^ (~b23 & b25); - s[30] = b30 ^ (~b32 & b34); - s[31] = b31 ^ (~b33 & b35); - s[40] = b40 ^ (~b42 & b44); - s[41] = b41 ^ (~b43 & b45); - s[2] = b2 ^ (~b4 & b6); - s[3] = b3 ^ (~b5 & b7); - s[12] = b12 ^ (~b14 & b16); - s[13] = b13 ^ (~b15 & b17); - s[22] = b22 ^ (~b24 & b26); - s[23] = b23 ^ (~b25 & b27); - s[32] = b32 ^ (~b34 & b36); - s[33] = b33 ^ (~b35 & b37); - s[42] = b42 ^ (~b44 & b46); - s[43] = b43 ^ (~b45 & b47); - s[4] = b4 ^ (~b6 & b8); - s[5] = b5 ^ (~b7 & b9); - s[14] = b14 ^ (~b16 & b18); - s[15] = b15 ^ (~b17 & b19); - s[24] = b24 ^ (~b26 & b28); - s[25] = b25 ^ (~b27 & b29); - s[34] = b34 ^ (~b36 & b38); - s[35] = b35 ^ (~b37 & b39); - s[44] = b44 ^ (~b46 & b48); - s[45] = b45 ^ (~b47 & b49); - s[6] = b6 ^ (~b8 & b0); - s[7] = b7 ^ (~b9 & b1); - s[16] = b16 ^ (~b18 & b10); - s[17] = b17 ^ (~b19 & b11); - s[26] = b26 ^ (~b28 & b20); - s[27] = b27 ^ (~b29 & b21); - s[36] = b36 ^ (~b38 & b30); - s[37] = b37 ^ (~b39 & b31); - s[46] = b46 ^ (~b48 & b40); - s[47] = b47 ^ (~b49 & b41); - s[8] = b8 ^ (~b0 & b2); - s[9] = b9 ^ (~b1 & b3); - s[18] = b18 ^ (~b10 & b12); - s[19] = b19 ^ (~b11 & b13); - s[28] = b28 ^ (~b20 & b22); - s[29] = b29 ^ (~b21 & b23); - s[38] = b38 ^ (~b30 & b32); - s[39] = b39 ^ (~b31 & b33); - s[48] = b48 ^ (~b40 & b42); - s[49] = b49 ^ (~b41 & b43); - - s[0] ^= RC[n]; - s[1] ^= RC[n + 1]; - } - }; - - if (COMMON_JS) { - module.exports = methods; - } else { - for (var i = 0; i < methodNames.length; ++i) { - root[methodNames[i]] = methods[methodNames[i]]; - } - } -})(); - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1438}],332:[function(require,module,exports){ -var generate = function generate(num, fn) { - var a = []; - for (var i = 0; i < num; ++i) { - a.push(fn(i)); - }return a; -}; - -var replicate = function replicate(num, val) { - return generate(num, function () { - return val; - }); -}; - -var concat = function concat(a, b) { - return a.concat(b); -}; - -var flatten = function flatten(a) { - var r = []; - for (var j = 0, J = a.length; j < J; ++j) { - for (var i = 0, I = a[j].length; i < I; ++i) { - r.push(a[j][i]); - } - }return r; -}; - -var chunksOf = function chunksOf(n, a) { - var b = []; - for (var i = 0, l = a.length; i < l; i += n) { - b.push(a.slice(i, i + n)); - }return b; -}; - -module.exports = { - generate: generate, - replicate: replicate, - concat: concat, - flatten: flatten, - chunksOf: chunksOf -}; -},{}],333:[function(require,module,exports){ -var A = require("./array.js"); - -var at = function at(bytes, index) { - return parseInt(bytes.slice(index * 2 + 2, index * 2 + 4), 16); -}; - -var random = function random(bytes) { - var rnd = void 0; - if (typeof window !== "undefined" && window.crypto && window.crypto.getRandomValues) rnd = window.crypto.getRandomValues(new Uint8Array(bytes));else if (typeof require !== "undefined") rnd = require("c" + "rypto").randomBytes(bytes);else throw "Safe random numbers not available."; - var hex = "0x"; - for (var i = 0; i < bytes; ++i) { - hex += ("00" + rnd[i].toString(16)).slice(-2); - }return hex; -}; - -var length = function length(a) { - return (a.length - 2) / 2; -}; - -var flatten = function flatten(a) { - return "0x" + a.reduce(function (r, s) { - return r + s.slice(2); - }, ""); -}; - -var slice = function slice(i, j, bs) { - return "0x" + bs.slice(i * 2 + 2, j * 2 + 2); -}; - -var reverse = function reverse(hex) { - var rev = "0x"; - for (var i = 0, l = length(hex); i < l; ++i) { - rev += hex.slice((l - i) * 2, (l - i + 1) * 2); - } - return rev; -}; - -var pad = function pad(l, hex) { - return hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2)); -}; - -var padRight = function padRight(l, hex) { - return hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0"); -}; - -var toArray = function toArray(hex) { - var arr = []; - for (var i = 2, l = hex.length; i < l; i += 2) { - arr.push(parseInt(hex.slice(i, i + 2), 16)); - }return arr; -}; - -var fromArray = function fromArray(arr) { - var hex = "0x"; - for (var i = 0, l = arr.length; i < l; ++i) { - var b = arr[i]; - hex += (b < 16 ? "0" : "") + b.toString(16); - } - return hex; -}; - -var toUint8Array = function toUint8Array(hex) { - return new Uint8Array(toArray(hex)); -}; - -var fromUint8Array = function fromUint8Array(arr) { - return fromArray([].slice.call(arr, 0)); -}; - -var fromNumber = function fromNumber(num) { - var hex = num.toString(16); - return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex; -}; - -var toNumber = function toNumber(hex) { - return parseInt(hex.slice(2), 16); -}; - -var concat = function concat(a, b) { - return a.concat(b.slice(2)); -}; - -var fromNat = function fromNat(bn) { - return bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2); -}; - -var toNat = function toNat(bn) { - return bn[2] === "0" ? "0x" + bn.slice(3) : bn; -}; - -var fromAscii = function fromAscii(ascii) { - var hex = "0x"; - for (var i = 0; i < ascii.length; ++i) { - hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2); - }return hex; -}; - -var toAscii = function toAscii(hex) { - var ascii = ""; - for (var i = 2; i < hex.length; i += 2) { - ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16)); - }return ascii; -}; - -// From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330 -var fromString = function fromString(s) { - var makeByte = function makeByte(uint8) { - var b = uint8.toString(16); - return b.length < 2 ? "0" + b : b; - }; - var bytes = "0x"; - for (var ci = 0; ci != s.length; ci++) { - var c = s.charCodeAt(ci); - if (c < 128) { - bytes += makeByte(c); - continue; - } - if (c < 2048) { - bytes += makeByte(c >> 6 | 192); - } else { - if (c > 0xd7ff && c < 0xdc00) { - if (++ci == s.length) return null; - var c2 = s.charCodeAt(ci); - if (c2 < 0xdc00 || c2 > 0xdfff) return null; - c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); - bytes += makeByte(c >> 18 | 240); - bytes += makeByte(c >> 12 & 63 | 128); - } else { - // c <= 0xffff - bytes += makeByte(c >> 12 | 224); - } - bytes += makeByte(c >> 6 & 63 | 128); - } - bytes += makeByte(c & 63 | 128); - } - return bytes; -}; - -var toString = function toString(bytes) { - var s = ''; - var i = 0; - var l = length(bytes); - while (i < l) { - var c = at(bytes, i++); - if (c > 127) { - if (c > 191 && c < 224) { - if (i >= l) return null; - c = (c & 31) << 6 | at(bytes, i) & 63; - } else if (c > 223 && c < 240) { - if (i + 1 >= l) return null; - c = (c & 15) << 12 | (at(bytes, i) & 63) << 6 | at(bytes, ++i) & 63; - } else if (c > 239 && c < 248) { - if (i + 2 >= l) return null; - c = (c & 7) << 18 | (at(bytes, i) & 63) << 12 | (at(bytes, ++i) & 63) << 6 | at(bytes, ++i) & 63; - } else return null; - ++i; - } - if (c <= 0xffff) s += String.fromCharCode(c);else if (c <= 0x10ffff) { - c -= 0x10000; - s += String.fromCharCode(c >> 10 | 0xd800); - s += String.fromCharCode(c & 0x3FF | 0xdc00); - } else return null; - } - return s; -}; - -module.exports = { - random: random, - length: length, - concat: concat, - flatten: flatten, - slice: slice, - reverse: reverse, - pad: pad, - padRight: padRight, - fromAscii: fromAscii, - toAscii: toAscii, - fromString: fromString, - toString: toString, - fromNumber: fromNumber, - toNumber: toNumber, - fromNat: fromNat, - toNat: toNat, - fromArray: fromArray, - toArray: toArray, - fromUint8Array: fromUint8Array, - toUint8Array: toUint8Array -}; -},{"./array.js":332}],334:[function(require,module,exports){ -// This was ported from https://github.com/emn178/js-sha3, with some minor -// modifications and pruning. It is licensed under MIT: -// -// Copyright 2015-2016 Chen, Yi-Cyuan -// -// 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. - -var HEX_CHARS = '0123456789abcdef'.split(''); -var KECCAK_PADDING = [1, 256, 65536, 16777216]; -var SHIFT = [0, 8, 16, 24]; -var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - -var Keccak = function Keccak(bits) { - return { - blocks: [], - reset: true, - block: 0, - start: 0, - blockCount: 1600 - (bits << 1) >> 5, - outputBlocks: bits >> 5, - s: function (s) { - return [].concat(s, s, s, s, s); - }([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) - }; -}; - -var update = function update(state, message) { - var length = message.length, - blocks = state.blocks, - byteCount = state.blockCount << 2, - blockCount = state.blockCount, - outputBlocks = state.outputBlocks, - s = state.s, - index = 0, - i, - code; - - // update - while (index < length) { - if (state.reset) { - state.reset = false; - blocks[0] = state.block; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - if (typeof message !== "string") { - for (i = state.start; index < length && i < byteCount; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; - } - } else { - for (i = state.start; index < length && i < byteCount; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; - } else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; - } else { - code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff); - blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; - } - } - } - state.lastByteIndex = i; - if (i >= byteCount) { - state.start = i - byteCount; - state.block = blocks[blockCount]; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - state.reset = true; - } else { - state.start = i; - } - } - - // finalize - i = state.lastByteIndex; - blocks[i >> 2] |= KECCAK_PADDING[i & 3]; - if (state.lastByteIndex === byteCount) { - blocks[0] = blocks[blockCount]; - for (i = 1; i < blockCount + 1; ++i) { - blocks[i] = 0; - } - } - blocks[blockCount - 1] |= 0x80000000; - for (i = 0; i < blockCount; ++i) { - s[i] ^= blocks[i]; - } - f(s); - - // toString - var hex = '', - i = 0, - j = 0, - block; - while (j < outputBlocks) { - for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { - block = s[i]; - hex += HEX_CHARS[block >> 4 & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[block >> 12 & 0x0F] + HEX_CHARS[block >> 8 & 0x0F] + HEX_CHARS[block >> 20 & 0x0F] + HEX_CHARS[block >> 16 & 0x0F] + HEX_CHARS[block >> 28 & 0x0F] + HEX_CHARS[block >> 24 & 0x0F]; - } - if (j % blockCount === 0) { - f(s); - i = 0; - } - } - return "0x" + hex; -}; - -var f = function f(s) { - var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - - for (n = 0; n < 48; n += 2) { - c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; - c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; - c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; - c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; - c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; - c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; - c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; - c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; - c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; - c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - - h = c8 ^ (c2 << 1 | c3 >>> 31); - l = c9 ^ (c3 << 1 | c2 >>> 31); - s[0] ^= h; - s[1] ^= l; - s[10] ^= h; - s[11] ^= l; - s[20] ^= h; - s[21] ^= l; - s[30] ^= h; - s[31] ^= l; - s[40] ^= h; - s[41] ^= l; - h = c0 ^ (c4 << 1 | c5 >>> 31); - l = c1 ^ (c5 << 1 | c4 >>> 31); - s[2] ^= h; - s[3] ^= l; - s[12] ^= h; - s[13] ^= l; - s[22] ^= h; - s[23] ^= l; - s[32] ^= h; - s[33] ^= l; - s[42] ^= h; - s[43] ^= l; - h = c2 ^ (c6 << 1 | c7 >>> 31); - l = c3 ^ (c7 << 1 | c6 >>> 31); - s[4] ^= h; - s[5] ^= l; - s[14] ^= h; - s[15] ^= l; - s[24] ^= h; - s[25] ^= l; - s[34] ^= h; - s[35] ^= l; - s[44] ^= h; - s[45] ^= l; - h = c4 ^ (c8 << 1 | c9 >>> 31); - l = c5 ^ (c9 << 1 | c8 >>> 31); - s[6] ^= h; - s[7] ^= l; - s[16] ^= h; - s[17] ^= l; - s[26] ^= h; - s[27] ^= l; - s[36] ^= h; - s[37] ^= l; - s[46] ^= h; - s[47] ^= l; - h = c6 ^ (c0 << 1 | c1 >>> 31); - l = c7 ^ (c1 << 1 | c0 >>> 31); - s[8] ^= h; - s[9] ^= l; - s[18] ^= h; - s[19] ^= l; - s[28] ^= h; - s[29] ^= l; - s[38] ^= h; - s[39] ^= l; - s[48] ^= h; - s[49] ^= l; - - b0 = s[0]; - b1 = s[1]; - b32 = s[11] << 4 | s[10] >>> 28; - b33 = s[10] << 4 | s[11] >>> 28; - b14 = s[20] << 3 | s[21] >>> 29; - b15 = s[21] << 3 | s[20] >>> 29; - b46 = s[31] << 9 | s[30] >>> 23; - b47 = s[30] << 9 | s[31] >>> 23; - b28 = s[40] << 18 | s[41] >>> 14; - b29 = s[41] << 18 | s[40] >>> 14; - b20 = s[2] << 1 | s[3] >>> 31; - b21 = s[3] << 1 | s[2] >>> 31; - b2 = s[13] << 12 | s[12] >>> 20; - b3 = s[12] << 12 | s[13] >>> 20; - b34 = s[22] << 10 | s[23] >>> 22; - b35 = s[23] << 10 | s[22] >>> 22; - b16 = s[33] << 13 | s[32] >>> 19; - b17 = s[32] << 13 | s[33] >>> 19; - b48 = s[42] << 2 | s[43] >>> 30; - b49 = s[43] << 2 | s[42] >>> 30; - b40 = s[5] << 30 | s[4] >>> 2; - b41 = s[4] << 30 | s[5] >>> 2; - b22 = s[14] << 6 | s[15] >>> 26; - b23 = s[15] << 6 | s[14] >>> 26; - b4 = s[25] << 11 | s[24] >>> 21; - b5 = s[24] << 11 | s[25] >>> 21; - b36 = s[34] << 15 | s[35] >>> 17; - b37 = s[35] << 15 | s[34] >>> 17; - b18 = s[45] << 29 | s[44] >>> 3; - b19 = s[44] << 29 | s[45] >>> 3; - b10 = s[6] << 28 | s[7] >>> 4; - b11 = s[7] << 28 | s[6] >>> 4; - b42 = s[17] << 23 | s[16] >>> 9; - b43 = s[16] << 23 | s[17] >>> 9; - b24 = s[26] << 25 | s[27] >>> 7; - b25 = s[27] << 25 | s[26] >>> 7; - b6 = s[36] << 21 | s[37] >>> 11; - b7 = s[37] << 21 | s[36] >>> 11; - b38 = s[47] << 24 | s[46] >>> 8; - b39 = s[46] << 24 | s[47] >>> 8; - b30 = s[8] << 27 | s[9] >>> 5; - b31 = s[9] << 27 | s[8] >>> 5; - b12 = s[18] << 20 | s[19] >>> 12; - b13 = s[19] << 20 | s[18] >>> 12; - b44 = s[29] << 7 | s[28] >>> 25; - b45 = s[28] << 7 | s[29] >>> 25; - b26 = s[38] << 8 | s[39] >>> 24; - b27 = s[39] << 8 | s[38] >>> 24; - b8 = s[48] << 14 | s[49] >>> 18; - b9 = s[49] << 14 | s[48] >>> 18; - - s[0] = b0 ^ ~b2 & b4; - s[1] = b1 ^ ~b3 & b5; - s[10] = b10 ^ ~b12 & b14; - s[11] = b11 ^ ~b13 & b15; - s[20] = b20 ^ ~b22 & b24; - s[21] = b21 ^ ~b23 & b25; - s[30] = b30 ^ ~b32 & b34; - s[31] = b31 ^ ~b33 & b35; - s[40] = b40 ^ ~b42 & b44; - s[41] = b41 ^ ~b43 & b45; - s[2] = b2 ^ ~b4 & b6; - s[3] = b3 ^ ~b5 & b7; - s[12] = b12 ^ ~b14 & b16; - s[13] = b13 ^ ~b15 & b17; - s[22] = b22 ^ ~b24 & b26; - s[23] = b23 ^ ~b25 & b27; - s[32] = b32 ^ ~b34 & b36; - s[33] = b33 ^ ~b35 & b37; - s[42] = b42 ^ ~b44 & b46; - s[43] = b43 ^ ~b45 & b47; - s[4] = b4 ^ ~b6 & b8; - s[5] = b5 ^ ~b7 & b9; - s[14] = b14 ^ ~b16 & b18; - s[15] = b15 ^ ~b17 & b19; - s[24] = b24 ^ ~b26 & b28; - s[25] = b25 ^ ~b27 & b29; - s[34] = b34 ^ ~b36 & b38; - s[35] = b35 ^ ~b37 & b39; - s[44] = b44 ^ ~b46 & b48; - s[45] = b45 ^ ~b47 & b49; - s[6] = b6 ^ ~b8 & b0; - s[7] = b7 ^ ~b9 & b1; - s[16] = b16 ^ ~b18 & b10; - s[17] = b17 ^ ~b19 & b11; - s[26] = b26 ^ ~b28 & b20; - s[27] = b27 ^ ~b29 & b21; - s[36] = b36 ^ ~b38 & b30; - s[37] = b37 ^ ~b39 & b31; - s[46] = b46 ^ ~b48 & b40; - s[47] = b47 ^ ~b49 & b41; - s[8] = b8 ^ ~b0 & b2; - s[9] = b9 ^ ~b1 & b3; - s[18] = b18 ^ ~b10 & b12; - s[19] = b19 ^ ~b11 & b13; - s[28] = b28 ^ ~b20 & b22; - s[29] = b29 ^ ~b21 & b23; - s[38] = b38 ^ ~b30 & b32; - s[39] = b39 ^ ~b31 & b33; - s[48] = b48 ^ ~b40 & b42; - s[49] = b49 ^ ~b41 & b43; - - s[0] ^= RC[n]; - s[1] ^= RC[n + 1]; - } -}; - -var keccak = function keccak(bits) { - return function (str) { - var msg; - if (str.slice(0, 2) === "0x") { - msg = []; - for (var i = 2, l = str.length; i < l; i += 2) { - msg.push(parseInt(str.slice(i, i + 2), 16)); - } - } else { - msg = str; - } - return update(Keccak(bits, bits), msg); - }; -}; - -module.exports = { - keccak256: keccak(256), - keccak512: keccak(512), - keccak256s: keccak(256), - keccak512s: keccak(512) -}; -},{}],335:[function(require,module,exports){ -const keccak256 = require('keccak256') - -function toChecksumAddress (address, chainId = null) { - if (typeof address !== 'string') { - return '' - } - - if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { throw new Error(`Given address "${address}" is not a valid Ethereum address.`) } - - const stripAddress = stripHexPrefix(address).toLowerCase() - const prefix = chainId != null ? chainId.toString() + '0x' : '' - const keccakHash = keccak256(prefix + stripAddress) - .toString('hex') - .replace(/^0x/i, '') - let checksumAddress = '0x' - - for (let i = 0; i < stripAddress.length; i++) { checksumAddress += parseInt(keccakHash[i], 16) >= 8 ? stripAddress[i].toUpperCase() : stripAddress[i] } - - return checksumAddress -} - -function checkAddressChecksum (address, chainId = null) { - const stripAddress = stripHexPrefix(address).toLowerCase() - const prefix = chainId != null ? chainId.toString() + '0x' : '' - const keccakHash = keccak256(prefix + stripAddress) - .toString('hex') - .replace(/^0x/i, '') - - for (let i = 0; i < stripAddress.length; i++) { - let output = parseInt(keccakHash[i], 16) >= 8 ? stripAddress[i].toUpperCase() : stripAddress[i] - if (stripHexPrefix(address)[i] !== output) { - return false - } - } - return true -}; - -function stripHexPrefix (string) { - return string.slice(0, 2) === '0x' ? string.slice(2) : string -}; - -module.exports = { - toChecksumAddress, - checkAddressChecksum -} - -},{"keccak256":839}],336:[function(require,module,exports){ -(function (Buffer){ -const privateKeyToPublicKey = require('ethereum-private-key-to-public-key') -const publicKeyToAddress = require('ethereum-public-key-to-address') - -function privateKeyToAddress (privateKey) { - if (!Buffer.isBuffer(privateKey)) { - if (typeof privateKey !== 'string') { - throw new Error('Expected Buffer or string as argument') - } - - privateKey = privateKey.slice(0, 2) === '0x' ? privateKey.slice(2) : privateKey - privateKey = Buffer.from(privateKey, 'hex') - } - - return publicKeyToAddress(privateKeyToPublicKey(privateKey)) -} - -module.exports = privateKeyToAddress - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"ethereum-private-key-to-public-key":337,"ethereum-public-key-to-address":338}],337:[function(require,module,exports){ -(function (Buffer){ -const { publicKeyCreate } = require('secp256k1') - -function privateKeyToPublicKey (privateKey) { - if (!Buffer.isBuffer(privateKey)) { - if (typeof privateKey !== 'string') { - throw new Error('Expected Buffer or string as argument') - } - - privateKey = privateKey.slice(0, 2) === '0x' ? privateKey.slice(2) : privateKey - privateKey = Buffer.from(privateKey, 'hex') - } - - return publicKeyCreate(privateKey, false) -} - -module.exports = privateKeyToPublicKey - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"secp256k1":1600}],338:[function(require,module,exports){ -(function (Buffer){ -const { publicKeyConvert } = require('secp256k1') -const keccak256 = require('keccak256') -const { toChecksumAddress } = require('ethereum-checksum-address') - -function publicKeyToAddress (publicKey) { - if (!Buffer.isBuffer(publicKey)) { - if (typeof publicKey !== 'string') { - throw new Error('Expected Buffer or string as argument') - } - - publicKey = publicKey.slice(0, 2) === '0x' ? publicKey.slice(2) : publicKey - publicKey = Buffer.from(publicKey, 'hex') - } - - publicKey = publicKeyConvert(publicKey, false).slice(1) - return toChecksumAddress(keccak256(publicKey).slice(-20).toString('hex')) -} - -module.exports = publicKeyToAddress - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"ethereum-checksum-address":335,"keccak256":839,"secp256k1":1600}],339:[function(require,module,exports){ -module.exports={ - "name": "goerli", - "chainId": 5, - "networkId": 5, - "comment": "Cross-client PoA test network", - "url": "https://github.com/goerli/testnet", - "genesis": { - "hash": "0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a", - "timestamp": "0x5c51a607", - "gasLimit": 10485760, - "difficulty": 1, - "nonce": "0x0000000000000000", - "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "stateRoot": "0x5d6cded585e73c4e322c30c2f782a336316f17dd85a4863b9d838d2d4b8b3008" - }, - "hardforks": [ - { - "name": "chainstart", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "homestead", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "dao", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "tangerineWhistle", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "spuriousDragon", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "byzantium", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "constantinople", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "petersburg", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "istanbul", - "block": null, - "consensus": "poa", - "finality": null - } - ], - "bootstrapNodes": [ - { - "ip": "51.141.78.53", - "port": 30303, - "id": "011f758e6552d105183b1761c5e2dea0111bc20fd5f6422bc7f91e0fabbec9a6595caf6239b37feb773dddd3f87240d99d859431891e4a642cf2a0a9e6cbb98a", - "location": "", - "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt" - }, - { - "ip": "13.93.54.137", - "port": 30303, - "id": "176b9417f511d05b6b2cf3e34b756cf0a7096b3094572a8f6ef4cdcb9d1f9d00683bf0f83347eebdf3b81c3521c2332086d9592802230bf528eaf606a1d9677b", - "location": "", - "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt" - }, - { - "ip": "94.237.54.114", - "port": 30313, - "id": "46add44b9f13965f7b9875ac6b85f016f341012d84f975377573800a863526f4da19ae2c620ec73d11591fa9510e992ecc03ad0751f53cc02f7c7ed6d55c7291", - "location": "", - "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt" - }, - { - "ip": "52.64.155.147", - "port": 30303, - "id": "c1f8b7c2ac4453271fa07d8e9ecf9a2e8285aa0bd0c07df0131f47153306b0736fd3db8924e7a9bf0bed6b1d8d4f87362a71b033dc7c64547728d953e43e59b2", - "location": "", - "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt" - }, - { - "ip": "213.186.16.82", - "port": 30303, - "id": "f4a9c6ee28586009fb5a96c8af13a58ed6d8315a9eee4772212c1d4d9cebe5a8b8a78ea4434f318726317d04a3f531a1ef0420cf9752605a562cfe858c46e263", - "location": "", - "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt" - } - ] -} - -},{}],340:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.chains = { - names: { - '1': 'mainnet', - '3': 'ropsten', - '4': 'rinkeby', - '42': 'kovan', - '6284': 'goerli', - }, - mainnet: require('./mainnet.json'), - ropsten: require('./ropsten.json'), - rinkeby: require('./rinkeby.json'), - kovan: require('./kovan.json'), - goerli: require('./goerli.json'), -}; - -},{"./goerli.json":339,"./kovan.json":341,"./mainnet.json":342,"./rinkeby.json":343,"./ropsten.json":344}],341:[function(require,module,exports){ -module.exports={ - "name": "kovan", - "chainId": 42, - "networkId": 42, - "comment": "Parity PoA test network", - "url": "https://kovan-testnet.github.io/website/", - "genesis": { - "hash": "0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9", - "timestamp": null, - "gasLimit": 6000000, - "difficulty": 131072, - "nonce": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "extraData": "0x", - "stateRoot": "0x2480155b48a1cea17d67dbfdfaafe821c1d19cdd478c5358e8ec56dec24502b2" - }, - "hardforks": [], - "bootstrapNodes": [ - { - "ip": "40.71.221.215", - "port": 30303, - "id": "56abaf065581a5985b8c5f4f88bd202526482761ba10be9bfdcd14846dd01f652ec33fde0f8c0fd1db19b59a4c04465681fcef50e11380ca88d25996191c52de", - "location": "", - "comment": "Parity Bootnode" - }, - { - "ip": "52.166.117.77", - "port": 30303, - "id": "d07827483dc47b368eaf88454fb04b41b7452cf454e194e2bd4c14f98a3278fed5d819dbecd0d010407fc7688d941ee1e58d4f9c6354d3da3be92f55c17d7ce3", - "location": "", - "comment": "Parity Bootnode" - }, - { - "ip": "52.165.239.18", - "port": 30303, - "id": "8fa162563a8e5a05eef3e1cd5abc5828c71344f7277bb788a395cce4a0e30baf2b34b92fe0b2dbbba2313ee40236bae2aab3c9811941b9f5a7e8e90aaa27ecba", - "location": "", - "comment": "Parity Bootnode" - }, - { - "ip": "52.243.47.56", - "port": 30303, - "id": "7e2e7f00784f516939f94e22bdc6cf96153603ca2b5df1c7cc0f90a38e7a2f218ffb1c05b156835e8b49086d11fdd1b3e2965be16baa55204167aa9bf536a4d9", - "location": "", - "comment": "Parity Bootnode" - }, - { - "ip": "40.68.248.100", - "port": 30303, - "id": "0518a3d35d4a7b3e8c433e7ffd2355d84a1304ceb5ef349787b556197f0c87fad09daed760635b97d52179d645d3e6d16a37d2cc0a9945c2ddf585684beb39ac", - "location": "", - "comment": "Parity Bootnode" - } - ] -} - -},{}],342:[function(require,module,exports){ -module.exports={ - "name": "mainnet", - "chainId": 1, - "networkId": 1, - "comment": "The Ethereum main chain", - "url": "https://ethstats.net/", - "genesis": { - "hash": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", - "timestamp": null, - "gasLimit": 5000, - "difficulty": 17179869184, - "nonce": "0x0000000000000042", - "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", - "stateRoot": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" - }, - "hardforks": [ - { - "name": "chainstart", - "block": 0, - "consensus": "pow", - "finality": null - }, - { - "name": "homestead", - "block": 1150000, - "consensus": "pow", - "finality": null - }, - { - "name": "dao", - "block": 1920000, - "consensus": "pow", - "finality": null - }, - { - "name": "tangerineWhistle", - "block": 2463000, - "consensus": "pow", - "finality": null - }, - { - "name": "spuriousDragon", - "block": 2675000, - "consensus": "pow", - "finality": null - }, - { - "name": "byzantium", - "block": 4370000, - "consensus": "pow", - "finality": null - }, - { - "name": "constantinople", - "block": 7280000, - "consensus": "pow", - "finality": null - }, - { - "name": "petersburg", - "block": 7280000, - "consensus": "pow", - "finality": null - }, - { - "name": "istanbul", - "block": null, - "consensus": "pow", - "finality": null - } - ], - "bootstrapNodes": [ - { - "ip": "13.93.211.84", - "port": 30303, - "id": "3f1d12044546b76342d59d4a05532c14b85aa669704bfe1f864fe079415aa2c02d743e03218e57a33fb94523adb54032871a6c51b2cc5514cb7c7e35b3ed0a99", - "location": "US-WEST", - "comment": "Go Bootnode" - }, - { - "ip": "191.235.84.50", - "port": 30303, - "id": "78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d", - "location": "BR", - "comment": "Go Bootnode" - }, - { - "ip": "13.75.154.138", - "port": 30303, - "id": "158f8aab45f6d19c6cbf4a089c2670541a8da11978a2f90dbf6a502a4a3bab80d288afdbeb7ec0ef6d92de563767f3b1ea9e8e334ca711e9f8e2df5a0385e8e6", - "location": "AU", - "comment": "Go Bootnode" - }, - { - "ip": "52.74.57.123", - "port": 30303, - "id": "1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082", - "location": "SG", - "comment": "Go Bootnode" - } - ] -} - -},{}],343:[function(require,module,exports){ -module.exports={ - "name": "rinkeby", - "chainId": 4, - "networkId": 4, - "comment": "PoA test network", - "url": "https://www.rinkeby.io", - "genesis": { - "hash": "0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177", - "timestamp": "0x58ee40ba", - "gasLimit": 4700000, - "difficulty": 1, - "nonce": "0x0000000000000000", - "extraData": "0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "stateRoot": "0x53580584816f617295ea26c0e17641e0120cab2f0a8ffb53a866fd53aa8e8c2d" - }, - "hardforks": [ - { - "name": "chainstart", - "block": 0, - "consensus": "poa", - "finality": null - }, - { - "name": "homestead", - "block": 1, - "consensus": "poa", - "finality": null - }, - { - "name": "dao", - "block": null, - "consensus": "poa", - "finality": null - }, - { - "name": "tangerineWhistle", - "block": 2, - "consensus": "poa", - "finality": null - }, - { - "name": "spuriousDragon", - "block": 3, - "consensus": "poa", - "finality": null - }, - { - "name": "byzantium", - "block": 1035301, - "consensus": "poa", - "finality": null - }, - { - "name": "constantinople", - "block": null, - "consensus": "poa", - "finality": null - }, - { - "name": "istanbul", - "block": null, - "consensus": "poa", - "finality": null - } - ], - "bootstrapNodes": [ - { - "ip": "52.169.42.101", - "port": 30303, - "id": "a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf", - "location": "IE", - "comment": "" - }, - { - "ip": "52.3.158.184", - "port": 30303, - "id": "343149e4feefa15d882d9fe4ac7d88f885bd05ebb735e547f12e12080a9fa07c8014ca6fd7f373123488102fe5e34111f8509cf0b7de3f5b44339c9f25e87cb8", - "location": "", - "comment": "INFURA" - } - ] -} - -},{}],344:[function(require,module,exports){ -module.exports={ - "name": "ropsten", - "chainId": 3, - "networkId": 3, - "comment": "PoW test network", - "url": "https://github.com/ethereum/ropsten", - "genesis": { - "hash": "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d", - "timestamp": null, - "gasLimit": 16777216, - "difficulty": 1048576, - "nonce": "0x0000000000000042", - "extraData": "0x3535353535353535353535353535353535353535353535353535353535353535", - "stateRoot": "0x217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b" - }, - "hardforks": [ - { - "name": "chainstart", - "block": 0, - "consensus": "pow", - "finality": null - }, - { - "name": "homestead", - "block": 0, - "consensus": "pow", - "finality": null - }, - { - "name": "dao", - "block": null, - "consensus": "pow", - "finality": null - }, - { - "name": "tangerineWhistle", - "block": 0, - "consensus": "pow", - "finality": null - }, - { - "name": "spuriousDragon", - "block": 10, - "consensus": "pow", - "finality": null - }, - { - "name": "byzantium", - "block": 1700000, - "consensus": "pow", - "finality": null - }, - { - "name": "constantinople", - "block": 4230000, - "consensus": "pow", - "finality": null - }, - { - "name": "petersburg", - "block": 4939394, - "consensus": "pow", - "finality": null - }, - { - "name": "istanbul", - "block": null, - "consensus": "pow", - "finality": null - } - ], - "bootstrapNodes": [ - { - "ip": "52.176.7.10", - "port": "30303", - "id": "30b7ab30a01c124a6cceca36863ece12c4f5fa68e3ba9b0b51407ccc002eeed3b3102d20a88f1c1d3c3154e2449317b8ef95090e77b312d5cc39354f86d5d606", - "network": "Ropsten", - "chainId": 3, - "location": "US", - "comment": "US-Azure geth" - }, - { - "ip": "52.176.100.77", - "port": "30303", - "id": "865a63255b3bb68023b6bffd5095118fcc13e79dcf014fe4e47e065c350c7cc72af2e53eff895f11ba1bbb6a2b33271c1116ee870f266618eadfc2e78aa7349c", - "network": "Ropsten", - "chainId": 3, - "location": "US", - "comment": "US-Azure parity" - }, - { - "ip": "52.232.243.152", - "port": "30303", - "id": "6332792c4a00e3e4ee0926ed89e0d27ef985424d97b6a45bf0f23e51f0dcb5e66b875777506458aea7af6f9e4ffb69f43f3778ee73c81ed9d34c51c4b16b0b0f", - "network": "Ropsten", - "chainId": 3, - "location": "US", - "comment": "Parity" - }, - { - "ip": "192.81.208.223", - "port": "30303", - "id": "94c15d1b9e2fe7ce56e458b9a3b672ef11894ddedd0c6f247e0f1d3487f52b66208fb4aeb8179fce6e3a749ea93ed147c37976d67af557508d199d9594c35f09", - "network": "Ropsten", - "chainId": 3, - "location": "US", - "comment": "@gpip" - } - ] -} - -},{}],345:[function(require,module,exports){ -module.exports={ - "name": "byzantium", - "comment": "Hardfork with new precompiles, instructions and other protocol changes", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-609", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": { - "modexpGquaddivisor": { - "v": 20, - "d": "Gquaddivisor from modexp precompile for gas calculation" - }, - "ecAdd": { - "v": 500, - "d": "Gas costs for curve addition precompile" - }, - "ecMul": { - "v": 40000, - "d": "Gas costs for curve multiplication precompile" - }, - "ecPairing": { - "v": 100000, - "d": "Base gas costs for curve pairing precompile" - }, - "ecPairingWord": { - "v": 80000, - "d": "Gas costs regarding curve pairing precompile input length" - } - }, - "vm": {}, - "pow": { - "minerReward": { - "v": "3000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - } - }, - "casper": {}, - "sharding": {} -} - -},{}],346:[function(require,module,exports){ -module.exports={ - "name": "chainstart", - "comment": "Start of the Ethereum main chain", - "eip": { - "url": "", - "status": "" - }, - "status": "", - "gasConfig": { - "minGasLimit": { - "v": 5000, - "d": "Minimum the gas limit may ever be" - }, - "gasLimitBoundDivisor": { - "v": 1024, - "d": "The bound divisor of the gas limit, used in update calculations" - } - }, - "gasPrices": { - "base": { - "v": 2, - "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)" - }, - "tierStep": { - "v": [0, 2, 3, 5, 8, 10, 20], - "d": "Once per operation, for a selection of them" - }, - "exp": { - "v": 10, - "d": "Once per EXP instuction" - }, - "expByte": { - "v": 10, - "d": "Times ceil(log256(exponent)) for the EXP instruction" - }, - "sha3": { - "v": 30, - "d": "Once per SHA3 operation" - }, - "sha3Word": { - "v": 6, - "d": "Once per word of the SHA3 operation's data" - }, - "sload": { - "v": 50, - "d": "Once per SLOAD operation" - }, - "sstoreSet": { - "v": 20000, - "d": "Once per SSTORE operation if the zeroness changes from zero" - }, - "sstoreReset": { - "v": 5000, - "d": "Once per SSTORE operation if the zeroness does not change from zero" - }, - "sstoreRefund": { - "v": 15000, - "d": "Once per SSTORE operation if the zeroness changes to zero" - }, - "jumpdest": { - "v": 1, - "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero" - }, - "log": { - "v": 375, - "d": "Per LOG* operation" - }, - "logData": { - "v": 8, - "d": "Per byte in a LOG* operation's data" - }, - "logTopic": { - "v": 375, - "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas" - }, - "create": { - "v": 32000, - "d": "Once per CREATE operation & contract-creation transaction" - }, - "call": { - "v": 40, - "d": "Once per CALL operation & message call transaction" - }, - "callStipend": { - "v": 2300, - "d": "Free gas given at beginning of call" - }, - "callValueTransfer": { - "v": 9000, - "d": "Paid for CALL when the value transfor is non-zero" - }, - "callNewAccount": { - "v": 25000, - "d": "Paid for CALL when the destination address didn't exist prior" - }, - "selfdestructRefund": { - "v": 24000, - "d": "Refunded following a selfdestruct operation" - }, - "memory": { - "v": 3, - "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL" - }, - "quadCoeffDiv": { - "v": 512, - "d": "Divisor for the quadratic particle of the memory cost equation" - }, - "createData": { - "v": 200, - "d": "" - }, - "tx": { - "v": 21000, - "d": "Per transaction. NOTE: Not payable on data of calls between transactions" - }, - "txCreation": { - "v": 32000, - "d": "The cost of creating a contract via tx" - }, - "txDataZero": { - "v": 4, - "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions" - }, - "txDataNonZero": { - "v": 68, - "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" - }, - "copy": { - "v": 3, - "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added" - }, - "ecRecover": { - "v": 3000, - "d": "" - }, - "sha256": { - "v": 60, - "d": "" - }, - "sha256Word": { - "v": 12, - "d": "" - }, - "ripemd160": { - "v": 600, - "d": "" - }, - "ripemd160Word": { - "v": 120, - "d": "" - }, - "identity": { - "v": 15, - "d": "" - }, - "identityWord": { - "v": 3, - "d": "" - } - }, - "vm": { - "stackLimit": { - "v": 1024, - "d": "Maximum size of VM stack allowed" - }, - "callCreateDepth": { - "v": 1024, - "d": "Maximum depth of call/create stack" - }, - "maxExtraDataSize": { - "v": 32, - "d": "Maximum size extra data may be after Genesis" - } - }, - "pow": { - "minimumDifficulty": { - "v": 131072, - "d": "The minimum that the difficulty may ever be" - }, - "difficultyBoundDivisor": { - "v": 2048, - "d": "The bound divisor of the difficulty, used in the update calculations" - }, - "durationLimit": { - "v": 13, - "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not" - }, - "epochDuration": { - "v": 30000, - "d": "Duration between proof-of-work epochs" - }, - "timebombPeriod": { - "v": 100000, - "d": "Exponential difficulty timebomb period" - }, - "minerReward": { - "v": "5000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - } - }, - "casper": {}, - "sharding": {} -} - -},{}],347:[function(require,module,exports){ -module.exports={ - "name": "constantinople", - "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-1013", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": { - "netSstoreNoopGas": { - "v": 200, - "d": "Once per SSTORE operation if the value doesn't change" - }, - "netSstoreInitGas": { - "v": 20000, - "d": "Once per SSTORE operation from clean zero" - }, - "netSstoreCleanGas": { - "v": 5000, - "d": "Once per SSTORE operation from clean non-zero" - }, - "netSstoreDirtyGas": { - "v": 200, - "d": "Once per SSTORE operation from dirty" - }, - "netSstoreClearRefund": { - "v": 15000, - "d": "Once per SSTORE operation for clearing an originally existing storage slot" - }, - "netSstoreResetRefund": { - "v": 4800, - "d": "Once per SSTORE operation for resetting to the original non-zero value" - }, - "netSstoreResetClearRefund": { - "v": 19800, - "d": "Once per SSTORE operation for resetting to the original zero value" - } - }, - "vm": {}, - "pow": { - "minerReward": { - "v": "2000000000000000000", - "d": "The amount a miner gets rewarded for mining a block" - } - }, - "casper": {}, - "sharding": {} -} - -},{}],348:[function(require,module,exports){ -module.exports={ - "name": "dao", - "comment": "DAO rescue hardfork", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-779", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],349:[function(require,module,exports){ -module.exports={ - "name": "homestead", - "comment": "Homestead hardfork with protocol and network changes", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-606", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],350:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hardforks = [ - ['chainstart', require('./chainstart.json')], - ['homestead', require('./homestead.json')], - ['dao', require('./dao.json')], - ['tangerineWhistle', require('./tangerineWhistle.json')], - ['spuriousDragon', require('./spuriousDragon.json')], - ['byzantium', require('./byzantium.json')], - ['constantinople', require('./constantinople.json')], - ['petersburg', require('./petersburg.json')], - ['istanbul', require('./istanbul.json')], -]; - -},{"./byzantium.json":345,"./chainstart.json":346,"./constantinople.json":347,"./dao.json":348,"./homestead.json":349,"./istanbul.json":351,"./petersburg.json":352,"./spuriousDragon.json":353,"./tangerineWhistle.json":354}],351:[function(require,module,exports){ -module.exports={ - "name": "istanbul", - "comment": "HF targeted for October 2019 following the Constantinople/Petersburg HF", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-1679", - "status": "Draft" - }, - "gasConfig": {}, - "gasPrices": { - "blake2Round": { - "v": 1, - "d": "Gas cost per round for the Blake2 F precompile" - }, - "ecAdd": { - "v": 150, - "d": "Gas costs for curve addition precompile" - }, - "ecMul": { - "v": 6000, - "d": "Gas costs for curve multiplication precompile" - }, - "ecPairing": { - "v": 45000, - "d": "Base gas costs for curve pairing precompile" - }, - "ecPairingWord": { - "v": 34000, - "d": "Gas costs regarding curve pairing precompile input length" - }, - "txDataNonZero": { - "v": 16, - "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" - }, - "sstoreSentryGasEIP2200": { - "v": 2300, - "d": "Minimum gas required to be present for an SSTORE call, not consumed" - }, - "sstoreNoopGasEIP2200": { - "v": 800, - "d": "Once per SSTORE operation if the value doesn't change" - }, - "sstoreDirtyGasEIP2200": { - "v": 800, - "d": "Once per SSTORE operation if a dirty value is changed" - }, - "sstoreInitGasEIP2200": { - "v": 20000, - "d": "Once per SSTORE operation from clean zero to non-zero" - }, - "sstoreInitRefundEIP2200": { - "v": 19200, - "d": "Once per SSTORE operation for resetting to the original zero value" - }, - "sstoreCleanGasEIP2200": { - "v": 5000, - "d": "Once per SSTORE operation from clean non-zero to something else" - }, - "sstoreCleanRefundEIP2200": { - "v": 4200, - "d": "Once per SSTORE operation for resetting to the original non-zero value" - }, - "sstoreClearRefundEIP2200": { - "v": 15000, - "d": "Once per SSTORE operation for clearing an originally existing storage slot" - } - }, - "vm": {}, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],352:[function(require,module,exports){ -module.exports={ - "name": "petersburg", - "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople", - "eip": { - "url": "https://github.com/ethereum/EIPs/pull/1716", - "status": "Draft" - }, - "gasConfig": {}, - "gasPrices": { - "netSstoreNoopGas": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreInitGas": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreCleanGas": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreDirtyGas": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreClearRefund": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreResetRefund": { - "v": null, - "d": "Removed along EIP-1283" - }, - "netSstoreResetClearRefund": { - "v": null, - "d": "Removed along EIP-1283" - } - }, - "vm": {}, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],353:[function(require,module,exports){ -module.exports={ - "name": "spuriousDragon", - "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-607", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": { - "expByte": { - "v": 50, - "d": "Times ceil(log256(exponent)) for the EXP instruction" - } - }, - "vm": { - "maxCodeSize": { - "v": 24576, - "d": "Maximum length of contract code" - } - }, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],354:[function(require,module,exports){ -module.exports={ - "name": "tangerineWhistle", - "comment": "Hardfork with gas cost changes for IO-heavy operations", - "eip": { - "url": "https://eips.ethereum.org/EIPS/eip-608", - "status": "Final" - }, - "gasConfig": {}, - "gasPrices": { - "sload": { - "v": 200, - "d": "Once per SLOAD operation" - }, - "call": { - "v": 700, - "d": "Once per CALL operation & message call transaction" - } - }, - "vm": {}, - "pow": {}, - "casper": {}, - "sharding": {} -} - -},{}],355:[function(require,module,exports){ -"use strict"; -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -var chains_1 = require("./chains"); -var hardforks_1 = require("./hardforks"); -/** - * Common class to access chain and hardfork parameters - */ -var Common = /** @class */ (function () { - /** - * @constructor - * @param chain String ('mainnet') or Number (1) chain - * @param hardfork String identifier ('byzantium') for hardfork (optional) - * @param supportedHardforks Limit parameter returns to the given hardforks (optional) - */ - function Common(chain, hardfork, supportedHardforks) { - this._chainParams = this.setChain(chain); - this._hardfork = null; - this._supportedHardforks = supportedHardforks === undefined ? [] : supportedHardforks; - if (hardfork) { - this.setHardfork(hardfork); - } - } - /** - * Creates a Common object for a custom chain, based on a standard one. It uses all the [[Chain]] - * params from [[baseChain]] except the ones overridden in [[customChainParams]]. - * - * @param baseChain The name (`mainnet`) or id (`1`) of a standard chain used to base the custom - * chain params on. - * @param customChainParams The custom parameters of the chain. - * @param hardfork String identifier ('byzantium') for hardfork (optional) - * @param supportedHardforks Limit parameter returns to the given hardforks (optional) - */ - Common.forCustomChain = function (baseChain, customChainParams, hardfork, supportedHardforks) { - var standardChainParams = Common._getChainParams(baseChain); - return new Common(__assign({}, standardChainParams, customChainParams), hardfork, supportedHardforks); - }; - Common._getChainParams = function (chain) { - if (typeof chain === 'number') { - if (chains_1.chains['names'][chain]) { - return chains_1.chains[chains_1.chains['names'][chain]]; - } - throw new Error("Chain with ID " + chain + " not supported"); - } - if (chains_1.chains[chain]) { - return chains_1.chains[chain]; - } - throw new Error("Chain with name " + chain + " not supported"); - }; - /** - * Sets the chain - * @param chain String ('mainnet') or Number (1) chain - * representation. Or, a Dictionary of chain parameters for a private network. - * @returns The dictionary with parameters set as chain - */ - Common.prototype.setChain = function (chain) { - if (typeof chain === 'number' || typeof chain === 'string') { - this._chainParams = Common._getChainParams(chain); - } - else if (typeof chain === 'object') { - var required = ['networkId', 'genesis', 'hardforks', 'bootstrapNodes']; - for (var _i = 0, required_1 = required; _i < required_1.length; _i++) { - var param = required_1[_i]; - if (chain[param] === undefined) { - throw new Error("Missing required chain parameter: " + param); - } - } - this._chainParams = chain; - } - else { - throw new Error('Wrong input format'); - } - return this._chainParams; - }; - /** - * Sets the hardfork to get params for - * @param hardfork String identifier ('byzantium') - */ - Common.prototype.setHardfork = function (hardfork) { - if (!this._isSupportedHardfork(hardfork)) { - throw new Error("Hardfork " + hardfork + " not set as supported in supportedHardforks"); - } - var changed = false; - for (var _i = 0, hardforkChanges_1 = hardforks_1.hardforks; _i < hardforkChanges_1.length; _i++) { - var hfChanges = hardforkChanges_1[_i]; - if (hfChanges[0] === hardfork) { - this._hardfork = hardfork; - changed = true; - } - } - if (!changed) { - throw new Error("Hardfork with name " + hardfork + " not supported"); - } - }; - /** - * Internal helper function to choose between hardfork set and hardfork provided as param - * @param hardfork Hardfork given to function as a parameter - * @returns Hardfork chosen to be used - */ - Common.prototype._chooseHardfork = function (hardfork, onlySupported) { - onlySupported = onlySupported === undefined ? true : onlySupported; - if (!hardfork) { - if (!this._hardfork) { - throw new Error('Method called with neither a hardfork set nor provided by param'); - } - else { - hardfork = this._hardfork; - } - } - else if (onlySupported && !this._isSupportedHardfork(hardfork)) { - throw new Error("Hardfork " + hardfork + " not set as supported in supportedHardforks"); - } - return hardfork; - }; - /** - * Internal helper function, returns the params for the given hardfork for the chain set - * @param hardfork Hardfork name - * @returns Dictionary with hardfork params - */ - Common.prototype._getHardfork = function (hardfork) { - var hfs = this.hardforks(); - for (var _i = 0, hfs_1 = hfs; _i < hfs_1.length; _i++) { - var hf = hfs_1[_i]; - if (hf['name'] === hardfork) - return hf; - } - throw new Error("Hardfork " + hardfork + " not defined for chain " + this.chainName()); - }; - /** - * Internal helper function to check if a hardfork is set to be supported by the library - * @param hardfork Hardfork name - * @returns True if hardfork is supported - */ - Common.prototype._isSupportedHardfork = function (hardfork) { - if (this._supportedHardforks.length > 0) { - for (var _i = 0, _a = this._supportedHardforks; _i < _a.length; _i++) { - var supportedHf = _a[_i]; - if (hardfork === supportedHf) - return true; - } - } - else { - return true; - } - return false; - }; - /** - * Returns the parameter corresponding to a hardfork - * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow', 'casper', 'sharding') - * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic) - * @param hardfork Hardfork name, optional if hardfork set - */ - Common.prototype.param = function (topic, name, hardfork) { - hardfork = this._chooseHardfork(hardfork); - var value; - for (var _i = 0, hardforkChanges_2 = hardforks_1.hardforks; _i < hardforkChanges_2.length; _i++) { - var hfChanges = hardforkChanges_2[_i]; - if (!hfChanges[1][topic]) { - throw new Error("Topic " + topic + " not defined"); - } - if (hfChanges[1][topic][name] !== undefined) { - value = hfChanges[1][topic][name].v; - } - if (hfChanges[0] === hardfork) - break; - } - if (value === undefined) { - throw new Error(topic + " value for " + name + " not found"); - } - return value; - }; - /** - * Returns a parameter for the hardfork active on block number - * @param topic Parameter topic - * @param name Parameter name - * @param blockNumber Block number - */ - Common.prototype.paramByBlock = function (topic, name, blockNumber) { - var activeHfs = this.activeHardforks(blockNumber); - var hardfork = activeHfs[activeHfs.length - 1]['name']; - return this.param(topic, name, hardfork); - }; - /** - * Checks if set or provided hardfork is active on block number - * @param hardfork Hardfork name or null (for HF set) - * @param blockNumber - * @param opts Hardfork options (onlyActive unused) - * @returns True if HF is active on block number - */ - Common.prototype.hardforkIsActiveOnBlock = function (hardfork, blockNumber, opts) { - opts = opts !== undefined ? opts : {}; - var onlySupported = opts.onlySupported === undefined ? false : opts.onlySupported; - hardfork = this._chooseHardfork(hardfork, onlySupported); - var hfBlock = this.hardforkBlock(hardfork); - if (hfBlock !== null && blockNumber >= hfBlock) - return true; - return false; - }; - /** - * Alias to hardforkIsActiveOnBlock when hardfork is set - * @param blockNumber - * @param opts Hardfork options (onlyActive unused) - * @returns True if HF is active on block number - */ - Common.prototype.activeOnBlock = function (blockNumber, opts) { - return this.hardforkIsActiveOnBlock(null, blockNumber, opts); - }; - /** - * Sequence based check if given or set HF1 is greater than or equal HF2 - * @param hardfork1 Hardfork name or null (if set) - * @param hardfork2 Hardfork name - * @param opts Hardfork options - * @returns True if HF1 gte HF2 - */ - Common.prototype.hardforkGteHardfork = function (hardfork1, hardfork2, opts) { - opts = opts !== undefined ? opts : {}; - var onlyActive = opts.onlyActive === undefined ? false : opts.onlyActive; - hardfork1 = this._chooseHardfork(hardfork1, opts.onlySupported); - var hardforks; - if (onlyActive) { - hardforks = this.activeHardforks(null, opts); - } - else { - hardforks = this.hardforks(); - } - var posHf1 = -1, posHf2 = -1; - var index = 0; - for (var _i = 0, hardforks_2 = hardforks; _i < hardforks_2.length; _i++) { - var hf = hardforks_2[_i]; - if (hf['name'] === hardfork1) - posHf1 = index; - if (hf['name'] === hardfork2) - posHf2 = index; - index += 1; - } - return posHf1 >= posHf2; - }; - /** - * Alias to hardforkGteHardfork when hardfork is set - * @param hardfork Hardfork name - * @param opts Hardfork options - * @returns True if hardfork set is greater than hardfork provided - */ - Common.prototype.gteHardfork = function (hardfork, opts) { - return this.hardforkGteHardfork(null, hardfork, opts); - }; - /** - * Checks if given or set hardfork is active on the chain - * @param hardfork Hardfork name, optional if HF set - * @param opts Hardfork options (onlyActive unused) - * @returns True if hardfork is active on the chain - */ - Common.prototype.hardforkIsActiveOnChain = function (hardfork, opts) { - opts = opts !== undefined ? opts : {}; - var onlySupported = opts.onlySupported === undefined ? false : opts.onlySupported; - hardfork = this._chooseHardfork(hardfork, onlySupported); - for (var _i = 0, _a = this.hardforks(); _i < _a.length; _i++) { - var hf = _a[_i]; - if (hf['name'] === hardfork && hf['block'] !== null) - return true; - } - return false; - }; - /** - * Returns the active hardfork switches for the current chain - * @param blockNumber up to block if provided, otherwise for the whole chain - * @param opts Hardfork options (onlyActive unused) - * @return Array with hardfork arrays - */ - Common.prototype.activeHardforks = function (blockNumber, opts) { - opts = opts !== undefined ? opts : {}; - var activeHardforks = []; - var hfs = this.hardforks(); - for (var _i = 0, hfs_2 = hfs; _i < hfs_2.length; _i++) { - var hf = hfs_2[_i]; - if (hf['block'] === null) - continue; - if (blockNumber !== undefined && blockNumber !== null && blockNumber < hf['block']) - break; - if (opts.onlySupported && !this._isSupportedHardfork(hf['name'])) - continue; - activeHardforks.push(hf); - } - return activeHardforks; - }; - /** - * Returns the latest active hardfork name for chain or block or throws if unavailable - * @param blockNumber up to block if provided, otherwise for the whole chain - * @param opts Hardfork options (onlyActive unused) - * @return Hardfork name - */ - Common.prototype.activeHardfork = function (blockNumber, opts) { - opts = opts !== undefined ? opts : {}; - var activeHardforks = this.activeHardforks(blockNumber, opts); - if (activeHardforks.length > 0) { - return activeHardforks[activeHardforks.length - 1]['name']; - } - else { - throw new Error("No (supported) active hardfork found"); - } - }; - /** - * Returns the hardfork change block for hardfork provided or set - * @param hardfork Hardfork name, optional if HF set - * @returns Block number - */ - Common.prototype.hardforkBlock = function (hardfork) { - hardfork = this._chooseHardfork(hardfork, false); - return this._getHardfork(hardfork)['block']; - }; - /** - * True if block number provided is the hardfork (given or set) change block of the current chain - * @param blockNumber Number of the block to check - * @param hardfork Hardfork name, optional if HF set - * @returns True if blockNumber is HF block - */ - Common.prototype.isHardforkBlock = function (blockNumber, hardfork) { - hardfork = this._chooseHardfork(hardfork, false); - if (this.hardforkBlock(hardfork) === blockNumber) { - return true; - } - else { - return false; - } - }; - /** - * Provide the consensus type for the hardfork set or provided as param - * @param hardfork Hardfork name, optional if hardfork set - * @returns Consensus type (e.g. 'pow', 'poa') - */ - Common.prototype.consensus = function (hardfork) { - hardfork = this._chooseHardfork(hardfork); - return this._getHardfork(hardfork)['consensus']; - }; - /** - * Provide the finality type for the hardfork set or provided as param - * @param {String} hardfork Hardfork name, optional if hardfork set - * @returns {String} Finality type (e.g. 'pos', null of no finality) - */ - Common.prototype.finality = function (hardfork) { - hardfork = this._chooseHardfork(hardfork); - return this._getHardfork(hardfork)['finality']; - }; - /** - * Returns the Genesis parameters of current chain - * @returns Genesis dictionary - */ - Common.prototype.genesis = function () { - return this._chainParams['genesis']; - }; - /** - * Returns the hardforks for current chain - * @returns {Array} Array with arrays of hardforks - */ - Common.prototype.hardforks = function () { - return this._chainParams['hardforks']; - }; - /** - * Returns bootstrap nodes for the current chain - * @returns {Dictionary} Dict with bootstrap nodes - */ - Common.prototype.bootstrapNodes = function () { - return this._chainParams['bootstrapNodes']; - }; - /** - * Returns the hardfork set - * @returns Hardfork name - */ - Common.prototype.hardfork = function () { - return this._hardfork; - }; - /** - * Returns the Id of current chain - * @returns chain Id - */ - Common.prototype.chainId = function () { - return this._chainParams['chainId']; - }; - /** - * Returns the name of current chain - * @returns chain name (lower case) - */ - Common.prototype.chainName = function () { - return chains_1.chains['names'][this.chainId()] || this._chainParams['name']; - }; - /** - * Returns the Id of current network - * @returns network Id - */ - Common.prototype.networkId = function () { - return this._chainParams['networkId']; - }; - return Common; -}()); -exports.default = Common; - -},{"./chains":340,"./hardforks":350}],356:[function(require,module,exports){ -arguments[4][331][0].apply(exports,arguments) -},{"_process":1438,"dup":331}],357:[function(require,module,exports){ -'use strict'; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI -var address_1 = require("./address"); -var bignumber_1 = require("./bignumber"); -var bytes_1 = require("./bytes"); -var utf8_1 = require("./utf8"); -var properties_1 = require("./properties"); -var errors = __importStar(require("./errors")); -var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); -var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); -var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); -exports.defaultCoerceFunc = function (type, value) { - var match = type.match(paramTypeNumber); - if (match && parseInt(match[2]) <= 48) { - return value.toNumber(); - } - return value; -}; -/////////////////////////////////// -// Parsing for Solidity Signatures -var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"); -var regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$"); -function verifyType(type) { - // These need to be transformed to their full description - if (type.match(/^uint($|[^1-9])/)) { - type = 'uint256' + type.substring(4); - } - else if (type.match(/^int($|[^1-9])/)) { - type = 'int256' + type.substring(3); - } - return type; -} -function parseParam(param, allowIndexed) { - function throwError(i) { - throw new Error('unexpected character "' + param[i] + '" at position ' + i + ' in "' + param + '"'); - } - var parent = { type: '', name: '', state: { allowType: true } }; - var node = parent; - for (var i = 0; i < param.length; i++) { - var c = param[i]; - switch (c) { - case '(': - if (!node.state.allowParams) { - throwError(i); - } - node.state.allowType = false; - node.type = verifyType(node.type); - node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }]; - node = node.components[0]; - break; - case ')': - delete node.state; - if (allowIndexed && node.name === 'indexed') { - node.indexed = true; - node.name = ''; - } - node.type = verifyType(node.type); - var child = node; - node = node.parent; - if (!node) { - throwError(i); - } - delete child.parent; - node.state.allowParams = false; - node.state.allowName = true; - node.state.allowArray = true; - break; - case ',': - delete node.state; - if (allowIndexed && node.name === 'indexed') { - node.indexed = true; - node.name = ''; - } - node.type = verifyType(node.type); - var sibling = { type: '', name: '', parent: node.parent, state: { allowType: true } }; - node.parent.components.push(sibling); - delete node.parent; - node = sibling; - break; - // Hit a space... - case ' ': - // If reading type, the type is done and may read a param or name - if (node.state.allowType) { - if (node.type !== '') { - node.type = verifyType(node.type); - delete node.state.allowType; - node.state.allowName = true; - node.state.allowParams = true; - } - } - // If reading name, the name is done - if (node.state.allowName) { - if (node.name !== '') { - if (allowIndexed && node.name === 'indexed') { - node.indexed = true; - node.name = ''; - } - else { - node.state.allowName = false; - } - } - } - break; - case '[': - if (!node.state.allowArray) { - throwError(i); - } - node.type += c; - node.state.allowArray = false; - node.state.allowName = false; - node.state.readArray = true; - break; - case ']': - if (!node.state.readArray) { - throwError(i); - } - node.type += c; - node.state.readArray = false; - node.state.allowArray = true; - node.state.allowName = true; - break; - default: - if (node.state.allowType) { - node.type += c; - node.state.allowParams = true; - node.state.allowArray = true; - } - else if (node.state.allowName) { - node.name += c; - delete node.state.allowArray; - } - else if (node.state.readArray) { - node.type += c; - } - else { - throwError(i); - } - } - } - if (node.parent) { - throw new Error("unexpected eof"); - } - delete parent.state; - if (allowIndexed && node.name === 'indexed') { - node.indexed = true; - node.name = ''; - } - parent.type = verifyType(parent.type); - return parent; -} -// @TODO: Better return type -function parseSignatureEvent(fragment) { - var abi = { - anonymous: false, - inputs: [], - name: '', - type: 'event' - }; - var match = fragment.match(regexParen); - if (!match) { - throw new Error('invalid event: ' + fragment); - } - abi.name = match[1].trim(); - splitNesting(match[2]).forEach(function (param) { - param = parseParam(param, true); - param.indexed = !!param.indexed; - abi.inputs.push(param); - }); - match[3].split(' ').forEach(function (modifier) { - switch (modifier) { - case 'anonymous': - abi.anonymous = true; - break; - case '': - break; - default: - console.log('unknown modifier: ' + modifier); - } - }); - if (abi.name && !abi.name.match(regexIdentifier)) { - throw new Error('invalid identifier: "' + abi.name + '"'); - } - return abi; -} -function parseSignatureFunction(fragment) { - var abi = { - constant: false, - inputs: [], - name: '', - outputs: [], - payable: false, - stateMutability: null, - type: 'function' - }; - var comps = fragment.split(' returns '); - var left = comps[0].match(regexParen); - if (!left) { - throw new Error('invalid signature'); - } - abi.name = left[1].trim(); - if (!abi.name.match(regexIdentifier)) { - throw new Error('invalid identifier: "' + left[1] + '"'); - } - splitNesting(left[2]).forEach(function (param) { - abi.inputs.push(parseParam(param)); - }); - left[3].split(' ').forEach(function (modifier) { - switch (modifier) { - case 'constant': - abi.constant = true; - break; - case 'payable': - abi.payable = true; - break; - case 'pure': - abi.constant = true; - abi.stateMutability = 'pure'; - break; - case 'view': - abi.constant = true; - abi.stateMutability = 'view'; - break; - case '': - break; - default: - console.log('unknown modifier: ' + modifier); - } - }); - // We have outputs - if (comps.length > 1) { - var right = comps[1].match(regexParen); - if (right[1].trim() != '' || right[3].trim() != '') { - throw new Error('unexpected tokens'); - } - splitNesting(right[2]).forEach(function (param) { - abi.outputs.push(parseParam(param)); - }); - } - return abi; -} -function parseParamType(type) { - return parseParam(type, true); -} -exports.parseParamType = parseParamType; -// @TODO: Allow a second boolean to expose names -function formatParamType(paramType) { - return getParamCoder(exports.defaultCoerceFunc, paramType).type; -} -exports.formatParamType = formatParamType; -// @TODO: Allow a second boolean to expose names and modifiers -function formatSignature(fragment) { - return fragment.name + '(' + fragment.inputs.map(function (i) { return formatParamType(i); }).join(',') + ')'; -} -exports.formatSignature = formatSignature; -function parseSignature(fragment) { - if (typeof (fragment) === 'string') { - // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space - fragment = fragment.replace(/\(/g, ' (').replace(/\)/g, ') ').replace(/\s+/g, ' '); - fragment = fragment.trim(); - if (fragment.substring(0, 6) === 'event ') { - return parseSignatureEvent(fragment.substring(6).trim()); - } - else { - if (fragment.substring(0, 9) === 'function ') { - fragment = fragment.substring(9); - } - return parseSignatureFunction(fragment.trim()); - } - } - throw new Error('unknown signature'); -} -exports.parseSignature = parseSignature; -var Coder = /** @class */ (function () { - function Coder(coerceFunc, name, type, localName, dynamic) { - this.coerceFunc = coerceFunc; - this.name = name; - this.type = type; - this.localName = localName; - this.dynamic = dynamic; - } - return Coder; -}()); -// Clones the functionality of an existing Coder, but without a localName -var CoderAnonymous = /** @class */ (function (_super) { - __extends(CoderAnonymous, _super); - function CoderAnonymous(coder) { - var _this = _super.call(this, coder.coerceFunc, coder.name, coder.type, undefined, coder.dynamic) || this; - properties_1.defineReadOnly(_this, 'coder', coder); - return _this; - } - CoderAnonymous.prototype.encode = function (value) { return this.coder.encode(value); }; - CoderAnonymous.prototype.decode = function (data, offset) { return this.coder.decode(data, offset); }; - return CoderAnonymous; -}(Coder)); -var CoderNull = /** @class */ (function (_super) { - __extends(CoderNull, _super); - function CoderNull(coerceFunc, localName) { - return _super.call(this, coerceFunc, 'null', '', localName, false) || this; - } - CoderNull.prototype.encode = function (value) { - return bytes_1.arrayify([]); - }; - CoderNull.prototype.decode = function (data, offset) { - if (offset > data.length) { - throw new Error('invalid null'); - } - return { - consumed: 0, - value: this.coerceFunc('null', undefined) - }; - }; - return CoderNull; -}(Coder)); -var CoderNumber = /** @class */ (function (_super) { - __extends(CoderNumber, _super); - function CoderNumber(coerceFunc, size, signed, localName) { - var _this = this; - var name = ((signed ? 'int' : 'uint') + (size * 8)); - _this = _super.call(this, coerceFunc, name, name, localName, false) || this; - _this.size = size; - _this.signed = signed; - return _this; - } - CoderNumber.prototype.encode = function (value) { - try { - var v = bignumber_1.bigNumberify(value); - v = v.toTwos(this.size * 8).maskn(this.size * 8); - //value = value.toTwos(size * 8).maskn(size * 8); - if (this.signed) { - v = v.fromTwos(this.size * 8).toTwos(256); - } - return bytes_1.padZeros(bytes_1.arrayify(v), 32); - } - catch (error) { - errors.throwError('invalid number value', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: this.name, - value: value - }); - } - return null; - }; - CoderNumber.prototype.decode = function (data, offset) { - if (data.length < offset + 32) { - errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: this.name, - value: bytes_1.hexlify(data.slice(offset, offset + 32)) - }); - } - var junkLength = 32 - this.size; - var value = bignumber_1.bigNumberify(data.slice(offset + junkLength, offset + 32)); - if (this.signed) { - value = value.fromTwos(this.size * 8); - } - else { - value = value.maskn(this.size * 8); - } - return { - consumed: 32, - value: this.coerceFunc(this.name, value), - }; - }; - return CoderNumber; -}(Coder)); -var uint256Coder = new CoderNumber(function (type, value) { return value; }, 32, false, 'none'); -var CoderBoolean = /** @class */ (function (_super) { - __extends(CoderBoolean, _super); - function CoderBoolean(coerceFunc, localName) { - return _super.call(this, coerceFunc, 'bool', 'bool', localName, false) || this; - } - CoderBoolean.prototype.encode = function (value) { - return uint256Coder.encode(!!value ? 1 : 0); - }; - CoderBoolean.prototype.decode = function (data, offset) { - try { - var result = uint256Coder.decode(data, offset); - } - catch (error) { - if (error.reason === 'insufficient data for uint256 type') { - errors.throwError('insufficient data for boolean type', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'boolean', - value: error.value - }); - } - throw error; - } - return { - consumed: result.consumed, - value: this.coerceFunc('bool', !result.value.isZero()) - }; - }; - return CoderBoolean; -}(Coder)); -var CoderFixedBytes = /** @class */ (function (_super) { - __extends(CoderFixedBytes, _super); - function CoderFixedBytes(coerceFunc, length, localName) { - var _this = this; - var name = ('bytes' + length); - _this = _super.call(this, coerceFunc, name, name, localName, false) || this; - _this.length = length; - return _this; - } - CoderFixedBytes.prototype.encode = function (value) { - var result = new Uint8Array(32); - try { - var data = bytes_1.arrayify(value); - if (data.length > 32) { - throw new Error(); - } - result.set(data); - } - catch (error) { - errors.throwError('invalid ' + this.name + ' value', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: this.name, - value: (error.value || value) - }); - } - return result; - }; - CoderFixedBytes.prototype.decode = function (data, offset) { - if (data.length < offset + 32) { - errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: this.name, - value: bytes_1.hexlify(data.slice(offset, offset + 32)) - }); - } - return { - consumed: 32, - value: this.coerceFunc(this.name, bytes_1.hexlify(data.slice(offset, offset + this.length))) - }; - }; - return CoderFixedBytes; -}(Coder)); -var CoderAddress = /** @class */ (function (_super) { - __extends(CoderAddress, _super); - function CoderAddress(coerceFunc, localName) { - return _super.call(this, coerceFunc, 'address', 'address', localName, false) || this; - } - CoderAddress.prototype.encode = function (value) { - var result = new Uint8Array(32); - try { - result.set(bytes_1.arrayify(address_1.getAddress(value)), 12); - } - catch (error) { - errors.throwError('invalid address', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'address', - value: value - }); - } - return result; - }; - CoderAddress.prototype.decode = function (data, offset) { - if (data.length < offset + 32) { - errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'address', - value: bytes_1.hexlify(data.slice(offset, offset + 32)) - }); - } - return { - consumed: 32, - value: this.coerceFunc('address', address_1.getAddress(bytes_1.hexlify(data.slice(offset + 12, offset + 32)))) - }; - }; - return CoderAddress; -}(Coder)); -function _encodeDynamicBytes(value) { - var dataLength = 32 * Math.ceil(value.length / 32); - var padding = new Uint8Array(dataLength - value.length); - return bytes_1.concat([ - uint256Coder.encode(value.length), - value, - padding - ]); -} -function _decodeDynamicBytes(data, offset, localName) { - if (data.length < offset + 32) { - errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, { - arg: localName, - coderType: 'dynamicBytes', - value: bytes_1.hexlify(data.slice(offset, offset + 32)) - }); - } - var length = uint256Coder.decode(data, offset).value; - try { - length = length.toNumber(); - } - catch (error) { - errors.throwError('dynamic bytes count too large', errors.INVALID_ARGUMENT, { - arg: localName, - coderType: 'dynamicBytes', - value: length.toString() - }); - } - if (data.length < offset + 32 + length) { - errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, { - arg: localName, - coderType: 'dynamicBytes', - value: bytes_1.hexlify(data.slice(offset, offset + 32 + length)) - }); - } - return { - consumed: 32 + 32 * Math.ceil(length / 32), - value: data.slice(offset + 32, offset + 32 + length), - }; -} -var CoderDynamicBytes = /** @class */ (function (_super) { - __extends(CoderDynamicBytes, _super); - function CoderDynamicBytes(coerceFunc, localName) { - return _super.call(this, coerceFunc, 'bytes', 'bytes', localName, true) || this; - } - CoderDynamicBytes.prototype.encode = function (value) { - try { - return _encodeDynamicBytes(bytes_1.arrayify(value)); - } - catch (error) { - errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'bytes', - value: error.value - }); - } - return null; - }; - CoderDynamicBytes.prototype.decode = function (data, offset) { - var result = _decodeDynamicBytes(data, offset, this.localName); - result.value = this.coerceFunc('bytes', bytes_1.hexlify(result.value)); - return result; - }; - return CoderDynamicBytes; -}(Coder)); -var CoderString = /** @class */ (function (_super) { - __extends(CoderString, _super); - function CoderString(coerceFunc, localName) { - return _super.call(this, coerceFunc, 'string', 'string', localName, true) || this; - } - CoderString.prototype.encode = function (value) { - if (typeof (value) !== 'string') { - errors.throwError('invalid string value', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'string', - value: value - }); - } - return _encodeDynamicBytes(utf8_1.toUtf8Bytes(value)); - }; - CoderString.prototype.decode = function (data, offset) { - var result = _decodeDynamicBytes(data, offset, this.localName); - result.value = this.coerceFunc('string', utf8_1.toUtf8String(result.value)); - return result; - }; - return CoderString; -}(Coder)); -function alignSize(size) { - return 32 * Math.ceil(size / 32); -} -function pack(coders, values) { - if (Array.isArray(values)) { - // do nothing - } - else if (values && typeof (values) === 'object') { - var arrayValues = []; - coders.forEach(function (coder) { - arrayValues.push(values[coder.localName]); - }); - values = arrayValues; - } - else { - errors.throwError('invalid tuple value', errors.INVALID_ARGUMENT, { - coderType: 'tuple', - value: values - }); - } - if (coders.length !== values.length) { - errors.throwError('types/value length mismatch', errors.INVALID_ARGUMENT, { - coderType: 'tuple', - value: values - }); - } - var parts = []; - coders.forEach(function (coder, index) { - parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); - }); - var staticSize = 0, dynamicSize = 0; - parts.forEach(function (part) { - if (part.dynamic) { - staticSize += 32; - dynamicSize += alignSize(part.value.length); - } - else { - staticSize += alignSize(part.value.length); - } - }); - var offset = 0, dynamicOffset = staticSize; - var data = new Uint8Array(staticSize + dynamicSize); - parts.forEach(function (part) { - if (part.dynamic) { - //uint256Coder.encode(dynamicOffset).copy(data, offset); - data.set(uint256Coder.encode(dynamicOffset), offset); - offset += 32; - //part.value.copy(data, dynamicOffset); @TODO - data.set(part.value, dynamicOffset); - dynamicOffset += alignSize(part.value.length); - } - else { - //part.value.copy(data, offset); @TODO - data.set(part.value, offset); - offset += alignSize(part.value.length); - } - }); - return data; -} -function unpack(coders, data, offset) { - var baseOffset = offset; - var consumed = 0; - var value = []; - coders.forEach(function (coder) { - if (coder.dynamic) { - var dynamicOffset = uint256Coder.decode(data, offset); - var result = coder.decode(data, baseOffset + dynamicOffset.value.toNumber()); - // The dynamic part is leap-frogged somewhere else; doesn't count towards size - result.consumed = dynamicOffset.consumed; - } - else { - var result = coder.decode(data, offset); - } - if (result.value != undefined) { - value.push(result.value); - } - offset += result.consumed; - consumed += result.consumed; - }); - coders.forEach(function (coder, index) { - var name = coder.localName; - if (!name) { - return; - } - if (name === 'length') { - name = '_length'; - } - if (value[name] != null) { - return; - } - value[name] = value[index]; - }); - return { - value: value, - consumed: consumed - }; -} -var CoderArray = /** @class */ (function (_super) { - __extends(CoderArray, _super); - function CoderArray(coerceFunc, coder, length, localName) { - var _this = this; - var type = (coder.type + '[' + (length >= 0 ? length : '') + ']'); - var dynamic = (length === -1 || coder.dynamic); - _this = _super.call(this, coerceFunc, 'array', type, localName, dynamic) || this; - _this.coder = coder; - _this.length = length; - return _this; - } - CoderArray.prototype.encode = function (value) { - if (!Array.isArray(value)) { - errors.throwError('expected array value', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'array', - value: value - }); - } - var count = this.length; - var result = new Uint8Array(0); - if (count === -1) { - count = value.length; - result = uint256Coder.encode(count); - } - errors.checkArgumentCount(count, value.length, 'in coder array' + (this.localName ? (" " + this.localName) : "")); - var coders = []; - for (var i = 0; i < value.length; i++) { - coders.push(this.coder); - } - return bytes_1.concat([result, pack(coders, value)]); - }; - CoderArray.prototype.decode = function (data, offset) { - // @TODO: - //if (data.length < offset + length * 32) { throw new Error('invalid array'); } - var consumed = 0; - var count = this.length; - if (count === -1) { - try { - var decodedLength = uint256Coder.decode(data, offset); - } - catch (error) { - errors.throwError('insufficient data for dynamic array length', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'array', - value: error.value - }); - } - try { - count = decodedLength.value.toNumber(); - } - catch (error) { - errors.throwError('array count too large', errors.INVALID_ARGUMENT, { - arg: this.localName, - coderType: 'array', - value: decodedLength.value.toString() - }); - } - consumed += decodedLength.consumed; - offset += decodedLength.consumed; - } - var coders = []; - for (var i = 0; i < count; i++) { - coders.push(new CoderAnonymous(this.coder)); - } - var result = unpack(coders, data, offset); - result.consumed += consumed; - result.value = this.coerceFunc(this.type, result.value); - return result; - }; - return CoderArray; -}(Coder)); -var CoderTuple = /** @class */ (function (_super) { - __extends(CoderTuple, _super); - function CoderTuple(coerceFunc, coders, localName) { - var _this = this; - var dynamic = false; - var types = []; - coders.forEach(function (coder) { - if (coder.dynamic) { - dynamic = true; - } - types.push(coder.type); - }); - var type = ('tuple(' + types.join(',') + ')'); - _this = _super.call(this, coerceFunc, 'tuple', type, localName, dynamic) || this; - _this.coders = coders; - return _this; - } - CoderTuple.prototype.encode = function (value) { - return pack(this.coders, value); - }; - CoderTuple.prototype.decode = function (data, offset) { - var result = unpack(this.coders, data, offset); - result.value = this.coerceFunc(this.type, result.value); - return result; - }; - return CoderTuple; -}(Coder)); -/* -function getTypes(coders) { - var type = coderTuple(coders).type; - return type.substring(6, type.length - 1); -} -*/ -function splitNesting(value) { - var result = []; - var accum = ''; - var depth = 0; - for (var offset = 0; offset < value.length; offset++) { - var c = value[offset]; - if (c === ',' && depth === 0) { - result.push(accum); - accum = ''; - } - else { - accum += c; - if (c === '(') { - depth++; - } - else if (c === ')') { - depth--; - if (depth === -1) { - throw new Error('unbalanced parenthsis'); - } - } - } - } - result.push(accum); - return result; -} -// @TODO: Is there a way to return "class"? -var paramTypeSimple = { - address: CoderAddress, - bool: CoderBoolean, - string: CoderString, - bytes: CoderDynamicBytes, -}; -function getTupleParamCoder(coerceFunc, components, localName) { - if (!components) { - components = []; - } - var coders = []; - components.forEach(function (component) { - coders.push(getParamCoder(coerceFunc, component)); - }); - return new CoderTuple(coerceFunc, coders, localName); -} -function getParamCoder(coerceFunc, param) { - var coder = paramTypeSimple[param.type]; - if (coder) { - return new coder(coerceFunc, param.name); - } - var match = param.type.match(paramTypeNumber); - if (match) { - var size = parseInt(match[2] || "256"); - if (size === 0 || size > 256 || (size % 8) !== 0) { - errors.throwError('invalid ' + match[1] + ' bit length', errors.INVALID_ARGUMENT, { - arg: 'param', - value: param - }); - } - return new CoderNumber(coerceFunc, size / 8, (match[1] === 'int'), param.name); - } - var match = param.type.match(paramTypeBytes); - if (match) { - var size = parseInt(match[1]); - if (size === 0 || size > 32) { - errors.throwError('invalid bytes length', errors.INVALID_ARGUMENT, { - arg: 'param', - value: param - }); - } - return new CoderFixedBytes(coerceFunc, size, param.name); - } - var match = param.type.match(paramTypeArray); - if (match) { - var size = parseInt(match[2] || "-1"); - param = properties_1.jsonCopy(param); - param.type = match[1]; - return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name); - } - if (param.type.substring(0, 5) === 'tuple') { - return getTupleParamCoder(coerceFunc, param.components, param.name); - } - if (param.type === '') { - return new CoderNull(coerceFunc, param.name); - } - errors.throwError('invalid type', errors.INVALID_ARGUMENT, { - arg: 'type', - value: param.type - }); - return null; -} -var AbiCoder = /** @class */ (function () { - function AbiCoder(coerceFunc) { - errors.checkNew(this, AbiCoder); - if (!coerceFunc) { - coerceFunc = exports.defaultCoerceFunc; - } - properties_1.defineReadOnly(this, 'coerceFunc', coerceFunc); - } - AbiCoder.prototype.encode = function (types, values) { - if (types.length !== values.length) { - errors.throwError('types/values length mismatch', errors.INVALID_ARGUMENT, { - count: { types: types.length, values: values.length }, - value: { types: types, values: values } - }); - } - var coders = []; - types.forEach(function (type) { - // Convert types to type objects - // - "uint foo" => { type: "uint", name: "foo" } - // - "tuple(uint, uint)" => { type: "tuple", components: [ { type: "uint" }, { type: "uint" }, ] } - var typeObject = null; - if (typeof (type) === 'string') { - typeObject = parseParam(type); - } - else { - typeObject = type; - } - coders.push(getParamCoder(this.coerceFunc, typeObject)); - }, this); - return bytes_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values)); - }; - AbiCoder.prototype.decode = function (types, data) { - var coders = []; - types.forEach(function (type) { - // See encode for details - var typeObject = null; - if (typeof (type) === 'string') { - typeObject = parseParam(type); - } - else { - typeObject = properties_1.jsonCopy(type); - } - coders.push(getParamCoder(this.coerceFunc, typeObject)); - }, this); - return new CoderTuple(this.coerceFunc, coders, '_').decode(bytes_1.arrayify(data), 0).value; - }; - return AbiCoder; -}()); -exports.AbiCoder = AbiCoder; -exports.defaultAbiCoder = new AbiCoder(); - -},{"./address":358,"./bignumber":359,"./bytes":360,"./errors":361,"./properties":363,"./utf8":366}],358:[function(require,module,exports){ -'use strict'; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -// We use this for base 36 maths -var bn_js_1 = __importDefault(require("bn.js")); -var bytes_1 = require("./bytes"); -var keccak256_1 = require("./keccak256"); -var rlp_1 = require("./rlp"); -var errors = require("./errors"); -function getChecksumAddress(address) { - if (typeof (address) !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) { - errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); - } - address = address.toLowerCase(); - var chars = address.substring(2).split(''); - var hashed = new Uint8Array(40); - for (var i_1 = 0; i_1 < 40; i_1++) { - hashed[i_1] = chars[i_1].charCodeAt(0); - } - hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed)); - for (var i = 0; i < 40; i += 2) { - if ((hashed[i >> 1] >> 4) >= 8) { - chars[i] = chars[i].toUpperCase(); - } - if ((hashed[i >> 1] & 0x0f) >= 8) { - chars[i + 1] = chars[i + 1].toUpperCase(); - } - } - return '0x' + chars.join(''); -} -// Shims for environments that are missing some required constants and functions -var MAX_SAFE_INTEGER = 0x1fffffffffffff; -function log10(x) { - if (Math.log10) { - return Math.log10(x); - } - return Math.log(x) / Math.LN10; -} -// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number -// Create lookup table -var ibanLookup = {}; -for (var i = 0; i < 10; i++) { - ibanLookup[String(i)] = String(i); -} -for (var i = 0; i < 26; i++) { - ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); -} -// How many decimal digits can we process? (for 64-bit float, this is 15) -var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER)); -function ibanChecksum(address) { - address = address.toUpperCase(); - address = address.substring(4) + address.substring(0, 2) + '00'; - var expanded = ''; - address.split('').forEach(function (c) { - expanded += ibanLookup[c]; - }); - // Javascript can handle integers safely up to 15 (decimal) digits - while (expanded.length >= safeDigits) { - var block = expanded.substring(0, safeDigits); - expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); - } - var checksum = String(98 - (parseInt(expanded, 10) % 97)); - while (checksum.length < 2) { - checksum = '0' + checksum; - } - return checksum; -} -; -function getAddress(address) { - var result = null; - if (typeof (address) !== 'string') { - errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); - } - if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - // Missing the 0x prefix - if (address.substring(0, 2) !== '0x') { - address = '0x' + address; - } - result = getChecksumAddress(address); - // It is a checksummed address with a bad checksum - if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { - errors.throwError('bad address checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); - } - // Maybe ICAP? (we only support direct mode) - } - else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - // It is an ICAP address with a bad checksum - if (address.substring(2, 4) !== ibanChecksum(address)) { - errors.throwError('bad icap checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); - } - result = (new bn_js_1.default.BN(address.substring(4), 36)).toString(16); - while (result.length < 40) { - result = '0' + result; - } - result = getChecksumAddress('0x' + result); - } - else { - errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); - } - return result; -} -exports.getAddress = getAddress; -function getIcapAddress(address) { - var base36 = (new bn_js_1.default.BN(getAddress(address).substring(2), 16)).toString(36).toUpperCase(); - while (base36.length < 30) { - base36 = '0' + base36; - } - return 'XE' + ibanChecksum('XE00' + base36) + base36; -} -exports.getIcapAddress = getIcapAddress; -// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed -function getContractAddress(transaction) { - if (!transaction.from) { - throw new Error('missing from address'); - } - var nonce = transaction.nonce; - return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([ - getAddress(transaction.from), - bytes_1.stripZeros(bytes_1.hexlify(nonce)) - ])).substring(26)); -} -exports.getContractAddress = getContractAddress; - -},{"./bytes":360,"./errors":361,"./keccak256":362,"./rlp":364,"bn.js":171}],359:[function(require,module,exports){ -'use strict'; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * BigNumber - * - * A wrapper around the BN.js object. We use the BN.js library - * because it is used by elliptic, so it is required regardles. - * - */ -var bn_js_1 = __importDefault(require("bn.js")); -var bytes_1 = require("./bytes"); -var properties_1 = require("./properties"); -var types_1 = require("./types"); -var errors = __importStar(require("./errors")); -var BN_1 = new bn_js_1.default.BN(-1); -function toHex(bn) { - var value = bn.toString(16); - if (value[0] === '-') { - if ((value.length % 2) === 0) { - return '-0x0' + value.substring(1); - } - return "-0x" + value.substring(1); - } - if ((value.length % 2) === 1) { - return '0x0' + value; - } - return '0x' + value; -} -function toBN(value) { - return bigNumberify(value)._bn; -} -function toBigNumber(bn) { - return new BigNumber(toHex(bn)); -} -var BigNumber = /** @class */ (function (_super) { - __extends(BigNumber, _super); - function BigNumber(value) { - var _this = _super.call(this) || this; - errors.checkNew(_this, BigNumber); - if (typeof (value) === 'string') { - if (bytes_1.isHexString(value)) { - if (value == '0x') { - value = '0x0'; - } - properties_1.defineReadOnly(_this, '_hex', value); - } - else if (value[0] === '-' && bytes_1.isHexString(value.substring(1))) { - properties_1.defineReadOnly(_this, '_hex', value); - } - else if (value.match(/^-?[0-9]*$/)) { - if (value == '') { - value = '0'; - } - properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); - } - else { - errors.throwError('invalid BigNumber string value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - } - else if (typeof (value) === 'number') { - if (parseInt(String(value)) !== value) { - errors.throwError('underflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'underflow', value: value, outputValue: parseInt(String(value)) }); - } - try { - properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); - } - catch (error) { - errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); - } - } - else if (value instanceof BigNumber) { - properties_1.defineReadOnly(_this, '_hex', value._hex); - } - else if (value.toHexString) { - properties_1.defineReadOnly(_this, '_hex', toHex(toBN(value.toHexString()))); - } - else if (bytes_1.isArrayish(value)) { - properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(bytes_1.hexlify(value).substring(2), 16))); - } - else { - errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - return _this; - } - Object.defineProperty(BigNumber.prototype, "_bn", { - get: function () { - if (this._hex[0] === '-') { - return (new bn_js_1.default.BN(this._hex.substring(3), 16)).mul(BN_1); - } - return new bn_js_1.default.BN(this._hex.substring(2), 16); - }, - enumerable: true, - configurable: true - }); - BigNumber.prototype.fromTwos = function (value) { - return toBigNumber(this._bn.fromTwos(value)); - }; - BigNumber.prototype.toTwos = function (value) { - return toBigNumber(this._bn.toTwos(value)); - }; - BigNumber.prototype.add = function (other) { - return toBigNumber(this._bn.add(toBN(other))); - }; - BigNumber.prototype.sub = function (other) { - return toBigNumber(this._bn.sub(toBN(other))); - }; - BigNumber.prototype.div = function (other) { - var o = bigNumberify(other); - if (o.isZero()) { - errors.throwError('division by zero', errors.NUMERIC_FAULT, { operation: 'divide', fault: 'division by zero' }); - } - return toBigNumber(this._bn.div(toBN(other))); - }; - BigNumber.prototype.mul = function (other) { - return toBigNumber(this._bn.mul(toBN(other))); - }; - BigNumber.prototype.mod = function (other) { - return toBigNumber(this._bn.mod(toBN(other))); - }; - BigNumber.prototype.pow = function (other) { - return toBigNumber(this._bn.pow(toBN(other))); - }; - BigNumber.prototype.maskn = function (value) { - return toBigNumber(this._bn.maskn(value)); - }; - BigNumber.prototype.eq = function (other) { - return this._bn.eq(toBN(other)); - }; - BigNumber.prototype.lt = function (other) { - return this._bn.lt(toBN(other)); - }; - BigNumber.prototype.lte = function (other) { - return this._bn.lte(toBN(other)); - }; - BigNumber.prototype.gt = function (other) { - return this._bn.gt(toBN(other)); - }; - BigNumber.prototype.gte = function (other) { - return this._bn.gte(toBN(other)); - }; - BigNumber.prototype.isZero = function () { - return this._bn.isZero(); - }; - BigNumber.prototype.toNumber = function () { - try { - return this._bn.toNumber(); - } - catch (error) { - errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); - } - return null; - }; - BigNumber.prototype.toString = function () { - return this._bn.toString(10); - }; - BigNumber.prototype.toHexString = function () { - return this._hex; - }; - return BigNumber; -}(types_1.BigNumber)); -function bigNumberify(value) { - if (value instanceof BigNumber) { - return value; - } - return new BigNumber(value); -} -exports.bigNumberify = bigNumberify; -exports.ConstantNegativeOne = bigNumberify(-1); -exports.ConstantZero = bigNumberify(0); -exports.ConstantOne = bigNumberify(1); -exports.ConstantTwo = bigNumberify(2); -exports.ConstantWeiPerEther = bigNumberify('1000000000000000000'); - -},{"./bytes":360,"./errors":361,"./properties":363,"./types":365,"bn.js":171}],360:[function(require,module,exports){ -"use strict"; -/** - * Conversion Utilities - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -var types_1 = require("./types"); -var errors = require("./errors"); -exports.AddressZero = '0x0000000000000000000000000000000000000000'; -exports.HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000'; -function isBigNumber(value) { - return (value instanceof types_1.BigNumber); -} -function addSlice(array) { - if (array.slice) { - return array; - } - array.slice = function () { - var args = Array.prototype.slice.call(arguments); - return new Uint8Array(Array.prototype.slice.apply(array, args)); - }; - return array; -} -function isArrayish(value) { - if (!value || parseInt(String(value.length)) != value.length || typeof (value) === 'string') { - return false; - } - for (var i = 0; i < value.length; i++) { - var v = value[i]; - if (v < 0 || v >= 256 || parseInt(String(v)) != v) { - return false; - } - } - return true; -} -exports.isArrayish = isArrayish; -function arrayify(value) { - if (value == null) { - errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - if (isBigNumber(value)) { - value = value.toHexString(); - } - if (typeof (value) === 'string') { - var match = value.match(/^(0x)?[0-9a-fA-F]*$/); - if (!match) { - errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - if (match[1] !== '0x') { - errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - value = value.substring(2); - if (value.length % 2) { - value = '0' + value; - } - var result = []; - for (var i = 0; i < value.length; i += 2) { - result.push(parseInt(value.substr(i, 2), 16)); - } - return addSlice(new Uint8Array(result)); - } - else if (typeof (value) === 'string') { - } - if (isArrayish(value)) { - return addSlice(new Uint8Array(value)); - } - errors.throwError('invalid arrayify value', null, { arg: 'value', value: value, type: typeof (value) }); - return null; -} -exports.arrayify = arrayify; -function concat(objects) { - var arrays = []; - var length = 0; - for (var i = 0; i < objects.length; i++) { - var object = arrayify(objects[i]); - arrays.push(object); - length += object.length; - } - var result = new Uint8Array(length); - var offset = 0; - for (var i = 0; i < arrays.length; i++) { - result.set(arrays[i], offset); - offset += arrays[i].length; - } - return addSlice(result); -} -exports.concat = concat; -function stripZeros(value) { - var result = arrayify(value); - if (result.length === 0) { - return result; - } - // Find the first non-zero entry - var start = 0; - while (result[start] === 0) { - start++; - } - // If we started with zeros, strip them - if (start) { - result = result.slice(start); - } - return result; -} -exports.stripZeros = stripZeros; -function padZeros(value, length) { - value = arrayify(value); - if (length < value.length) { - throw new Error('cannot pad'); - } - var result = new Uint8Array(length); - result.set(value, length - value.length); - return addSlice(result); -} -exports.padZeros = padZeros; -function isHexString(value, length) { - if (typeof (value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - if (length && value.length !== 2 + 2 * length) { - return false; - } - return true; -} -exports.isHexString = isHexString; -var HexCharacters = '0123456789abcdef'; -function hexlify(value) { - if (isBigNumber(value)) { - return value.toHexString(); - } - if (typeof (value) === 'number') { - if (value < 0) { - errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - var hex = ''; - while (value) { - hex = HexCharacters[value & 0x0f] + hex; - value = Math.floor(value / 16); - } - if (hex.length) { - if (hex.length % 2) { - hex = '0' + hex; - } - return '0x' + hex; - } - return '0x00'; - } - if (typeof (value) === 'string') { - var match = value.match(/^(0x)?[0-9a-fA-F]*$/); - if (!match) { - errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - if (match[1] !== '0x') { - errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - if (value.length % 2) { - value = '0x0' + value.substring(2); - } - return value; - } - if (isArrayish(value)) { - var result = []; - for (var i = 0; i < value.length; i++) { - var v = value[i]; - result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]); - } - return '0x' + result.join(''); - } - errors.throwError('invalid hexlify value', null, { arg: 'value', value: value }); - return 'never'; -} -exports.hexlify = hexlify; -function hexDataLength(data) { - if (!isHexString(data) || (data.length % 2) !== 0) { - return null; - } - return (data.length - 2) / 2; -} -exports.hexDataLength = hexDataLength; -function hexDataSlice(data, offset, length) { - if (!isHexString(data)) { - errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); - } - if ((data.length % 2) !== 0) { - errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); - } - offset = 2 + 2 * offset; - if (length != null) { - return '0x' + data.substring(offset, offset + 2 * length); - } - return '0x' + data.substring(offset); -} -exports.hexDataSlice = hexDataSlice; -function hexStripZeros(value) { - if (!isHexString(value)) { - errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - while (value.length > 3 && value.substring(0, 3) === '0x0') { - value = '0x' + value.substring(3); - } - return value; -} -exports.hexStripZeros = hexStripZeros; -function hexZeroPad(value, length) { - if (!isHexString(value)) { - errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); - } - while (value.length < 2 * length + 2) { - value = '0x0' + value.substring(2); - } - return value; -} -exports.hexZeroPad = hexZeroPad; -function isSignature(value) { - return (value && value.r != null && value.s != null); -} -function splitSignature(signature) { - var v = 0; - var r = '0x', s = '0x'; - if (isSignature(signature)) { - if (signature.v == null && signature.recoveryParam == null) { - errors.throwError('at least on of recoveryParam or v must be specified', errors.INVALID_ARGUMENT, { argument: 'signature', value: signature }); - } - r = hexZeroPad(signature.r, 32); - s = hexZeroPad(signature.s, 32); - v = signature.v; - if (typeof (v) === 'string') { - v = parseInt(v, 16); - } - var recoveryParam = signature.recoveryParam; - if (recoveryParam == null && signature.v != null) { - recoveryParam = 1 - (v % 2); - } - v = 27 + recoveryParam; - } - else { - var bytes = arrayify(signature); - if (bytes.length !== 65) { - throw new Error('invalid signature'); - } - r = hexlify(bytes.slice(0, 32)); - s = hexlify(bytes.slice(32, 64)); - v = bytes[64]; - if (v !== 27 && v !== 28) { - v = 27 + (v % 2); - } - } - return { - r: r, - s: s, - recoveryParam: (v - 27), - v: v - }; -} -exports.splitSignature = splitSignature; -function joinSignature(signature) { - signature = splitSignature(signature); - return hexlify(concat([ - signature.r, - signature.s, - (signature.recoveryParam ? '0x1c' : '0x1b') - ])); -} -exports.joinSignature = joinSignature; - -},{"./errors":361,"./types":365}],361:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -// Unknown Error -exports.UNKNOWN_ERROR = 'UNKNOWN_ERROR'; -// Not implemented -exports.NOT_IMPLEMENTED = 'NOT_IMPLEMENTED'; -// Missing new operator to an object -// - name: The name of the class -exports.MISSING_NEW = 'MISSING_NEW'; -// Call exception -// - transaction: the transaction -// - address?: the contract address -// - args?: The arguments passed into the function -// - method?: The Solidity method signature -// - errorSignature?: The EIP848 error signature -// - errorArgs?: The EIP848 error parameters -// - reason: The reason (only for EIP848 "Error(string)") -exports.CALL_EXCEPTION = 'CALL_EXCEPTION'; -// Response from a server was invalid -// - response: The body of the response -//'BAD_RESPONSE', -// Invalid argument (e.g. value is incompatible with type) to a function: -// - arg: The argument name that was invalid -// - value: The value of the argument -exports.INVALID_ARGUMENT = 'INVALID_ARGUMENT'; -// Missing argument to a function: -// - count: The number of arguments received -// - expectedCount: The number of arguments expected -exports.MISSING_ARGUMENT = 'MISSING_ARGUMENT'; -// Too many arguments -// - count: The number of arguments received -// - expectedCount: The number of arguments expected -exports.UNEXPECTED_ARGUMENT = 'UNEXPECTED_ARGUMENT'; -// Numeric Fault -// - operation: the operation being executed -// - fault: the reason this faulted -exports.NUMERIC_FAULT = 'NUMERIC_FAULT'; -// Unsupported operation -// - operation -exports.UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION'; -var _permanentCensorErrors = false; -var _censorErrors = false; -// @TODO: Enum -function throwError(message, code, params) { - if (_censorErrors) { - throw new Error('unknown error'); - } - if (!code) { - code = exports.UNKNOWN_ERROR; - } - if (!params) { - params = {}; - } - var messageDetails = []; - Object.keys(params).forEach(function (key) { - try { - messageDetails.push(key + '=' + JSON.stringify(params[key])); - } - catch (error) { - messageDetails.push(key + '=' + JSON.stringify(params[key].toString())); - } - }); - var reason = message; - if (messageDetails.length) { - message += ' (' + messageDetails.join(', ') + ')'; - } - // @TODO: Any?? - var error = new Error(message); - error.reason = reason; - error.code = code; - Object.keys(params).forEach(function (key) { - error[key] = params[key]; - }); - throw error; -} -exports.throwError = throwError; -function checkNew(self, kind) { - if (!(self instanceof kind)) { - throwError('missing new', exports.MISSING_NEW, { name: kind.name }); - } -} -exports.checkNew = checkNew; -function checkArgumentCount(count, expectedCount, suffix) { - if (!suffix) { - suffix = ''; - } - if (count < expectedCount) { - throwError('missing argument' + suffix, exports.MISSING_ARGUMENT, { count: count, expectedCount: expectedCount }); - } - if (count > expectedCount) { - throwError('too many arguments' + suffix, exports.UNEXPECTED_ARGUMENT, { count: count, expectedCount: expectedCount }); - } -} -exports.checkArgumentCount = checkArgumentCount; -function setCensorship(censorship, permanent) { - if (_permanentCensorErrors) { - throwError('error censorship permanent', exports.UNSUPPORTED_OPERATION, { operation: 'setCersorship' }); - } - _censorErrors = !!censorship; - _permanentCensorErrors = !!permanent; -} -exports.setCensorship = setCensorship; - -},{}],362:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -var sha3 = require("js-sha3"); -var bytes_1 = require("./bytes"); -function keccak256(data) { - return '0x' + sha3.keccak_256(bytes_1.arrayify(data)); -} -exports.keccak256 = keccak256; - -},{"./bytes":360,"js-sha3":356}],363:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -function defineReadOnly(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - value: value, - writable: false, - }); -} -exports.defineReadOnly = defineReadOnly; -function defineFrozen(object, name, value) { - var frozen = JSON.stringify(value); - Object.defineProperty(object, name, { - enumerable: true, - get: function () { return JSON.parse(frozen); } - }); -} -exports.defineFrozen = defineFrozen; -function resolveProperties(object) { - var result = {}; - var promises = []; - Object.keys(object).forEach(function (key) { - var value = object[key]; - if (value instanceof Promise) { - promises.push(value.then(function (value) { - result[key] = value; - return null; - })); - } - else { - result[key] = value; - } - }); - return Promise.all(promises).then(function () { - return result; - }); -} -exports.resolveProperties = resolveProperties; -function shallowCopy(object) { - var result = {}; - for (var key in object) { - result[key] = object[key]; - } - return result; -} -exports.shallowCopy = shallowCopy; -function jsonCopy(object) { - return JSON.parse(JSON.stringify(object)); -} -exports.jsonCopy = jsonCopy; - -},{}],364:[function(require,module,exports){ -"use strict"; -//See: https://github.com/ethereum/wiki/wiki/RLP -Object.defineProperty(exports, "__esModule", { value: true }); -var bytes_1 = require("./bytes"); -function arrayifyInteger(value) { - var result = []; - while (value) { - result.unshift(value & 0xff); - value >>= 8; - } - return result; -} -function unarrayifyInteger(data, offset, length) { - var result = 0; - for (var i = 0; i < length; i++) { - result = (result * 256) + data[offset + i]; - } - return result; -} -function _encode(object) { - if (Array.isArray(object)) { - var payload = []; - object.forEach(function (child) { - payload = payload.concat(_encode(child)); - }); - if (payload.length <= 55) { - payload.unshift(0xc0 + payload.length); - return payload; - } - var length = arrayifyInteger(payload.length); - length.unshift(0xf7 + length.length); - return length.concat(payload); - } - var data = Array.prototype.slice.call(bytes_1.arrayify(object)); - if (data.length === 1 && data[0] <= 0x7f) { - return data; - } - else if (data.length <= 55) { - data.unshift(0x80 + data.length); - return data; - } - var length = arrayifyInteger(data.length); - length.unshift(0xb7 + length.length); - return length.concat(data); -} -function encode(object) { - return bytes_1.hexlify(_encode(object)); -} -exports.encode = encode; -function _decodeChildren(data, offset, childOffset, length) { - var result = []; - while (childOffset < offset + 1 + length) { - var decoded = _decode(data, childOffset); - result.push(decoded.result); - childOffset += decoded.consumed; - if (childOffset > offset + 1 + length) { - throw new Error('invalid rlp'); - } - } - return { consumed: (1 + length), result: result }; -} -// returns { consumed: number, result: Object } -function _decode(data, offset) { - if (data.length === 0) { - throw new Error('invalid rlp data'); - } - // Array with extra length prefix - if (data[offset] >= 0xf8) { - var lengthLength = data[offset] - 0xf7; - if (offset + 1 + lengthLength > data.length) { - throw new Error('too short'); - } - var length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - throw new Error('to short'); - } - return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); - } - else if (data[offset] >= 0xc0) { - var length = data[offset] - 0xc0; - if (offset + 1 + length > data.length) { - throw new Error('invalid rlp data'); - } - return _decodeChildren(data, offset, offset + 1, length); - } - else if (data[offset] >= 0xb8) { - var lengthLength = data[offset] - 0xb7; - if (offset + 1 + lengthLength > data.length) { - throw new Error('invalid rlp data'); - } - var length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - throw new Error('invalid rlp data'); - } - var result = bytes_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); - return { consumed: (1 + lengthLength + length), result: result }; - } - else if (data[offset] >= 0x80) { - var length = data[offset] - 0x80; - if (offset + 1 + length > data.length) { - throw new Error('invlaid rlp data'); - } - var result = bytes_1.hexlify(data.slice(offset + 1, offset + 1 + length)); - return { consumed: (1 + length), result: result }; - } - return { consumed: 1, result: bytes_1.hexlify(data[offset]) }; -} -function decode(data) { - var bytes = bytes_1.arrayify(data); - var decoded = _decode(bytes, 0); - if (decoded.consumed !== bytes.length) { - throw new Error('invalid rlp data'); - } - return decoded.result; -} -exports.decode = decode; - -},{"./bytes":360}],365:[function(require,module,exports){ -"use strict"; -/////////////////////////////// -// Bytes -Object.defineProperty(exports, "__esModule", { value: true }); -/////////////////////////////// -// BigNumber -var BigNumber = /** @class */ (function () { - function BigNumber() { - } - return BigNumber; -}()); -exports.BigNumber = BigNumber; -; -; -; -/////////////////////////////// -// Interface -var Indexed = /** @class */ (function () { - function Indexed() { - } - return Indexed; -}()); -exports.Indexed = Indexed; -/** - * Provider - * - * Note: We use an abstract class so we can use instanceof to determine if an - * object is a Provider. - */ -var MinimalProvider = /** @class */ (function () { - function MinimalProvider() { - } - return MinimalProvider; -}()); -exports.MinimalProvider = MinimalProvider; -/** - * Signer - * - * Note: We use an abstract class so we can use instanceof to determine if an - * object is a Signer. - */ -var Signer = /** @class */ (function () { - function Signer() { - } - return Signer; -}()); -exports.Signer = Signer; -/////////////////////////////// -// HDNode -var HDNode = /** @class */ (function () { - function HDNode() { - } - return HDNode; -}()); -exports.HDNode = HDNode; - -},{}],366:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -var bytes_1 = require("./bytes"); -var UnicodeNormalizationForm; -(function (UnicodeNormalizationForm) { - UnicodeNormalizationForm["current"] = ""; - UnicodeNormalizationForm["NFC"] = "NFC"; - UnicodeNormalizationForm["NFD"] = "NFD"; - UnicodeNormalizationForm["NFKC"] = "NFKC"; - UnicodeNormalizationForm["NFKD"] = "NFKD"; -})(UnicodeNormalizationForm = exports.UnicodeNormalizationForm || (exports.UnicodeNormalizationForm = {})); -; -// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array -function toUtf8Bytes(str, form) { - if (form === void 0) { form = UnicodeNormalizationForm.current; } - if (form != UnicodeNormalizationForm.current) { - str = str.normalize(form); - } - var result = []; - var offset = 0; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - if (c < 128) { - result[offset++] = c; - } - else if (c < 2048) { - result[offset++] = (c >> 6) | 192; - result[offset++] = (c & 63) | 128; - } - else if (((c & 0xFC00) == 0xD800) && (i + 1) < str.length && ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) { - // Surrogate Pair - c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); - result[offset++] = (c >> 18) | 240; - result[offset++] = ((c >> 12) & 63) | 128; - result[offset++] = ((c >> 6) & 63) | 128; - result[offset++] = (c & 63) | 128; - } - else { - result[offset++] = (c >> 12) | 224; - result[offset++] = ((c >> 6) & 63) | 128; - result[offset++] = (c & 63) | 128; - } - } - return bytes_1.arrayify(result); -} -exports.toUtf8Bytes = toUtf8Bytes; -; -// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 -function toUtf8String(bytes) { - bytes = bytes_1.arrayify(bytes); - var result = ''; - var i = 0; - // Invalid bytes are ignored - while (i < bytes.length) { - var c = bytes[i++]; - if (c >> 7 == 0) { - // 0xxx xxxx - result += String.fromCharCode(c); - continue; - } - // Invalid starting byte - if (c >> 6 == 0x02) { - continue; - } - // Multibyte; how many bytes left for thus character? - var extraLength = null; - if (c >> 5 == 0x06) { - extraLength = 1; - } - else if (c >> 4 == 0x0e) { - extraLength = 2; - } - else if (c >> 3 == 0x1e) { - extraLength = 3; - } - else if (c >> 2 == 0x3e) { - extraLength = 4; - } - else if (c >> 1 == 0x7e) { - extraLength = 5; - } - else { - continue; - } - // Do we have enough bytes in our data? - if (i + extraLength > bytes.length) { - // If there is an invalid unprocessed byte, try to continue - for (; i < bytes.length; i++) { - if (bytes[i] >> 6 != 0x02) { - break; - } - } - if (i != bytes.length) - continue; - // All leftover bytes are valid. - return result; - } - // Remove the UTF-8 prefix from the char (res) - var res = c & ((1 << (8 - extraLength - 1)) - 1); - var count; - for (count = 0; count < extraLength; count++) { - var nextChar = bytes[i++]; - // Is the char valid multibyte part? - if (nextChar >> 6 != 0x02) { - break; - } - ; - res = (res << 6) | (nextChar & 0x3f); - } - if (count != extraLength) { - i--; - continue; - } - if (res <= 0xffff) { - result += String.fromCharCode(res); - continue; - } - res -= 0x10000; - result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00); - } - return result; -} -exports.toUtf8String = toUtf8String; - -},{"./bytes":360}],367:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var numberToBN = require('number-to-bn'); - -var zero = new BN(0); -var negative1 = new BN(-1); - -// complete ethereum unit map -var unitMap = { - 'noether': '0', // eslint-disable-line - 'wei': '1', // eslint-disable-line - 'kwei': '1000', // eslint-disable-line - 'Kwei': '1000', // eslint-disable-line - 'babbage': '1000', // eslint-disable-line - 'femtoether': '1000', // eslint-disable-line - 'mwei': '1000000', // eslint-disable-line - 'Mwei': '1000000', // eslint-disable-line - 'lovelace': '1000000', // eslint-disable-line - 'picoether': '1000000', // eslint-disable-line - 'gwei': '1000000000', // eslint-disable-line - 'Gwei': '1000000000', // eslint-disable-line - 'shannon': '1000000000', // eslint-disable-line - 'nanoether': '1000000000', // eslint-disable-line - 'nano': '1000000000', // eslint-disable-line - 'szabo': '1000000000000', // eslint-disable-line - 'microether': '1000000000000', // eslint-disable-line - 'micro': '1000000000000', // eslint-disable-line - 'finney': '1000000000000000', // eslint-disable-line - 'milliether': '1000000000000000', // eslint-disable-line - 'milli': '1000000000000000', // eslint-disable-line - 'ether': '1000000000000000000', // eslint-disable-line - 'kether': '1000000000000000000000', // eslint-disable-line - 'grand': '1000000000000000000000', // eslint-disable-line - 'mether': '1000000000000000000000000', // eslint-disable-line - 'gether': '1000000000000000000000000000', // eslint-disable-line - 'tether': '1000000000000000000000000000000' }; - -/** - * Returns value of unit in Wei - * - * @method getValueOfUnit - * @param {String} unit the unit to convert to, default ether - * @returns {BigNumber} value of the unit (in Wei) - * @throws error if the unit is not correct:w - */ -function getValueOfUnit(unitInput) { - var unit = unitInput ? unitInput.toLowerCase() : 'ether'; - var unitValue = unitMap[unit]; // eslint-disable-line - - if (typeof unitValue !== 'string') { - throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2)); - } - - return new BN(unitValue, 10); -} - -function numberToString(arg) { - if (typeof arg === 'string') { - if (!arg.match(/^-?[0-9.]+$/)) { - throw new Error('while converting number to string, invalid number value \'' + arg + '\', should be a number matching (^-?[0-9.]+).'); - } - return arg; - } else if (typeof arg === 'number') { - return String(arg); - } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) { - if (arg.toPrecision) { - return String(arg.toPrecision()); - } else { - // eslint-disable-line - return arg.toString(10); - } - } - throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.'); -} - -function fromWei(weiInput, unit, optionsInput) { - var wei = numberToBN(weiInput); // eslint-disable-line - var negative = wei.lt(zero); // eslint-disable-line - var base = getValueOfUnit(unit); - var baseLength = unitMap[unit].length - 1 || 1; - var options = optionsInput || {}; - - if (negative) { - wei = wei.mul(negative1); - } - - var fraction = wei.mod(base).toString(10); // eslint-disable-line - - while (fraction.length < baseLength) { - fraction = '0' + fraction; - } - - if (!options.pad) { - fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; - } - - var whole = wei.div(base).toString(10); // eslint-disable-line - - if (options.commify) { - whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); - } - - var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line - - if (negative) { - value = '-' + value; - } - - return value; -} - -function toWei(etherInput, unit) { - var ether = numberToString(etherInput); // eslint-disable-line - var base = getValueOfUnit(unit); - var baseLength = unitMap[unit].length - 1 || 1; - - // Is it negative? - var negative = ether.substring(0, 1) === '-'; // eslint-disable-line - if (negative) { - ether = ether.substring(1); - } - - if (ether === '.') { - throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value'); - } - - // Split it into a whole and fractional part - var comps = ether.split('.'); // eslint-disable-line - if (comps.length > 2) { - throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points'); - } - - var whole = comps[0], - fraction = comps[1]; // eslint-disable-line - - if (!whole) { - whole = '0'; - } - if (!fraction) { - fraction = '0'; - } - if (fraction.length > baseLength) { - throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places'); - } - - while (fraction.length < baseLength) { - fraction += '0'; - } - - whole = new BN(whole); - fraction = new BN(fraction); - var wei = whole.mul(base).add(fraction); // eslint-disable-line - - if (negative) { - wei = wei.mul(negative1); - } - - return new BN(wei.toString(10), 10); -} - -module.exports = { - unitMap: unitMap, - numberToString: numberToString, - getValueOfUnit: getValueOfUnit, - fromWei: fromWei, - toWei: toWei -}; -},{"bn.js":368,"number-to-bn":1386}],368:[function(require,module,exports){ -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // 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; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = require('buf' + 'fer').Buffer; - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - 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; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - 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); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - 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; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - 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; - } - - 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 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(); - }; - - 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; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } - - 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; - } - - 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; - } - 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; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; - - 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; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // 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(); - }; - - 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 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 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; - - 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; - } - - 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; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - 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; - }; - - 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); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - 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'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - 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); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - 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; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - 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; - }; - - // 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; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - 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; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - 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); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // 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]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // 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); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // 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; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // 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); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // 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(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - 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]; - } - } - - return this; - }; - - // 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; - } - - if (this.length > num.length) return this.clone().iadd(num); - - 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(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // 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; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - 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; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - 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; - - // 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; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - 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--; - } - - return out.strip(); - } - - // 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; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - 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 FFTM (x, y) { - this.x = x; - this.y = y; - } - - 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; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // 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); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - 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]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - 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; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - 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; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - 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; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - 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; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // 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); - }; - - // 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); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // 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++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `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); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - 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; - - if (r !== 0) { - var carry = 0; - - 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 (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // 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; - } - - 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); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - 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; - } - - 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; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // 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; - - // 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]; - - return !!(w & q); - }; - - // 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; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // 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.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // 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]++; - } - } - this.length = Math.max(this.length, i + 1); - - return 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; - } - - this.words[0] -= num; - - 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; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - 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; - } - - if (carry === 0) return this.strip(); - - // 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; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // 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; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - 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); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - 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(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // 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()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // 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); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - 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(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - 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); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - 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); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // 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()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - 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); - } - - x1.iushrn(1); - } - } - - 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); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - 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; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // 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; - } - - // 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++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - 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(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // 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; - - 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; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - 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); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - 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); - }; - - 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); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // 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); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // 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); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // 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); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - 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; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - 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); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - 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'); - } - inherits(K256, MPrime); - - 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; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - 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; - } else { - input.length -= 9; - } - }; - - 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); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - 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; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - 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; - - return prime; - }; - - // - // 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'); - }; - - 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'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - 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()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - 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); - } - - // 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()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // 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); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - 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)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - 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); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1); - if (num.cmpn(1) === 0) return a.clone(); - - 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); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - 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 (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - 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); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - 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; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - 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); - } - - return res._forceRed(this); - }; - - 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); - -},{}],369:[function(require,module,exports){ +},{"./custom":269}],271:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty @@ -58596,7 +39620,7 @@ if ('undefined' !== typeof module) { module.exports = EventEmitter; } -},{}],370:[function(require,module,exports){ +},{}],272:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -59121,7 +40145,7 @@ function functionBindPolyfill(context) { }; } -},{}],371:[function(require,module,exports){ +},{}],273:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var MD5 = require('md5.js') @@ -59168,7 +40192,7 @@ function EVP_BytesToKey (password, salt, keyBits, ivLen) { module.exports = EVP_BytesToKey -},{"md5.js":1297,"safe-buffer":1593}],372:[function(require,module,exports){ +},{"md5.js":1126,"safe-buffer":1371}],274:[function(require,module,exports){ function getStack(err) { if(err.stack && err.name && err.message) @@ -59205,370 +40229,7 @@ var explain = module.exports = function (err, message) { -},{}],373:[function(require,module,exports){ -'use strict'; - -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; - -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } - - return toStr.call(arr) === '[object Array]'; -}; - -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } - - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } - - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; - -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; - -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } - - return obj[name]; -}; - -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } - - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } - - // Return the modified object - return target; -}; - -},{}],374:[function(require,module,exports){ -(function (process){ -/* - * extsprintf.js: extended POSIX-style sprintf - */ - -var mod_assert = require('assert'); -var mod_util = require('util'); - -/* - * Public interface - */ -exports.sprintf = jsSprintf; -exports.printf = jsPrintf; -exports.fprintf = jsFprintf; - -/* - * Stripped down version of s[n]printf(3c). We make a best effort to throw an - * exception when given a format string we don't understand, rather than - * ignoring it, so that we won't break existing programs if/when we go implement - * the rest of this. - * - * This implementation currently supports specifying - * - field alignment ('-' flag), - * - zero-pad ('0' flag) - * - always show numeric sign ('+' flag), - * - field width - * - conversions for strings, decimal integers, and floats (numbers). - * - argument size specifiers. These are all accepted but ignored, since - * Javascript has no notion of the physical size of an argument. - * - * Everything else is currently unsupported, most notably precision, unsigned - * numbers, non-decimal numbers, and characters. - */ -function jsSprintf(fmt) -{ - var regex = [ - '([^%]*)', /* normal text */ - '%', /* start of format */ - '([\'\\-+ #0]*?)', /* flags (optional) */ - '([1-9]\\d*)?', /* width (optional) */ - '(\\.([1-9]\\d*))?', /* precision (optional) */ - '[lhjztL]*?', /* length mods (ignored) */ - '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ - ].join(''); - - var re = new RegExp(regex); - var args = Array.prototype.slice.call(arguments, 1); - var flags, width, precision, conversion; - var left, pad, sign, arg, match; - var ret = ''; - var argn = 1; - - mod_assert.equal('string', typeof (fmt)); - - while ((match = re.exec(fmt)) !== null) { - ret += match[1]; - fmt = fmt.substring(match[0].length); - - flags = match[2] || ''; - width = match[3] || 0; - precision = match[4] || ''; - conversion = match[6]; - left = false; - sign = false; - pad = ' '; - - if (conversion == '%') { - ret += '%'; - continue; - } - - if (args.length === 0) - throw (new Error('too few args to sprintf')); - - arg = args.shift(); - argn++; - - if (flags.match(/[\' #]/)) - throw (new Error( - 'unsupported flags: ' + flags)); - - if (precision.length > 0) - throw (new Error( - 'non-zero precision not supported')); - - if (flags.match(/-/)) - left = true; - - if (flags.match(/0/)) - pad = '0'; - - if (flags.match(/\+/)) - sign = true; - - switch (conversion) { - case 's': - if (arg === undefined || arg === null) - throw (new Error('argument ' + argn + - ': attempted to print undefined or null ' + - 'as a string')); - ret += doPad(pad, width, left, arg.toString()); - break; - - case 'd': - arg = Math.floor(arg); - /*jsl:fallthru*/ - case 'f': - sign = sign && arg > 0 ? '+' : ''; - ret += sign + doPad(pad, width, left, - arg.toString()); - break; - - case 'x': - ret += doPad(pad, width, left, arg.toString(16)); - break; - - case 'j': /* non-standard */ - if (width === 0) - width = 10; - ret += mod_util.inspect(arg, false, width); - break; - - case 'r': /* non-standard */ - ret += dumpException(arg); - break; - - default: - throw (new Error('unsupported conversion: ' + - conversion)); - } - } - - ret += fmt; - return (ret); -} - -function jsPrintf() { - var args = Array.prototype.slice.call(arguments); - args.unshift(process.stdout); - jsFprintf.apply(null, args); -} - -function jsFprintf(stream) { - var args = Array.prototype.slice.call(arguments, 1); - return (stream.write(jsSprintf.apply(this, args))); -} - -function doPad(chr, width, left, str) -{ - var ret = str; - - while (ret.length < width) { - if (left) - ret += chr; - else - ret = chr + ret; - } - - return (ret); -} - -/* - * This function dumps long stack traces for exceptions having a cause() method. - * See node-verror for an example. - */ -function dumpException(ex) -{ - var ret; - - if (!(ex instanceof Error)) - throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); - - /* Note that V8 prepends "ex.stack" with ex.toString(). */ - ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; - - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + dumpException(cex); - } - } - - return (ret); -} - -}).call(this,require('_process')) -},{"_process":1438,"assert":78,"util":1776}],375:[function(require,module,exports){ -'use strict'; - -var isArray = Array.isArray; -var keyList = Object.keys; -var hasProp = Object.prototype.hasOwnProperty; - -module.exports = function equal(a, b) { - if (a === b) return true; - - if (a && b && typeof a == 'object' && typeof b == 'object') { - var arrA = isArray(a) - , arrB = isArray(b) - , i - , length - , key; - - if (arrA && arrB) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; - } - - if (arrA != arrB) return false; - - var dateA = a instanceof Date - , dateB = b instanceof Date; - if (dateA != dateB) return false; - if (dateA && dateB) return a.getTime() == b.getTime(); - - var regexpA = a instanceof RegExp - , regexpB = b instanceof RegExp; - if (regexpA != regexpB) return false; - if (regexpA && regexpB) return a.toString() == b.toString(); - - var keys = keyList(a); - length = keys.length; - - if (length !== keyList(b).length) - return false; - - for (i = length; i-- !== 0;) - if (!hasProp.call(b, keys[i])) return false; - - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - - return true; - } - - return a!==a && b!==b; -}; - -},{}],376:[function(require,module,exports){ +},{}],275:[function(require,module,exports){ module.exports = class FixedFIFO { constructor (hwm) { if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') @@ -59599,7 +40260,7 @@ module.exports = class FixedFIFO { } } -},{}],377:[function(require,module,exports){ +},{}],276:[function(require,module,exports){ const FixedFIFO = require('./fixed-size') module.exports = class FastFIFO { @@ -59633,68 +40294,7 @@ module.exports = class FastFIFO { } } -},{"./fixed-size":376}],378:[function(require,module,exports){ -'use strict'; - -module.exports = function (data, opts) { - if (!opts) opts = {}; - if (typeof opts === 'function') opts = { cmp: opts }; - var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; - - var cmp = opts.cmp && (function (f) { - return function (node) { - return function (a, b) { - var aobj = { key: a, value: node[a] }; - var bobj = { key: b, value: node[b] }; - return f(aobj, bobj); - }; - }; - })(opts.cmp); - - var seen = []; - return (function stringify (node) { - if (node && node.toJSON && typeof node.toJSON === 'function') { - node = node.toJSON(); - } - - if (node === undefined) return; - if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; - if (typeof node !== 'object') return JSON.stringify(node); - - var i, out; - if (Array.isArray(node)) { - out = '['; - for (i = 0; i < node.length; i++) { - if (i) out += ','; - out += stringify(node[i]) || 'null'; - } - return out + ']'; - } - - if (node === null) return 'null'; - - if (seen.indexOf(node) !== -1) { - if (cycles) return JSON.stringify('__cycle__'); - throw new TypeError('Converting circular structure to JSON'); - } - - var seenIndex = seen.push(node) - 1; - var keys = Object.keys(node).sort(cmp && cmp(node)); - out = ''; - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node[key]); - - if (!value) continue; - if (out) out += ','; - out += JSON.stringify(key) + ':' + value; - } - seen.splice(seenIndex, 1); - return '{' + out + '}'; - })(data); -}; - -},{}],379:[function(require,module,exports){ +},{"./fixed-size":275}],277:[function(require,module,exports){ /** * Created by schwarzkopfb on 15/11/17. */ @@ -59727,215 +40327,7 @@ function hash(s) { module.exports = hash -},{}],380:[function(require,module,exports){ -'use strict'; - -var isCallable = require('is-callable'); - -var toStr = Object.prototype.toString; -var hasOwnProperty = Object.prototype.hasOwnProperty; - -var forEachArray = function forEachArray(array, iterator, receiver) { - for (var i = 0, len = array.length; i < len; i++) { - if (hasOwnProperty.call(array, i)) { - if (receiver == null) { - iterator(array[i], i, array); - } else { - iterator.call(receiver, array[i], i, array); - } - } - } -}; - -var forEachString = function forEachString(string, iterator, receiver) { - for (var i = 0, len = string.length; i < len; i++) { - // no such thing as a sparse string. - if (receiver == null) { - iterator(string.charAt(i), i, string); - } else { - iterator.call(receiver, string.charAt(i), i, string); - } - } -}; - -var forEachObject = function forEachObject(object, iterator, receiver) { - for (var k in object) { - if (hasOwnProperty.call(object, k)) { - if (receiver == null) { - iterator(object[k], k, object); - } else { - iterator.call(receiver, object[k], k, object); - } - } - } -}; - -var forEach = function forEach(list, iterator, thisArg) { - if (!isCallable(iterator)) { - throw new TypeError('iterator must be a function'); - } - - var receiver; - if (arguments.length >= 3) { - receiver = thisArg; - } - - if (toStr.call(list) === '[object Array]') { - forEachArray(list, iterator, receiver); - } else if (typeof list === 'string') { - forEachString(list, iterator, receiver); - } else { - forEachObject(list, iterator, receiver); - } -}; - -module.exports = forEach; - -},{"is-callable":767}],381:[function(require,module,exports){ -module.exports = ForeverAgent -ForeverAgent.SSL = ForeverAgentSSL - -var util = require('util') - , Agent = require('http').Agent - , net = require('net') - , tls = require('tls') - , AgentSSL = require('https').Agent - -function getConnectionName(host, port) { - var name = '' - if (typeof host === 'string') { - name = host + ':' + port - } else { - // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. - name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') - } - return name -} - -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = getConnectionName(host, port) - - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - var onIdleError = function() { - socket.destroy() - } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) - } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy() - } - }) - -} -util.inherits(ForeverAgent, Agent) - -ForeverAgent.defaultMinSockets = 5 - - -ForeverAgent.prototype.createConnection = net.createConnection -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = getConnectionName(host, port) - - if (typeof host !== 'string') { - var options = host - port = options.port - host = options.host - } - - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} - -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s) - if (index !== -1) { - this.sockets[name].splice(index, 1) - } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name] - delete this.requests[name] - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] - } - } - } - - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free') - } -} - -function ForeverAgentSSL (options) { - ForeverAgent.call(this, options) -} -util.inherits(ForeverAgentSSL, ForeverAgent) - -ForeverAgentSSL.prototype.createConnection = createConnectionSSL -ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest - -function createConnectionSSL (port, host, options) { - if (typeof port === 'object') { - options = port; - } else if (typeof host === 'object') { - options = host; - } else if (typeof options === 'object') { - options = options; - } else { - options = {}; - } - - if (typeof port === 'number') { - options.port = port; - } - - if (typeof host === 'string') { - options.host = host; - } - - return tls.connect(options); -} - -},{"http":1716,"https":446,"net":212,"tls":212,"util":1776}],382:[function(require,module,exports){ -/* eslint-env browser */ -module.exports = typeof self == 'object' ? self.FormData : window.FormData; - -},{}],383:[function(require,module,exports){ +},{}],278:[function(require,module,exports){ const EventEmitter = require('events').EventEmitter const assert = require('assert') const fsm = require('fsm') @@ -60014,7 +40406,7 @@ function reach (curr, next, reachable) { return here[next].length === 1 } -},{"assert":78,"events":370,"fsm":384}],384:[function(require,module,exports){ +},{"assert":26,"events":272,"fsm":279}],279:[function(require,module,exports){ function each(obj, iter) { for(var key in obj) { var value = obj[key] @@ -60188,68 +40580,7 @@ var combine = exports.combine = function (fsm1, fsm2, start1, start2) { } -},{}],385:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],386:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":385}],387:[function(require,module,exports){ +},{}],280:[function(require,module,exports){ // originally pulled out of simple-peer module.exports = function getBrowserRTC () { @@ -60266,7 +40597,7 @@ module.exports = function getBrowserRTC () { return wrtc } -},{}],388:[function(require,module,exports){ +},{}],281:[function(require,module,exports){ // If the passed object is an (async) iterable, then get the iterator // If it's probably an iterator already (i.e. has next function) return it // else throw @@ -60285,24 +40616,7 @@ module.exports = function getIterator (obj) { throw new Error('argument is not an iterator or iterable') } -},{}],389:[function(require,module,exports){ -(function (global){ -var win; - -if (typeof window !== "undefined") { - win = window; -} else if (typeof global !== "undefined") { - win = global; -} else if (typeof self !== "undefined"){ - win = self; -} else { - win = {}; -} - -module.exports = win; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],390:[function(require,module,exports){ +},{}],282:[function(require,module,exports){ (function (global){ /* globals self, window, global */ /* eslint no-negated-condition: 0, no-new-func: 0 */ @@ -60320,7 +40634,7 @@ if (typeof self !== 'undefined') { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],391:[function(require,module,exports){ +},{}],283:[function(require,module,exports){ 'use strict'; var defineProperties = require('define-properties'); @@ -60341,7 +40655,7 @@ defineProperties(getGlobal, { module.exports = getGlobal; -},{"./implementation":390,"./polyfill":392,"./shim":393,"define-properties":263}],392:[function(require,module,exports){ +},{"./implementation":282,"./polyfill":284,"./shim":285,"define-properties":218}],284:[function(require,module,exports){ (function (global){ 'use strict'; @@ -60355,7 +40669,7 @@ module.exports = function getPolyfill() { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./implementation":390}],393:[function(require,module,exports){ +},{"./implementation":282}],285:[function(require,module,exports){ 'use strict'; var define = require('define-properties'); @@ -60379,7 +40693,7 @@ module.exports = function shimGlobal() { return polyfill; }; -},{"./polyfill":392,"define-properties":263}],394:[function(require,module,exports){ +},{"./polyfill":284,"define-properties":218}],286:[function(require,module,exports){ 'use strict' const SparseArray = require('sparse-array') @@ -60625,7 +40939,7 @@ async function asyncTransformBucket (bucket, asyncMap, asyncReduce) { module.exports = Bucket -},{"./consumable-hash":396,"sparse-array":1672}],395:[function(require,module,exports){ +},{"./consumable-hash":288,"sparse-array":1439}],287:[function(require,module,exports){ 'use strict' const START_MASKS = [ @@ -60709,7 +41023,7 @@ function maskFor (start, length) { return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)] } -},{}],396:[function(require,module,exports){ +},{}],288:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -60794,7 +41108,7 @@ class InfiniteHash { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./consumable-buffer":395}],397:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"./consumable-buffer":287}],289:[function(require,module,exports){ 'use strict' const Bucket = require('./bucket') @@ -60805,764 +41119,7 @@ module.exports = function createHAMT (options) { module.exports.isBucket = Bucket.isBucket -},{"./bucket":394}],398:[function(require,module,exports){ -module.exports={ - "$id": "afterRequest.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "optional": true, - "required": [ - "lastAccess", - "eTag", - "hitCount" - ], - "properties": { - "expires": { - "type": "string", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?" - }, - "lastAccess": { - "type": "string", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?" - }, - "eTag": { - "type": "string" - }, - "hitCount": { - "type": "integer" - }, - "comment": { - "type": "string" - } - } -} - -},{}],399:[function(require,module,exports){ -module.exports={ - "$id": "beforeRequest.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "optional": true, - "required": [ - "lastAccess", - "eTag", - "hitCount" - ], - "properties": { - "expires": { - "type": "string", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?" - }, - "lastAccess": { - "type": "string", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?" - }, - "eTag": { - "type": "string" - }, - "hitCount": { - "type": "integer" - }, - "comment": { - "type": "string" - } - } -} - -},{}],400:[function(require,module,exports){ -module.exports={ - "$id": "browser.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "name", - "version" - ], - "properties": { - "name": { - "type": "string" - }, - "version": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],401:[function(require,module,exports){ -module.exports={ - "$id": "cache.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "properties": { - "beforeRequest": { - "oneOf": [ - { "type": "null" }, - { "$ref": "beforeRequest.json#" } - ] - }, - "afterRequest": { - "oneOf": [ - { "type": "null" }, - { "$ref": "afterRequest.json#" } - ] - }, - "comment": { - "type": "string" - } - } -} - -},{}],402:[function(require,module,exports){ -module.exports={ - "$id": "content.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "size", - "mimeType" - ], - "properties": { - "size": { - "type": "integer" - }, - "compression": { - "type": "integer" - }, - "mimeType": { - "type": "string" - }, - "text": { - "type": "string" - }, - "encoding": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],403:[function(require,module,exports){ -module.exports={ - "$id": "cookie.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "name", - "value" - ], - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - }, - "path": { - "type": "string" - }, - "domain": { - "type": "string" - }, - "expires": { - "type": ["string", "null"], - "format": "date-time" - }, - "httpOnly": { - "type": "boolean" - }, - "secure": { - "type": "boolean" - }, - "comment": { - "type": "string" - } - } -} - -},{}],404:[function(require,module,exports){ -module.exports={ - "$id": "creator.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "name", - "version" - ], - "properties": { - "name": { - "type": "string" - }, - "version": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],405:[function(require,module,exports){ -module.exports={ - "$id": "entry.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "optional": true, - "required": [ - "startedDateTime", - "time", - "request", - "response", - "cache", - "timings" - ], - "properties": { - "pageref": { - "type": "string" - }, - "startedDateTime": { - "type": "string", - "format": "date-time", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))" - }, - "time": { - "type": "number", - "min": 0 - }, - "request": { - "$ref": "request.json#" - }, - "response": { - "$ref": "response.json#" - }, - "cache": { - "$ref": "cache.json#" - }, - "timings": { - "$ref": "timings.json#" - }, - "serverIPAddress": { - "type": "string", - "oneOf": [ - { "format": "ipv4" }, - { "format": "ipv6" } - ] - }, - "connection": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],406:[function(require,module,exports){ -module.exports={ - "$id": "har.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "log" - ], - "properties": { - "log": { - "$ref": "log.json#" - } - } -} - -},{}],407:[function(require,module,exports){ -module.exports={ - "$id": "header.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "name", - "value" - ], - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],408:[function(require,module,exports){ -'use strict' - -module.exports = { - afterRequest: require('./afterRequest.json'), - beforeRequest: require('./beforeRequest.json'), - browser: require('./browser.json'), - cache: require('./cache.json'), - content: require('./content.json'), - cookie: require('./cookie.json'), - creator: require('./creator.json'), - entry: require('./entry.json'), - har: require('./har.json'), - header: require('./header.json'), - log: require('./log.json'), - page: require('./page.json'), - pageTimings: require('./pageTimings.json'), - postData: require('./postData.json'), - query: require('./query.json'), - request: require('./request.json'), - response: require('./response.json'), - timings: require('./timings.json') -} - -},{"./afterRequest.json":398,"./beforeRequest.json":399,"./browser.json":400,"./cache.json":401,"./content.json":402,"./cookie.json":403,"./creator.json":404,"./entry.json":405,"./har.json":406,"./header.json":407,"./log.json":409,"./page.json":410,"./pageTimings.json":411,"./postData.json":412,"./query.json":413,"./request.json":414,"./response.json":415,"./timings.json":416}],409:[function(require,module,exports){ -module.exports={ - "$id": "log.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "version", - "creator", - "entries" - ], - "properties": { - "version": { - "type": "string" - }, - "creator": { - "$ref": "creator.json#" - }, - "browser": { - "$ref": "browser.json#" - }, - "pages": { - "type": "array", - "items": { - "$ref": "page.json#" - } - }, - "entries": { - "type": "array", - "items": { - "$ref": "entry.json#" - } - }, - "comment": { - "type": "string" - } - } -} - -},{}],410:[function(require,module,exports){ -module.exports={ - "$id": "page.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "optional": true, - "required": [ - "startedDateTime", - "id", - "title", - "pageTimings" - ], - "properties": { - "startedDateTime": { - "type": "string", - "format": "date-time", - "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))" - }, - "id": { - "type": "string", - "unique": true - }, - "title": { - "type": "string" - }, - "pageTimings": { - "$ref": "pageTimings.json#" - }, - "comment": { - "type": "string" - } - } -} - -},{}],411:[function(require,module,exports){ -module.exports={ - "$id": "pageTimings.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "properties": { - "onContentLoad": { - "type": "number", - "min": -1 - }, - "onLoad": { - "type": "number", - "min": -1 - }, - "comment": { - "type": "string" - } - } -} - -},{}],412:[function(require,module,exports){ -module.exports={ - "$id": "postData.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "optional": true, - "required": [ - "mimeType" - ], - "properties": { - "mimeType": { - "type": "string" - }, - "text": { - "type": "string" - }, - "params": { - "type": "array", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - }, - "fileName": { - "type": "string" - }, - "contentType": { - "type": "string" - }, - "comment": { - "type": "string" - } - } - }, - "comment": { - "type": "string" - } - } -} - -},{}],413:[function(require,module,exports){ -module.exports={ - "$id": "query.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "name", - "value" - ], - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - }, - "comment": { - "type": "string" - } - } -} - -},{}],414:[function(require,module,exports){ -module.exports={ - "$id": "request.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "method", - "url", - "httpVersion", - "cookies", - "headers", - "queryString", - "headersSize", - "bodySize" - ], - "properties": { - "method": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - }, - "httpVersion": { - "type": "string" - }, - "cookies": { - "type": "array", - "items": { - "$ref": "cookie.json#" - } - }, - "headers": { - "type": "array", - "items": { - "$ref": "header.json#" - } - }, - "queryString": { - "type": "array", - "items": { - "$ref": "query.json#" - } - }, - "postData": { - "$ref": "postData.json#" - }, - "headersSize": { - "type": "integer" - }, - "bodySize": { - "type": "integer" - }, - "comment": { - "type": "string" - } - } -} - -},{}],415:[function(require,module,exports){ -module.exports={ - "$id": "response.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "type": "object", - "required": [ - "status", - "statusText", - "httpVersion", - "cookies", - "headers", - "content", - "redirectURL", - "headersSize", - "bodySize" - ], - "properties": { - "status": { - "type": "integer" - }, - "statusText": { - "type": "string" - }, - "httpVersion": { - "type": "string" - }, - "cookies": { - "type": "array", - "items": { - "$ref": "cookie.json#" - } - }, - "headers": { - "type": "array", - "items": { - "$ref": "header.json#" - } - }, - "content": { - "$ref": "content.json#" - }, - "redirectURL": { - "type": "string" - }, - "headersSize": { - "type": "integer" - }, - "bodySize": { - "type": "integer" - }, - "comment": { - "type": "string" - } - } -} - -},{}],416:[function(require,module,exports){ -module.exports={ - "$id": "timings.json#", - "$schema": "http://json-schema.org/draft-06/schema#", - "required": [ - "send", - "wait", - "receive" - ], - "properties": { - "dns": { - "type": "number", - "min": -1 - }, - "connect": { - "type": "number", - "min": -1 - }, - "blocked": { - "type": "number", - "min": -1 - }, - "send": { - "type": "number", - "min": -1 - }, - "wait": { - "type": "number", - "min": -1 - }, - "receive": { - "type": "number", - "min": -1 - }, - "ssl": { - "type": "number", - "min": -1 - }, - "comment": { - "type": "string" - } - } -} - -},{}],417:[function(require,module,exports){ -function HARError (errors) { - var message = 'validation failed' - - this.name = 'HARError' - this.message = message - this.errors = errors - - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, this.constructor) - } else { - this.stack = (new Error(message)).stack - } -} - -HARError.prototype = Error.prototype - -module.exports = HARError - -},{}],418:[function(require,module,exports){ -var Ajv = require('ajv') -var HARError = require('./error') -var schemas = require('har-schema') - -var ajv - -function createAjvInstance () { - var ajv = new Ajv({ - allErrors: true - }) - ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')) - ajv.addSchema(schemas) - - return ajv -} - -function validate (name, data) { - data = data || {} - - // validator config - ajv = ajv || createAjvInstance() - - var validate = ajv.getSchema(name + '.json') - - return new Promise(function (resolve, reject) { - var valid = validate(data) - - !valid ? reject(new HARError(validate.errors)) : resolve(data) - }) -} - -exports.afterRequest = function (data) { - return validate('afterRequest', data) -} - -exports.beforeRequest = function (data) { - return validate('beforeRequest', data) -} - -exports.browser = function (data) { - return validate('browser', data) -} - -exports.cache = function (data) { - return validate('cache', data) -} - -exports.content = function (data) { - return validate('content', data) -} - -exports.cookie = function (data) { - return validate('cookie', data) -} - -exports.creator = function (data) { - return validate('creator', data) -} - -exports.entry = function (data) { - return validate('entry', data) -} - -exports.har = function (data) { - return validate('har', data) -} - -exports.header = function (data) { - return validate('header', data) -} - -exports.log = function (data) { - return validate('log', data) -} - -exports.page = function (data) { - return validate('page', data) -} - -exports.pageTimings = function (data) { - return validate('pageTimings', data) -} - -exports.postData = function (data) { - return validate('postData', data) -} - -exports.query = function (data) { - return validate('query', data) -} - -exports.request = function (data) { - return validate('request', data) -} - -exports.response = function (data) { - return validate('response', data) -} - -exports.timings = function (data) { - return validate('timings', data) -} - -},{"./error":417,"ajv":8,"ajv/lib/refs/json-schema-draft-06.json":49,"har-schema":408}],419:[function(require,module,exports){ +},{"./bucket":286}],290:[function(require,module,exports){ (function (Buffer){ /* global Blob File */ @@ -61630,14 +41187,14 @@ function hasBinary (obj) { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"isarray":420}],420:[function(require,module,exports){ +},{"buffer":181,"isarray":291}],291:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],421:[function(require,module,exports){ +},{}],292:[function(require,module,exports){ /** * Module exports. @@ -61656,14 +41213,7 @@ try { module.exports = false; } -},{}],422:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":386}],423:[function(require,module,exports){ +},{}],293:[function(require,module,exports){ 'use strict' var Buffer = require('safe-buffer').Buffer var Transform = require('stream').Transform @@ -61760,7 +41310,7 @@ HashBase.prototype._digest = function () { module.exports = HashBase -},{"inherits":453,"safe-buffer":1593,"stream":1715}],424:[function(require,module,exports){ +},{"inherits":317,"safe-buffer":1371,"stream":1459}],294:[function(require,module,exports){ var hash = exports; hash.utils = require('./hash/utils'); @@ -61777,7 +41327,7 @@ hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; -},{"./hash/common":425,"./hash/hmac":426,"./hash/ripemd":427,"./hash/sha":428,"./hash/utils":435}],425:[function(require,module,exports){ +},{"./hash/common":295,"./hash/hmac":296,"./hash/ripemd":297,"./hash/sha":298,"./hash/utils":305}],295:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -61871,7 +41421,7 @@ BlockHash.prototype._pad = function pad() { return res; }; -},{"./utils":435,"minimalistic-assert":1303}],426:[function(require,module,exports){ +},{"./utils":305,"minimalistic-assert":1129}],296:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -61920,7 +41470,7 @@ Hmac.prototype.digest = function digest(enc) { return this.outer.digest(enc); }; -},{"./utils":435,"minimalistic-assert":1303}],427:[function(require,module,exports){ +},{"./utils":305,"minimalistic-assert":1129}],297:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -62068,7 +41618,7 @@ var sh = [ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; -},{"./common":425,"./utils":435}],428:[function(require,module,exports){ +},{"./common":295,"./utils":305}],298:[function(require,module,exports){ 'use strict'; exports.sha1 = require('./sha/1'); @@ -62077,7 +41627,7 @@ exports.sha256 = require('./sha/256'); exports.sha384 = require('./sha/384'); exports.sha512 = require('./sha/512'); -},{"./sha/1":429,"./sha/224":430,"./sha/256":431,"./sha/384":432,"./sha/512":433}],429:[function(require,module,exports){ +},{"./sha/1":299,"./sha/224":300,"./sha/256":301,"./sha/384":302,"./sha/512":303}],299:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62153,7 +41703,7 @@ SHA1.prototype._digest = function digest(enc) { return utils.split32(this.h, 'big'); }; -},{"../common":425,"../utils":435,"./common":434}],430:[function(require,module,exports){ +},{"../common":295,"../utils":305,"./common":304}],300:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62185,7 +41735,7 @@ SHA224.prototype._digest = function digest(enc) { }; -},{"../utils":435,"./256":431}],431:[function(require,module,exports){ +},{"../utils":305,"./256":301}],301:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62292,7 +41842,7 @@ SHA256.prototype._digest = function digest(enc) { return utils.split32(this.h, 'big'); }; -},{"../common":425,"../utils":435,"./common":434,"minimalistic-assert":1303}],432:[function(require,module,exports){ +},{"../common":295,"../utils":305,"./common":304,"minimalistic-assert":1129}],302:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62329,7 +41879,7 @@ SHA384.prototype._digest = function digest(enc) { return utils.split32(this.h.slice(0, 12), 'big'); }; -},{"../utils":435,"./512":433}],433:[function(require,module,exports){ +},{"../utils":305,"./512":303}],303:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62661,7 +42211,7 @@ function g1_512_lo(xh, xl) { return r; } -},{"../common":425,"../utils":435,"minimalistic-assert":1303}],434:[function(require,module,exports){ +},{"../common":295,"../utils":305,"minimalistic-assert":1129}],304:[function(require,module,exports){ 'use strict'; var utils = require('../utils'); @@ -62712,7 +42262,7 @@ function g1_256(x) { } exports.g1_256 = g1_256; -},{"../utils":435}],435:[function(require,module,exports){ +},{"../utils":305}],305:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); @@ -62992,7 +42542,7 @@ function shr64_lo(ah, al, num) { } exports.shr64_lo = shr64_lo; -},{"inherits":453,"minimalistic-assert":1303}],436:[function(require,module,exports){ +},{"inherits":317,"minimalistic-assert":1129}],306:[function(require,module,exports){ module.exports = function (max) { if (!max) throw Error('hashlru must have a max value, of type number, greater than 0') @@ -63045,10 +42595,10 @@ module.exports = function (max) { -},{}],437:[function(require,module,exports){ +},{}],307:[function(require,module,exports){ module.exports = require('./lib/heap'); -},{"./lib/heap":438}],438:[function(require,module,exports){ +},{"./lib/heap":308}],308:[function(require,module,exports){ // Generated by CoffeeScript 1.8.0 (function() { var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; @@ -63073,9 +42623,9 @@ module.exports = require('./lib/heap'); /* Insert item x in list a, and keep it sorted assuming a is sorted. - + If x is already in a, insert it to the right of the rightmost x. - + Optional args lo (default 0) and hi (default a.length) bound the slice of a to be searched. */ @@ -63142,7 +42692,7 @@ module.exports = require('./lib/heap'); /* Pop and return the current smallest value, and add the new item. - + This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed size heap. Note that the value returned may be larger than item! That constrains reasonable use of @@ -63425,7 +42975,7 @@ module.exports = require('./lib/heap'); }).call(this); -},{}],439:[function(require,module,exports){ +},{}],309:[function(require,module,exports){ (function (process,global){ /* * [hi-base32]{@link https://github.com/emn178/hi-base32} @@ -63880,7 +43430,7 @@ module.exports = require('./lib/heap'); })(); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1438}],440:[function(require,module,exports){ +},{"_process":1258}],310:[function(require,module,exports){ 'use strict'; var hash = require('hash.js'); @@ -63995,966 +43545,7 @@ HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { return utils.encode(res, enc); }; -},{"hash.js":424,"minimalistic-assert":1303,"minimalistic-crypto-utils":1304}],441:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -var parser = require('./parser'); -var signer = require('./signer'); -var verify = require('./verify'); -var utils = require('./utils'); - - - -///--- API - -module.exports = { - - parse: parser.parseRequest, - parseRequest: parser.parseRequest, - - sign: signer.signRequest, - signRequest: signer.signRequest, - createSigner: signer.createSigner, - isSigner: signer.isSigner, - - sshKeyToPEM: utils.sshKeyToPEM, - sshKeyFingerprint: utils.fingerprint, - pemToRsaSSHKey: utils.pemToRsaSSHKey, - - verify: verify.verifySignature, - verifySignature: verify.verifySignature, - verifyHMAC: verify.verifyHMAC -}; - -},{"./parser":442,"./signer":443,"./utils":444,"./verify":445}],442:[function(require,module,exports){ -// Copyright 2012 Joyent, Inc. All rights reserved. - -var assert = require('assert-plus'); -var util = require('util'); -var utils = require('./utils'); - - - -///--- Globals - -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var HttpSignatureError = utils.HttpSignatureError; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var validateAlgorithm = utils.validateAlgorithm; - -var State = { - New: 0, - Params: 1 -}; - -var ParamsState = { - Name: 0, - Quote: 1, - Value: 2, - Comma: 3 -}; - - -///--- Specific Errors - - -function ExpiredRequestError(message) { - HttpSignatureError.call(this, message, ExpiredRequestError); -} -util.inherits(ExpiredRequestError, HttpSignatureError); - - -function InvalidHeaderError(message) { - HttpSignatureError.call(this, message, InvalidHeaderError); -} -util.inherits(InvalidHeaderError, HttpSignatureError); - - -function InvalidParamsError(message) { - HttpSignatureError.call(this, message, InvalidParamsError); -} -util.inherits(InvalidParamsError, HttpSignatureError); - - -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); -} -util.inherits(MissingHeaderError, HttpSignatureError); - -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); -} -util.inherits(StrictParsingError, HttpSignatureError); - -///--- Exported API - -module.exports = { - - /** - * Parses the 'Authorization' header out of an http.ServerRequest object. - * - * Note that this API will fully validate the Authorization header, and throw - * on any error. It will not however check the signature, or the keyId format - * as those are specific to your environment. You can use the options object - * to pass in extra constraints. - * - * As a response object you can expect this: - * - * { - * "scheme": "Signature", - * "params": { - * "keyId": "foo", - * "algorithm": "rsa-sha256", - * "headers": [ - * "date" or "x-date", - * "digest" - * ], - * "signature": "base64" - * }, - * "signingString": "ready to be passed to crypto.verify()" - * } - * - * @param {Object} request an http.ServerRequest. - * @param {Object} options an optional options object with: - * - clockSkew: allowed clock skew in seconds (default 300). - * - headers: required header names (def: date or x-date) - * - algorithms: algorithms to support (default: all). - * - strict: should enforce latest spec parsing - * (default: false). - * @return {Object} parsed out object (see above). - * @throws {TypeError} on invalid input. - * @throws {InvalidHeaderError} on an invalid Authorization header error. - * @throws {InvalidParamsError} if the params in the scheme are invalid. - * @throws {MissingHeaderError} if the params indicate a header not present, - * either in the request headers from the params, - * or not in the params from a required header - * in options. - * @throws {StrictParsingError} if old attributes are used in strict parsing - * mode. - * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. - */ - parseRequest: function parseRequest(request, options) { - assert.object(request, 'request'); - assert.object(request.headers, 'request.headers'); - if (options === undefined) { - options = {}; - } - if (options.headers === undefined) { - options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; - } - assert.object(options, 'options'); - assert.arrayOfString(options.headers, 'options.headers'); - assert.optionalFinite(options.clockSkew, 'options.clockSkew'); - - var authzHeaderName = options.authorizationHeaderName || 'authorization'; - - if (!request.headers[authzHeaderName]) { - throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + - 'present in the request'); - } - - options.clockSkew = options.clockSkew || 300; - - - var i = 0; - var state = State.New; - var substate = ParamsState.Name; - var tmpName = ''; - var tmpValue = ''; - - var parsed = { - scheme: '', - params: {}, - signingString: '' - }; - - var authz = request.headers[authzHeaderName]; - for (i = 0; i < authz.length; i++) { - var c = authz.charAt(i); - - switch (Number(state)) { - - case State.New: - if (c !== ' ') parsed.scheme += c; - else state = State.Params; - break; - - case State.Params: - switch (Number(substate)) { - - case ParamsState.Name: - var code = c.charCodeAt(0); - // restricted name of A-Z / a-z - if ((code >= 0x41 && code <= 0x5a) || // A-Z - (code >= 0x61 && code <= 0x7a)) { // a-z - tmpName += c; - } else if (c === '=') { - if (tmpName.length === 0) - throw new InvalidHeaderError('bad param format'); - substate = ParamsState.Quote; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; - - case ParamsState.Quote: - if (c === '"') { - tmpValue = ''; - substate = ParamsState.Value; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; - - case ParamsState.Value: - if (c === '"') { - parsed.params[tmpName] = tmpValue; - substate = ParamsState.Comma; - } else { - tmpValue += c; - } - break; - - case ParamsState.Comma: - if (c === ',') { - tmpName = ''; - substate = ParamsState.Name; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; - - default: - throw new Error('Invalid substate'); - } - break; - - default: - throw new Error('Invalid substate'); - } - - } - - if (!parsed.params.headers || parsed.params.headers === '') { - if (request.headers['x-date']) { - parsed.params.headers = ['x-date']; - } else { - parsed.params.headers = ['date']; - } - } else { - parsed.params.headers = parsed.params.headers.split(' '); - } - - // Minimally validate the parsed object - if (!parsed.scheme || parsed.scheme !== 'Signature') - throw new InvalidHeaderError('scheme was not "Signature"'); - - if (!parsed.params.keyId) - throw new InvalidHeaderError('keyId was not specified'); - - if (!parsed.params.algorithm) - throw new InvalidHeaderError('algorithm was not specified'); - - if (!parsed.params.signature) - throw new InvalidHeaderError('signature was not specified'); - - // Check the algorithm against the official list - parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); - try { - validateAlgorithm(parsed.params.algorithm); - } catch (e) { - if (e instanceof InvalidAlgorithmError) - throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + - 'supported')); - else - throw (e); - } - - // Build the signingString - for (i = 0; i < parsed.params.headers.length; i++) { - var h = parsed.params.headers[i].toLowerCase(); - parsed.params.headers[i] = h; - - if (h === 'request-line') { - if (!options.strict) { - /* - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - parsed.signingString += - request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - parsed.signingString += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.url; - } else { - var value = request.headers[h]; - if (value === undefined) - throw new MissingHeaderError(h + ' was not in the request'); - parsed.signingString += h + ': ' + value; - } - - if ((i + 1) < parsed.params.headers.length) - parsed.signingString += '\n'; - } - - // Check against the constraints - var date; - if (request.headers.date || request.headers['x-date']) { - if (request.headers['x-date']) { - date = new Date(request.headers['x-date']); - } else { - date = new Date(request.headers.date); - } - var now = new Date(); - var skew = Math.abs(now.getTime() - date.getTime()); - - if (skew > options.clockSkew * 1000) { - throw new ExpiredRequestError('clock skew of ' + - (skew / 1000) + - 's was greater than ' + - options.clockSkew + 's'); - } - } - - options.headers.forEach(function (hdr) { - // Remember that we already checked any headers in the params - // were in the request, so if this passes we're good. - if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) - throw new MissingHeaderError(hdr + ' was not a signed header'); - }); - - if (options.algorithms) { - if (options.algorithms.indexOf(parsed.params.algorithm) === -1) - throw new InvalidParamsError(parsed.params.algorithm + - ' is not a supported algorithm'); - } - - parsed.algorithm = parsed.params.algorithm.toUpperCase(); - parsed.keyId = parsed.params.keyId; - return parsed; - } - -}; - -},{"./utils":444,"assert-plus":77,"util":1776}],443:[function(require,module,exports){ -(function (Buffer){ -// Copyright 2012 Joyent, Inc. All rights reserved. - -var assert = require('assert-plus'); -var crypto = require('crypto'); -var http = require('http'); -var util = require('util'); -var sshpk = require('sshpk'); -var jsprim = require('jsprim'); -var utils = require('./utils'); - -var sprintf = require('util').format; - -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; - -///--- Globals - -var AUTHZ_FMT = - 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; - -///--- Specific Errors - -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); -} -util.inherits(MissingHeaderError, HttpSignatureError); - -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); -} -util.inherits(StrictParsingError, HttpSignatureError); - -/* See createSigner() */ -function RequestSigner(options) { - assert.object(options, 'options'); - - var alg = []; - if (options.algorithm !== undefined) { - assert.string(options.algorithm, 'options.algorithm'); - alg = validateAlgorithm(options.algorithm); - } - this.rs_alg = alg; - - /* - * RequestSigners come in two varieties: ones with an rs_signFunc, and ones - * with an rs_signer. - * - * rs_signFunc-based RequestSigners have to build up their entire signing - * string within the rs_lines array and give it to rs_signFunc as a single - * concat'd blob. rs_signer-based RequestSigners can add a line at a time to - * their signing state by using rs_signer.update(), thus only needing to - * buffer the hash function state and one line at a time. - */ - if (options.sign !== undefined) { - assert.func(options.sign, 'options.sign'); - this.rs_signFunc = options.sign; - - } else if (alg[0] === 'hmac' && options.key !== undefined) { - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; - - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key for HMAC must be a string or Buffer')); - - /* - * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their - * data in chunks rather than requiring it all to be given in one go - * at the end, so they are more similar to signers than signFuncs. - */ - this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); - this.rs_signer.sign = function () { - var digest = this.digest('base64'); - return ({ - hashAlgorithm: alg[1], - toString: function () { return (digest); } - }); - }; - - } else if (options.key !== undefined) { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(key); - - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); - this.rs_key = key; - - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; - - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } - - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } - - this.rs_signer = key.createSign(alg[1]); - - } else { - throw (new TypeError('options.sign (func) or options.key is required')); - } - - this.rs_headers = []; - this.rs_lines = []; -} - -/** - * Adds a header to be signed, with its value, into this signer. - * - * @param {String} header - * @param {String} value - * @return {String} value written - */ -RequestSigner.prototype.writeHeader = function (header, value) { - assert.string(header, 'header'); - header = header.toLowerCase(); - assert.string(value, 'value'); - - this.rs_headers.push(header); - - if (this.rs_signFunc) { - this.rs_lines.push(header + ': ' + value); - - } else { - var line = header + ': ' + value; - if (this.rs_headers.length > 0) - line = '\n' + line; - this.rs_signer.update(line); - } - - return (value); -}; - -/** - * Adds a default Date header, returning its value. - * - * @return {String} - */ -RequestSigner.prototype.writeDateHeader = function () { - return (this.writeHeader('date', jsprim.rfc1123(new Date()))); -}; - -/** - * Adds the request target line to be signed. - * - * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') - * @param {String} path - */ -RequestSigner.prototype.writeTarget = function (method, path) { - assert.string(method, 'method'); - assert.string(path, 'path'); - method = method.toLowerCase(); - this.writeHeader('(request-target)', method + ' ' + path); -}; - -/** - * Calculate the value for the Authorization header on this request - * asynchronously. - * - * @param {Func} callback (err, authz) - */ -RequestSigner.prototype.sign = function (cb) { - assert.func(cb, 'callback'); - - if (this.rs_headers.length < 1) - throw (new Error('At least one header must be signed')); - - var alg, authz; - if (this.rs_signFunc) { - var data = this.rs_lines.join('\n'); - var self = this; - this.rs_signFunc(data, function (err, sig) { - if (err) { - cb(err); - return; - } - try { - assert.object(sig, 'signature'); - assert.string(sig.keyId, 'signature.keyId'); - assert.string(sig.algorithm, 'signature.algorithm'); - assert.string(sig.signature, 'signature.signature'); - alg = validateAlgorithm(sig.algorithm); - - authz = sprintf(AUTHZ_FMT, - sig.keyId, - sig.algorithm, - self.rs_headers.join(' '), - sig.signature); - } catch (e) { - cb(e); - return; - } - cb(null, authz); - }); - - } else { - try { - var sigObj = this.rs_signer.sign(); - } catch (e) { - cb(e); - return; - } - alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; - var signature = sigObj.toString(); - authz = sprintf(AUTHZ_FMT, - this.rs_keyId, - alg, - this.rs_headers.join(' '), - signature); - cb(null, authz); - } -}; - -///--- Exported API - -module.exports = { - /** - * Identifies whether a given object is a request signer or not. - * - * @param {Object} object, the object to identify - * @returns {Boolean} - */ - isSigner: function (obj) { - if (typeof (obj) === 'object' && obj instanceof RequestSigner) - return (true); - return (false); - }, - - /** - * Creates a request signer, used to asynchronously build a signature - * for a request (does not have to be an http.ClientRequest). - * - * @param {Object} options, either: - * - {String} keyId - * - {String|Buffer} key - * - {String} algorithm (optional, required for HMAC) - * or: - * - {Func} sign (data, cb) - * @return {RequestSigner} - */ - createSigner: function createSigner(options) { - return (new RequestSigner(options)); - }, - - /** - * Adds an 'Authorization' header to an http.ClientRequest object. - * - * Note that this API will add a Date header if it's not already set. Any - * other headers in the options.headers array MUST be present, or this - * will throw. - * - * You shouldn't need to check the return type; it's just there if you want - * to be pedantic. - * - * The optional flag indicates whether parsing should use strict enforcement - * of the version draft-cavage-http-signatures-04 of the spec or beyond. - * The default is to be loose and support - * older versions for compatibility. - * - * @param {Object} request an instance of http.ClientRequest. - * @param {Object} options signing parameters object: - * - {String} keyId required. - * - {String} key required (either a PEM or HMAC key). - * - {Array} headers optional; defaults to ['date']. - * - {String} algorithm optional (unless key is HMAC); - * default is the same as the sshpk default - * signing algorithm for the type of key given - * - {String} httpVersion optional; defaults to '1.1'. - * - {Boolean} strict optional; defaults to 'false'. - * @return {Boolean} true if Authorization (and optionally Date) were added. - * @throws {TypeError} on bad parameter types (input). - * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with - * the given key. - * @throws {sshpk.KeyParseError} if key was bad. - * @throws {MissingHeaderError} if a header to be signed was specified but - * was not present. - */ - signRequest: function signRequest(request, options) { - assert.object(request, 'request'); - assert.object(options, 'options'); - assert.optionalString(options.algorithm, 'options.algorithm'); - assert.string(options.keyId, 'options.keyId'); - assert.optionalArrayOfString(options.headers, 'options.headers'); - assert.optionalString(options.httpVersion, 'options.httpVersion'); - - if (!request.getHeader('Date')) - request.setHeader('Date', jsprim.rfc1123(new Date())); - if (!options.headers) - options.headers = ['date']; - if (!options.httpVersion) - options.httpVersion = '1.1'; - - var alg = []; - if (options.algorithm) { - options.algorithm = options.algorithm.toLowerCase(); - alg = validateAlgorithm(options.algorithm); - } - - var i; - var stringToSign = ''; - for (i = 0; i < options.headers.length; i++) { - if (typeof (options.headers[i]) !== 'string') - throw new TypeError('options.headers must be an array of Strings'); - - var h = options.headers[i].toLowerCase(); - - if (h === 'request-line') { - if (!options.strict) { - /** - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - stringToSign += - request.method + ' ' + request.path + ' HTTP/' + - options.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - stringToSign += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.path; - } else { - var value = request.getHeader(h); - if (value === undefined || value === '') { - throw new MissingHeaderError(h + ' was not in the request'); - } - stringToSign += h + ': ' + value; - } - - if ((i + 1) < options.headers.length) - stringToSign += '\n'; - } - - /* This is just for unit tests. */ - if (request.hasOwnProperty('_stringToSign')) { - request._stringToSign = stringToSign; - } - - var signature; - if (alg[0] === 'hmac') { - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key must be a string or Buffer')); - - var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); - hmac.update(stringToSign); - signature = hmac.digest('base64'); - - } else { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(options.key); - - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); - - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } - - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } - - var signer = key.createSign(alg[1]); - signer.update(stringToSign); - var sigObj = signer.sign(); - if (!HASH_ALGOS[sigObj.hashAlgorithm]) { - throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + - ' is not a supported hash algorithm')); - } - options.algorithm = key.type + '-' + sigObj.hashAlgorithm; - signature = sigObj.toString(); - assert.notStrictEqual(signature, '', 'empty signature produced'); - } - - var authzHeaderName = options.authorizationHeaderName || 'Authorization'; - - request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, - options.keyId, - options.algorithm, - options.headers.join(' '), - signature)); - - return true; - } - -}; - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./utils":444,"assert-plus":77,"crypto":236,"http":1716,"jsprim":829,"sshpk":1708,"util":1776}],444:[function(require,module,exports){ -// Copyright 2012 Joyent, Inc. All rights reserved. - -var assert = require('assert-plus'); -var sshpk = require('sshpk'); -var util = require('util'); - -var HASH_ALGOS = { - 'sha1': true, - 'sha256': true, - 'sha512': true -}; - -var PK_ALGOS = { - 'rsa': true, - 'dsa': true, - 'ecdsa': true -}; - -function HttpSignatureError(message, caller) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, caller || HttpSignatureError); - - this.message = message; - this.name = caller.name; -} -util.inherits(HttpSignatureError, Error); - -function InvalidAlgorithmError(message) { - HttpSignatureError.call(this, message, InvalidAlgorithmError); -} -util.inherits(InvalidAlgorithmError, HttpSignatureError); - -function validateAlgorithm(algorithm) { - var alg = algorithm.toLowerCase().split('-'); - - if (alg.length !== 2) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + - 'valid algorithm')); - } - - if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + - 'are not supported')); - } - - if (!HASH_ALGOS[alg[1]]) { - throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + - 'supported hash algorithm')); - } - - return (alg); -} - -///--- API - -module.exports = { - - HASH_ALGOS: HASH_ALGOS, - PK_ALGOS: PK_ALGOS, - - HttpSignatureError: HttpSignatureError, - InvalidAlgorithmError: InvalidAlgorithmError, - - validateAlgorithm: validateAlgorithm, - - /** - * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. - * - * The intent of this module is to interoperate with OpenSSL only, - * specifically the node crypto module's `verify` method. - * - * @param {String} key an OpenSSH public key. - * @return {String} PEM encoded form of the RSA public key. - * @throws {TypeError} on bad input. - * @throws {Error} on invalid ssh key formatted data. - */ - sshKeyToPEM: function sshKeyToPEM(key) { - assert.string(key, 'ssh_key'); - - var k = sshpk.parseKey(key, 'ssh'); - return (k.toString('pem')); - }, - - - /** - * Generates an OpenSSH fingerprint from an ssh public key. - * - * @param {String} key an OpenSSH public key. - * @return {String} key fingerprint. - * @throws {TypeError} on bad input. - * @throws {Error} if what you passed doesn't look like an ssh public key. - */ - fingerprint: function fingerprint(key) { - assert.string(key, 'ssh_key'); - - var k = sshpk.parseKey(key, 'ssh'); - return (k.fingerprint('md5').toString('hex')); - }, - - /** - * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) - * - * The reverse of the above function. - */ - pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { - assert.equal('string', typeof (pem), 'typeof pem'); - - var k = sshpk.parseKey(pem, 'pem'); - k.comment = comment; - return (k.toString('ssh')); - } -}; - -},{"assert-plus":77,"sshpk":1708,"util":1776}],445:[function(require,module,exports){ -(function (Buffer){ -// Copyright 2015 Joyent, Inc. - -var assert = require('assert-plus'); -var crypto = require('crypto'); -var sshpk = require('sshpk'); -var utils = require('./utils'); - -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; - -///--- Exported API - -module.exports = { - /** - * Verify RSA/DSA signature against public key. You are expected to pass in - * an object that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} pubkey RSA/DSA private key PEM. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifySignature: function verifySignature(parsedSignature, pubkey) { - assert.object(parsedSignature, 'parsedSignature'); - if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) - pubkey = sshpk.parseKey(pubkey); - assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); - - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] === 'hmac' || alg[0] !== pubkey.type) - return (false); - - var v = pubkey.createVerify(alg[1]); - v.update(parsedSignature.signingString); - return (v.verify(parsedSignature.params.signature, 'base64')); - }, - - /** - * Verify HMAC against shared secret. You are expected to pass in an object - * that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} secret HMAC shared secret. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifyHMAC: function verifyHMAC(parsedSignature, secret) { - assert.object(parsedSignature, 'parsedHMAC'); - assert.string(secret, 'secret'); - - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] !== 'hmac') - return (false); - - var hashAlg = alg[1].toUpperCase(); - - var hmac = crypto.createHmac(hashAlg, secret); - hmac.update(parsedSignature.signingString); - - /* - * Now double-hash to avoid leaking timing information - there's - * no easy constant-time compare in JS, so we use this approach - * instead. See for more info: - * https://www.isecpartners.com/blog/2011/february/double-hmac- - * verification.aspx - */ - var h1 = crypto.createHmac(hashAlg, secret); - h1.update(hmac.digest()); - h1 = h1.digest(); - var h2 = crypto.createHmac(hashAlg, secret); - h2.update(new Buffer(parsedSignature.params.signature, 'base64')); - h2 = h2.digest(); - - /* Node 0.8 returns strings from .digest(). */ - if (typeof (h1) === 'string') - return (h1 === h2); - /* And node 0.10 lacks the .equals() method on Buffers. */ - if (Buffer.isBuffer(h1) && !h1.equals) - return (h1.toString('binary') === h2.toString('binary')); - - return (h1.equals(h2)); - } -}; - -}).call(this,require("buffer").Buffer) -},{"./utils":444,"assert-plus":77,"buffer":217,"crypto":236,"sshpk":1708}],446:[function(require,module,exports){ +},{"hash.js":294,"minimalistic-assert":1129,"minimalistic-crypto-utils":1130}],311:[function(require,module,exports){ var http = require('http') var url = require('url') @@ -64987,7 +43578,7 @@ function validateParams (params) { return params } -},{"http":1716,"url":1769}],447:[function(require,module,exports){ +},{"http":1475,"url":1507}],312:[function(require,module,exports){ 'use strict' const whole = /^((\d+(\.\d+)*)(ns|ms|us|µs|m|s|h))+$/ @@ -65025,7 +43616,7 @@ module.exports = function (time) { }, 0) } -},{}],448:[function(require,module,exports){ +},{}],313:[function(require,module,exports){ /** * Copyright (c) 2016 Tim Kuijsten * @@ -65163,900 +43754,9 @@ function idbReadableStream(db, storeName, opts) { module.exports = idbReadableStream -},{"stream":1715,"xtend":1860}],449:[function(require,module,exports){ -/* This file is generated from the Unicode IDNA table, using - the build-unicode-tables.py script. Please edit that - script instead of this file. */ - -/* istanbul ignore next */ -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define([], function () { return factory(); }); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.uts46_map = factory(); - } -}(this, function () { -var blocks = [ - new Uint32Array([2157250,2157314,2157378,2157442,2157506,2157570,2157634,0,2157698,2157762,2157826,2157890,2157954,0,2158018,0]), - new Uint32Array([2179041,6291456,2179073,6291456,2179105,6291456,2179137,6291456,2179169,6291456,2179201,6291456,2179233,6291456,2179265,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064]), - new Uint32Array([0,2113729,2197345,2197377,2113825,2197409,2197441,2113921,2197473,2114017,2197505,2197537,2197569,2197601,2197633,2197665]), - new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672,23068672,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672,23068672,0,0,0,0,23068672]), - new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064]), - new Uint32Array([2196001,2196033,2196065,2196097,2196129,2196161,2196193,2196225,2196257,2196289,2196321,2196353,2196385,2196417,2196449,2196481]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,0,0,0,0,0]), - new Uint32Array([2097281,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), - new Uint32Array([2177025,6291456,2177057,6291456,2177089,6291456,2177121,6291456,2177153,6291456,2177185,6291456,2177217,6291456,2177249,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456]), - new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456]), - new Uint32Array([2134435,2134531,2134627,2134723,2134723,2134819,2134819,2134915,2134915,2135011,2105987,2135107,2135203,2135299,2131587,2135395]), - new Uint32Array([0,0,0,0,0,0,0,6291456,2168673,2169249,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354,2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354]), - new Uint32Array([2125219,2125315,2152834,2152898,2125411,2152962,2153026,2125506,2125507,2125603,2153090,2153154,2153218,2153282,2153346,2105348]), - new Uint32Array([2203393,6291456,2203425,6291456,2203457,6291456,2203489,6291456,6291456,6291456,6291456,2203521,6291456,2181281,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,23068672,6291456,2145538,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,6291456]), - new Uint32Array([2139426,2160834,2160898,2160962,2134242,2161026,2161090,2161154,2161218,2161282,2161346,2161410,2138658,2161474,2161538,2134722]), - new Uint32Array([2119939,2124930,2125026,2106658,2125218,2128962,2129058,2129154,2129250,2129346,2129442,2108866,2108770,2150466,2150530,2150594]), - new Uint32Array([2201601,6291456,2201633,6291456,2201665,6291456,2201697,6291456,2201729,6291456,2201761,6291456,2201793,6291456,2201825,6291456]), - new Uint32Array([2193537,2193569,2193601,2193633,2193665,2193697,2193729,2193761,2193793,2193825,2193857,2193889,2193921,2193953,2193985,2194017]), - new Uint32Array([6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2190561,6291456,2190593,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2190625,6291456,2190657,6291456,23068672]), - new Uint32Array([2215905,2215937,2215969,2216001,2216033,2216065,2216097,2216129,2216161,2216193,2216225,2216257,2105441,2216289,2216321,2216353]), - new Uint32Array([23068672,18884130,23068672,23068672,23068672,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2191233,2191265,2191297,2191329,2191361,2191393,2191425,2117377,2191457,2191489,2191521,2191553,2191585,2191617,2191649,2117953]), - new Uint32Array([2132227,2132323,2132419,2132419,2132515,2132515,2132611,2132707,2132707,2132803,2132899,2132899,2132995,2132995,2133091,2133187]), - new Uint32Array([0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,0,0]), - new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10609889,10610785,10609921,10610817,2222241]), - new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), - new Uint32Array([2219969,2157121,2157441,2157505,2157889,2157953,2220001,2158465,2158529,10575617,2156994,2157058,2129923,2130019,2157122,2157186]), - new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), - new Uint32Array([2185249,6291456,2185281,6291456,2185313,6291456,2185345,6291456,2185377,6291456,2185409,6291456,2185441,6291456,2185473,6291456]), - new Uint32Array([0,0,0,0,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,6291456,0]), - new Uint32Array([2183361,6291456,2183393,6291456,2183425,6291456,2183457,6291456,2183489,6291456,2183521,6291456,2183553,6291456,2183585,6291456]), - new Uint32Array([2192161,2192193,2192225,2192257,2192289,2192321,2192353,2192385,2192417,2192449,2192481,2192513,2192545,2192577,2192609,2192641]), - new Uint32Array([2212001,2212033,2212065,2212097,2212129,2212161,2212193,2212225,2212257,2212289,2212321,2212353,2212385,2212417,2212449,2207265]), - new Uint32Array([2249825,2249857,2249889,2249921,2249954,2250018,2250082,2250145,2250177,2250209,2250241,2250274,2250337,2250370,2250433,2250465]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147905,2147969,2148033,2148097,2148161,2148225,2148289,2148353]), - new Uint32Array([10485857,6291456,2197217,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672]), - new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), - new Uint32Array([2180353,2180385,2144033,2180417,2180449,2180481,2180513,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10610209,10610465,10610241,10610753,10609857]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), - new Uint32Array([2223842,2223906,2223970,2224034,2224098,2224162,2224226,2224290,2224354,2224418,2224482,2224546,2224610,2224674,2224738,2224802]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), - new Uint32Array([23068672,23068672,23068672,18923650,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,18923714,23068672,23068672]), - new Uint32Array([2126179,2125538,2126275,2126371,2126467,2125634,2126563,2105603,2105604,2125346,2126659,2126755,2126851,2098179,2098181,2098182]), - new Uint32Array([2227426,2227490,2227554,2227618,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2192353,2240642,2240642,2240705,2240737,2240737,2240769,2240802,2240866,2240929,2240961,2240993,2241025,2241057,2241089,2241121]), - new Uint32Array([6291456,2170881,2170913,2170945,6291456,2170977,6291456,2171009,2171041,6291456,6291456,6291456,2171073,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2132226,2132514,2163586,2132610,2160386,2133090,2133186,2160450,2160514,2160578,2133570,2106178,2160642,2133858,2160706,2160770]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10532162,10532226,10532290,10532354,10532418,10532482,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), - new Uint32Array([2098209,2108353,2108193,2108481,2170241,2111713,2105473,2105569,2105601,2112289,2112481,2098305,2108321,0,0,0]), - new Uint32Array([2209121,2209153,2209185,2209217,2209249,2209281,2209313,2209345,2209377,2209409,2209441,2209473,2207265,2209505,2209537,2209569]), - new Uint32Array([2189025,6291456,2189057,6291456,2189089,6291456,2189121,6291456,2189153,6291456,2189185,6291456,2189217,6291456,2189249,6291456]), - new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2165764,2140004]), - new Uint32Array([2215105,6291456,2215137,6291456,6291456,2215169,2215201,6291456,6291456,6291456,2215233,2215265,2215297,2215329,2215361,2215393]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,6291456,6291456,6291456,23068672,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([10505091,10505187,10505283,10505379,10505475,10505571,10505667,10505763,10505859,10505955,10506051,10506147,10506243,10506339,10506435,10506531]), - new Uint32Array([2229730,2229794,2229858,2229922,2229986,2230050,2230114,2230178,2230242,2230306,2230370,2230434,2230498,2230562,2230626,2230690]), - new Uint32Array([2105505,2098241,2108353,2108417,2105825,0,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), - new Uint32Array([6291456,6291456,6291456,6291456,10502115,10502178,10502211,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), - new Uint32Array([2190305,6291456,2190337,6291456,2190369,6291456,2190401,6291456,2190433,6291456,2190465,6291456,2190497,6291456,2190529,6291456]), - new Uint32Array([2173793,2173985,2174017,6291456,2173761,2173697,6291456,2174689,6291456,2174017,2174721,6291456,6291456,2174753,2174785,2174817]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609,2100033]), - new Uint32Array([2132898,2163842,2163906,2133282,2132034,2131938,2137410,2132802,2132706,2164866,2133282,2160578,2165186,2165186,6291456,6291456]), - new Uint32Array([10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059,10501155,10501251,10501347,10501443]), - new Uint32Array([2163458,2130978,2131074,2131266,2131362,2163522,2160130,2132066,2131010,2131106,2106018,2131618,2131298,2132034,2131938,2137410]), - new Uint32Array([2212961,2116993,2212993,2213025,2213057,2213089,2213121,2213153,2213185,2213217,2213249,2209633,2213281,2213313,2213345,2213377]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), - new Uint32Array([2113729,2113825,2113921,2114017,2114113,2114209,2114305,2114401,2114497,2114593,2114689,2114785,2114881,2114977,2115073,2115169]), - new Uint32Array([2238177,2238209,2238241,2238273,2238305,2238337,2238337,2217537,2238369,2238401,2238433,2238465,2215649,2238497,2238529,2238561]), - new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), - new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0]), - new Uint32Array([6291456,0,6291456,2145026,0,6291456,2145090,0,6291456,6291456,0,0,23068672,0,23068672,23068672]), - new Uint32Array([2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129,2100289]), - new Uint32Array([6291456,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0]), - new Uint32Array([2187681,2187713,2187745,2187777,2187809,2187841,2187873,2187905,2187937,2187969,2188001,2188033,2188065,2188097,2188129,2188161]), - new Uint32Array([0,10554498,10554562,10554626,10554690,10554754,10554818,10554882,10554946,10555010,10555074,6291456,6291456,0,0,0]), - new Uint32Array([2235170,2235234,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0]), - new Uint32Array([2181153,6291456,2188897,6291456,6291456,2188929,6291456,6291456,6291456,6291456,6291456,6291456,2111905,2100865,2188961,2188993]), - new Uint32Array([2100833,2100897,0,0,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,2112289]), - new Uint32Array([6291456,2172833,6291456,2172865,2172897,2172929,2172961,6291456,2172993,6291456,2173025,6291456,2173057,6291456,2173089,6291456]), - new Uint32Array([6291456,0,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,2190721]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456]), - new Uint32Array([2184993,6291456,2185025,6291456,2185057,6291456,2185089,6291456,2185121,6291456,2185153,6291456,2185185,6291456,2185217,6291456]), - new Uint32Array([2115265,2115361,2115457,2115553,2115649,2115745,2115841,2115937,2116033,2116129,2116225,2116321,2150658,2150722,2200225,6291456]), - new Uint32Array([2168321,6291456,2168353,6291456,2168385,6291456,2168417,6291456,2168449,6291456,2168481,6291456,2168513,6291456,2168545,6291456]), - new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,0,6291456,0,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,2186625,0,0,6291456,6291456,2186657,2186689,2186721,2173505,0,10496067,10496163,10496259]), - new Uint32Array([2178785,6291456,2178817,6291456,2178849,6291456,2178881,6291456,2178913,6291456,2178945,6291456,2178977,6291456,2179009,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), - new Uint32Array([2097152,0,0,0,2097152,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,0,2197857,2197889,2197921,2197953,2197985,2198017,0,0,2198049,2198081,2198113,2198145,2198177,2198209]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2098209,2167297,2111137,6291456]), - new Uint32Array([2171393,6291456,2171425,6291456,2171457,6291456,2171489,6291456,2171521,6291456,2171553,6291456,2171585,6291456,2171617,6291456]), - new Uint32Array([2206753,2206785,2195457,2206817,2206849,2206881,2206913,2197153,2197153,2206945,2117857,2206977,2207009,2207041,2207073,2207105]), - new Uint32Array([0,0,0,0,0,0,0,23068672,0,0,0,0,2144834,2144898,0,2144962]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672]), - new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,0,2105505,2098241]), - new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,2202049,6291456,2202081,6291456,2202113,6291456,2202145,6291456,2202177,6291456,2202209,6291456,2202241,6291456]), - new Uint32Array([10501155,10501251,10501347,10501443,10501539,10501635,10501731,10501827,10501923,10502019,2141731,2105505,2098177,2155586,2166530,0]), - new Uint32Array([2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441]), - new Uint32Array([2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330,2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([10502307,10502403,10502499,10502595,10502691,10502787,10502883,10502979,10503075,10503171,10503267,10503363,10503459,10503555,10503651,10503747]), - new Uint32Array([2179937,2179969,2180001,2180033,2156545,2180065,2156577,2180097,2180129,2180161,2180193,2180225,2180257,2180289,2156737,2180321]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,0,0,6291456,0,0,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), - new Uint32Array([2227682,2227746,2227810,2227874,2227938,2228002,2228066,2228130,2228194,2228258,2228322,2228386,2228450,2228514,2228578,2228642]), - new Uint32Array([2105601,2169121,2108193,2170049,2181025,2181057,2112481,2108321,2108289,2181089,2170497,2100865,2181121,2173601,2173633,2173665]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180641,6291456,6291456,6291456]), - new Uint32Array([0,6291456,6291456,6291456,0,6291456,0,6291456,0,0,6291456,6291456,0,6291456,6291456,6291456]), - new Uint32Array([2178273,6291456,2178305,6291456,2178337,6291456,2178369,6291456,2178401,6291456,2178433,6291456,2178465,6291456,2178497,6291456]), - new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064,14680064]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), - new Uint32Array([2237377,2237409,2236225,2237441,2237473,2217441,2215521,2215553,2217473,2237505,2237537,2209697,2237569,2215585,2237601,2237633]), - new Uint32Array([2221985,2165601,2165601,2165665,2165665,2222017,2222017,2165729,2165729,2158913,2158913,2158913,2158913,2097281,2097281,2105921]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2149634,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2176897,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2176929,6291456,2176961,6291456,2176993,6291456]), - new Uint32Array([2172641,6291456,2172673,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2172705,2172737,6291456,2172769,2172801,6291456]), - new Uint32Array([2099173,2104196,2121667,2099395,2121763,2152258,2152322,2098946,2152386,2121859,2121955,2099333,2122051,2104324,2099493,2122147]), - new Uint32Array([6291456,6291456,6291456,2145794,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2145858,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,0,0,6291456,0]), - new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,0,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2239074,2239138,2239201,2239233,2239265,2239297,2239329,2239361,0,2239393,2239425,2239425,2239458,2239521,2239553,2209569]), - new Uint32Array([14680064,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,6291456,23068672]), - new Uint32Array([2108321,2108289,2113153,2098209,2180897,2180929,2180961,2111137,2098241,2108353,2170241,2170273,2180993,2105825,6291456,2105473]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146114,6291456,6291456,6291456,0,0,0]), - new Uint32Array([2105921,2105921,2105921,2222049,2222049,2130977,2130977,2130977,2130977,2160065,2160065,2160065,2160065,2097729,2097729,2097729]), - new Uint32Array([2218145,2214785,2207937,2218177,2218209,2192993,2210113,2212769,2218241,2218273,2216129,2218305,2216161,2218337,2218369,2218401]), - new Uint32Array([0,0,0,2156546,2156610,2156674,2156738,2156802,0,0,0,0,0,2156866,23068672,2156930]), - new Uint32Array([23068672,23068672,23068672,0,0,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), - new Uint32Array([2213409,2213441,2213473,2213505,2213537,2213569,2213601,2213633,2213665,2195681,2213697,2213729,2213761,2213793,2213825,2213857]), - new Uint32Array([2100033,2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2201857,6291456,2201889,6291456,2201921,6291456,2201953,6291456,2201985,6291456,2202017,6291456,2176193,2176257,23068672,23068672]), - new Uint32Array([6291456,6291456,23068672,23068672,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2188193,2188225,2188257,2188289,2188321,2188353,2188385,2188417,2188449,2188481,2188513,2188545,2188577,2188609,2188641,0]), - new Uint32Array([10554529,2221089,0,10502113,10562017,10537921,10538049,2221121,2221153,0,0,0,0,0,0,0]), - new Uint32Array([2213889,2213921,2213953,2213985,2214017,2214049,2214081,2194177,2214113,2214145,2214177,2214209,2214241,2214273,2214305,2214337]), - new Uint32Array([2166978,2167042,2099169,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180545,6291456,6291456,6291456]), - new Uint32Array([10518915,10519011,10519107,10519203,2162242,2162306,2159554,2162370,2159362,2159618,2105922,2162434,2159746,2162498,2159810,2159874]), - new Uint32Array([2161730,2161794,2135586,2161858,2161922,2137186,2131810,2160290,2135170,2161986,2137954,2162050,2162114,2162178,10518723,10518819]), - new Uint32Array([10506627,10506723,10506819,10506915,10507011,10507107,10507203,10507299,10507395,10507491,10507587,10507683,10507779,10507875,10507971,10508067]), - new Uint32Array([6291456,23068672,23068672,23068672,0,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), - new Uint32Array([2175873,2175905,2175937,2175969,2176001,2176033,2176065,2176097,2176129,2176161,2176193,2176225,2176257,2176289,2176321,2176353]), - new Uint32Array([2140006,2140198,2140390,2140582,2140774,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,23068672,23068672,23068672]), - new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241]), - new Uint32Array([0,23068672,0,0,0,0,0,0,0,2145154,2145218,2145282,6291456,0,2145346,0]), - new Uint32Array([0,0,0,0,10531458,10495395,2148545,2143201,2173473,2148865,2173505,0,2173537,0,2173569,2149121]), - new Uint32Array([10537282,10495683,2148738,2148802,2148866,0,6291456,2148930,2186593,2173473,2148737,2148865,2148802,10495779,10495875,10495971]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2215425,2215457,2215489,2215521,2215553,2215585,2215617,2215649,2215681,2215713,2215745,2215777,2192033,2215809,2215841,2215873]), - new Uint32Array([2242049,2242081,2242113,2242145,2242177,2242209,2242241,2242273,2215937,2242305,2242338,2242401,2242433,2242465,2242497,2216001]), - new Uint32Array([10554529,2221089,0,0,10562017,10502113,10538049,10537921,2221185,10489601,10489697,10609889,10609921,2141729,2141793,10610273]), - new Uint32Array([2141923,2142019,2142115,2142211,2142307,2142403,2142499,2142595,2142691,0,0,0,0,0,0,0]), - new Uint32Array([0,2221185,2221217,10609857,10609857,10489601,10489697,10609889,10609921,2141729,2141793,2221345,2221377,2221409,2221441,2187105]), - new Uint32Array([6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18923970,23068672,23068672,23068672,0,6291456,6291456]), - new Uint32Array([2183105,6291456,2183137,6291456,2183169,6291456,2183201,6291456,2183233,6291456,2183265,6291456,2183297,6291456,2183329,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), - new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), - new Uint32Array([2134434,2134818,2097666,2097186,2097474,2097698,2105986,2131586,2132450,2131874,2131778,2135970,2135778,2161602,2136162,2161666]), - new Uint32Array([2236865,2236897,2236930,2236993,2237025,2235681,2237058,2237121,2237153,2237185,2237217,2217281,2237250,2191233,2237313,2237345]), - new Uint32Array([2190049,6291456,2190081,6291456,2190113,6291456,2190145,6291456,2190177,6291456,2190209,6291456,2190241,6291456,2190273,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2101922,2102050,2102178,2102306,10498755,10498851,10498947,10499043,10499139,10499235,10499331,10499427,10499523,10489604,10489732,10489860]), - new Uint32Array([2166914,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), - new Uint32Array([2181601,2170561,2181633,2181665,2170753,2181697,2172897,2170881,2181729,2170913,2172929,2113441,2181761,2181793,2171009,2173761]), - new Uint32Array([0,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), - new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0]), - new Uint32Array([2248001,2248033,2248066,2248130,2248193,2248226,2248289,2248322,2248385,2248417,2216673,2248450,2248514,2248577,2248610,2248673]), - new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,0,0,0]), - new Uint32Array([2169729,6291456,2169761,6291456,2169793,6291456,2169825,6291456,2169857,2169889,6291456,2169921,6291456,2143329,6291456,2098305]), - new Uint32Array([2162178,2163202,2163266,2135170,2136226,2161986,2137954,2159426,2159490,2163330,2159554,2163394,2159682,2139522,2136450,2159746]), - new Uint32Array([2173953,2173985,0,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2174209,2174241,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,4271169,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2174273]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,2190785,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2189793,6291456,2189825,6291456,2189857,6291456,2189889,6291456,2189921,6291456,2189953,6291456,2189985,6291456,2190017,6291456]), - new Uint32Array([2105601,2112289,2108193,2112481,2112577,0,2098305,2108321,2108289,2100865,2113153,2108481,2113345,0,2098209,2111137]), - new Uint32Array([2172129,6291456,2172161,6291456,2172193,6291456,2172225,6291456,2172257,6291456,2172289,6291456,2172321,6291456,2172353,6291456]), - new Uint32Array([2214753,6291456,2214785,6291456,6291456,2214817,2214849,2214881,2214913,2214945,2214977,2215009,2215041,2215073,2194401,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([0,0,0,0,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([10610305,10610337,10575617,2221761,10610401,10610433,10502177,0,10610465,10610497,10610529,10610561,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,0,0,0,0,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2187105,2187137,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2199393,2199425,2199457,2199489,2199521,2199553,2199585,2199617,2199649,2199681,2199713,2199745,2199777,2199809,2199841,0]), - new Uint32Array([2217249,2217281,2217313,2217345,2217377,2217409,2217441,2217473,2215617,2217505,2217537,2217569,2214753,2217601,2217633,2217665]), - new Uint32Array([2170273,2170305,6291456,2170337,2170369,6291456,2170401,2170433,2170465,6291456,6291456,6291456,2170497,2170529,6291456,2170561]), - new Uint32Array([2188673,6291456,2188705,2188737,2188769,6291456,6291456,2188801,6291456,2188833,6291456,2188865,6291456,2180929,2181505,2180897]), - new Uint32Array([10489988,10490116,10490244,10490372,10490500,10490628,10490756,10490884,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147393,2147457,2147521,2147585,2147649,2147713,2147777,2147841]), - new Uint32Array([23068672,23068672,0,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), - new Uint32Array([2241153,2241185,2241217,2215809,2241250,2241313,2241345,2241377,2217921,2241377,2241409,2215873,2241441,2241473,2241505,2241537]), - new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2220417,2220417,2220449,2220449,2220481,2220481,2220513,2220513,2220545,2220545,2220577,2220577,2220609,2220609,2220641,2220641]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2144002,0,6291456,6291456,0,0,6291456,6291456,6291456]), - new Uint32Array([2167105,2167137,2167169,2167201,2167233,2167265,2167297,2167329,2167361,2167393,2167425,2167457,2167489,2167521,2167553,2167585]), - new Uint32Array([10575521,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), - new Uint32Array([2234146,2234210,2234274,2234338,2234402,2234466,2234530,2234594,2234658,2234722,2234786,2234850,2234914,2234978,2235042,2235106]), - new Uint32Array([0,0,0,0,0,0,0,2180577,0,0,0,0,0,2180609,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456]), - new Uint32Array([2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2242529,2242561,2242593,2242625,2242657,2242689,2242721,2242753,2207937,2218177,2242785,2242817,2242849,2242882,2242945,2242977]), - new Uint32Array([2118049,2105345,2118241,2105441,2118433,2118529,2118625,2118721,2118817,2200257,2200289,2191809,2200321,2200353,2200385,2200417]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), - new Uint32Array([2185505,6291456,2185537,6291456,2185569,6291456,2185601,6291456,2185633,6291456,2185665,6291456,2185697,6291456,2185729,6291456]), - new Uint32Array([2231970,2232034,2232098,2232162,2232226,2232290,2232354,2232418,2232482,2232546,2232610,2232674,2232738,2232802,2232866,2232930]), - new Uint32Array([2218625,2246402,2246466,2246530,2246594,2246657,2246689,2246689,2218657,2219681,2246721,2246753,2246785,2246818,2246881,2208481]), - new Uint32Array([2197025,2197057,2197089,2197121,2197153,2197185,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2219137,2216961,2219169,2219201,2219233,2219265,2219297,2217025,2215041,2219329,2217057,2219361,2217089,2219393,2197153,2219426]), - new Uint32Array([23068672,23068672,23068672,0,0,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), - new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713]), - new Uint32Array([2243522,2243585,2243617,2243649,2243681,2210113,2243713,2243746,2243810,2243874,2243937,2243970,2244033,2244065,2244097,2244129]), - new Uint32Array([2178017,6291456,2178049,6291456,2178081,6291456,2178113,6291456,2178145,6291456,2178177,6291456,2178209,6291456,2178241,6291456]), - new Uint32Array([10553858,2165314,10518722,6291456,10518818,0,10518914,2130690,10519010,2130786,10519106,2130882,10519202,2165378,10554050,2165506]), - new Uint32Array([0,0,2135491,2135587,2135683,2135779,2135875,2135971,2135971,2136067,2136163,2136259,2136355,2136355,2136451,2136547]), - new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2220033,2220033,2220065,2220065,2220065,2220065,2220097,2220097,2220097,2220097,2220129,2220129,2220129,2220129,2220161,2220161]), - new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2100897,2100898,2100899,2150018,2100865,2100866,2100867,2100868,2150082,2108481,2109858,2109859,2105569,2105505,2098241,2105601]), - new Uint32Array([2097217,2097505,2097505,2097505,2097505,2165570,2165570,2165634,2165634,2165698,2165698,2097858,2097858,0,0,2097152]), - new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672]), - new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([10503843,10503939,10504035,10504131,10504227,10504323,10504419,10504515,10504611,10504707,10504803,10504899,10504995,10491140,10491268,0]), - new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,2235297,2220769,2235329,2235361]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2222401,2222433,2222465,10531394,2222497,2222529,2222561,0,2222593,2222625,2222657,2222689,2222721,2222753,2222785,0]), - new Uint32Array([2184481,6291456,2184513,6291456,2184545,6291456,2184577,6291456,2184609,6291456,2184641,6291456,2184673,6291456,2184705,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2105570,2156034,2126947,2156098,2153666,2127043,2127139,2156162,0,2127235,2156226,2156290,2156354,2156418,2127331,2127427]), - new Uint32Array([2215905,2207041,2153185,2241569,2241601,2241633,2241665,2241697,2241730,2241793,2241825,2241857,2241889,2241921,2241954,2242017]), - new Uint32Array([2203777,6291456,2203809,6291456,2203841,6291456,2203873,6291456,2203905,6291456,2173121,2180993,2181249,2203937,2181313,0]), - new Uint32Array([2168577,6291456,2168609,6291456,2168641,6291456,2168673,6291456,2168705,6291456,2168737,6291456,2168769,6291456,2168801,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,0,0]), - new Uint32Array([2210113,2195521,2210145,2210177,2210209,2210241,2210273,2210305,2210337,2210369,2210401,2210433,2210465,2210497,2210529,2210561]), - new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), - new Uint32Array([2228706,2228770,2228834,2228898,2228962,2229026,2229090,2229154,2229218,2229282,2229346,2229410,2229474,2229538,2229602,2229666]), - new Uint32Array([23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,18874368,18874368,18874368,0,0]), - new Uint32Array([2133089,2133281,2133281,2133281,2133281,2160577,2160577,2160577,2160577,2097441,2097441,2097441,2097441,2133857,2133857,2133857]), - new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089]), - new Uint32Array([2178529,6291456,2178561,6291456,2178593,6291456,2178625,6291456,2178657,6291456,2178689,6291456,2178721,6291456,2178753,6291456]), - new Uint32Array([2221025,2221025,2221057,2221057,2159329,2159329,2159329,2159329,2097217,2097217,2158914,2158914,2158978,2158978,2159042,2159042]), - new Uint32Array([2208161,2208193,2208225,2208257,2194433,2208289,2208321,2208353,2208385,2208417,2208449,2208481,2208513,2208545,2208577,2208609]), - new Uint32Array([2169217,6291456,2169249,6291456,2169281,6291456,2169313,6291456,2169345,6291456,2169377,6291456,2169409,6291456,2169441,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456]), - new Uint32Array([2133187,2133283,2133283,2133379,2133475,2133571,2133667,2133667,2133763,2133859,2133955,2134051,2134147,2134147,2134243,2134339]), - new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,0]), - new Uint32Array([2193089,2193121,2193153,2193185,2117665,2117569,2193217,2193249,2193281,2193313,2193345,2193377,2193409,2193441,2193473,2193505]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), - new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2184225,6291456,2184257,6291456,2184289,6291456,2184321,6291456,2184353,6291456,2184385,6291456,2184417,6291456,2184449,6291456]), - new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2100833,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2200801,2200833,2200865,0]), - new Uint32Array([23068672,23068672,23068672,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), - new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2181153,2105505,2181185,2167617,2180993]), - new Uint32Array([2160002,2160066,2160130,2160194,2160258,2132066,2131010,2131106,2106018,2131618,2160322,2131298,2132034,2131938,2137410,2132226]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,6291456]), - new Uint32Array([2183617,6291456,2183649,6291456,2183681,6291456,2183713,6291456,2183745,6291456,2183777,6291456,2183809,6291456,2183841,6291456]), - new Uint32Array([0,6291456,6291456,0,6291456,0,0,6291456,6291456,0,6291456,0,0,6291456,0,0]), - new Uint32Array([2250977,2251009,2251041,2251073,2195009,2251106,2251169,2251201,2251233,2251265,2251297,2251330,2251394,2251457,2251489,2251521]), - new Uint32Array([2205729,2205761,2205793,2205825,2205857,2205889,2205921,2205953,2205985,2206017,2206049,2206081,2206113,2206145,2206177,2206209]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2143170,2168993,6291456,2169025,6291456,2169057,6291456,2169089,6291456,2143234,2169121,6291456,2169153,6291456,2169185,6291456]), - new Uint32Array([23068672,23068672,2190689,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2248706,2248769,2248801,2248833,2248865,2248897,2248929,2248962,2249026,2249090,2249154,2240705,2249217,2249249,2249281,2249313]), - new Uint32Array([10485857,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10495394,6291456,2098209,6291456,6291456,2097152,6291456,10531394]), - new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,0]), - new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), - new Uint32Array([6291456,2186977,6291456,6291456,6291456,6291456,6291456,10537858,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2209601,2209633,2209665,2209697,2209729,2209761,2209793,2209825,2209857,2209889,2209921,2209953,2209985,2210017,2210049,2210081]), - new Uint32Array([10501539,10501635,10501731,10501827,10501923,10502019,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), - new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([6291456,6291456,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2194561,2194593,2194625,2119777,2119873,2194657,2194689,2194721,2194753,2194785,2194817,2194849,2194881,2194913,2194945,2194977]), - new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569]), - new Uint32Array([2222818,2222882,2222946,2223010,2223074,2223138,2223202,2223266,2223330,2223394,2223458,2223522,2223586,2223650,2223714,2223778]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672]), - new Uint32Array([0,2179553,2179585,2179617,2179649,2144001,2179681,2179713,2179745,2179777,2179809,2156705,2179841,2156833,2179873,2179905]), - new Uint32Array([6291456,23068672,6291456,2145602,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,6291456,0,0]), - new Uint32Array([2196513,2196545,2196577,2196609,2196641,2196673,2196705,2196737,2196769,2196801,2196833,2196865,2196897,2196929,2196961,2196993]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2177281,6291456,2177313,6291456,2177345,6291456,2177377,6291456,2177409,6291456,2177441,6291456,2177473,6291456,2177505,6291456]), - new Uint32Array([2187137,2221473,2221505,2221537,2221569,6291456,6291456,10610209,10610241,10537986,10537986,10537986,10537986,10609857,10609857,10609857]), - new Uint32Array([2243009,2243041,2216033,2243074,2243137,2243169,2243201,2219617,2243233,2243265,2243297,2243329,2243362,2243425,2243457,2243489]), - new Uint32Array([10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,2097152,4194304,4194304,0,0]), - new Uint32Array([2143042,6291456,2143106,2143106,2168833,6291456,2168865,6291456,6291456,2168897,6291456,2168929,6291456,2168961,6291456,2143170]), - new Uint32Array([6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2204193,2204225,2204257,2204289,2204321,2204353,2204385,2204417,2204449,2204481,2204513,2204545,2204577,2204609,2204641,2204673]), - new Uint32Array([2202753,6291456,2202785,6291456,2202817,6291456,2202849,6291456,2202881,6291456,2202913,6291456,2202945,6291456,2202977,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321]), - new Uint32Array([2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842,2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842]), - new Uint32Array([2253313,2253346,2253409,2253441,2253473,2253505,2253537,2253569,2253601,2253634,2219393,2253697,2253729,2253761,2253793,2253825]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([2162562,2162626,2131362,2162690,2159938,2160002,2162754,2162818,2160130,2162882,2160194,2160258,2160834,2160898,2161026,2161090]), - new Uint32Array([2175361,2175393,2175425,2175457,2175489,2175521,2175553,2175585,2175617,2175649,2175681,2175713,2175745,2175777,2175809,2175841]), - new Uint32Array([2253858,2253921,2253954,2254018,2254082,2196737,2254145,2196865,2254177,2254209,2254241,2254273,2197025,2254306,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2202113,2204129,2188705,2204161]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953]), - new Uint32Array([2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209]), - new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,0,2108417,0,2111713,2100897,2111905]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0]), - new Uint32Array([2175425,2175489,2175809,2175905,2175937,2175937,2176193,2176417,2180865,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,2143298,2143298,2143298,2143362,2143362,2143362,2143426,2143426,2143426,2171105,6291456,2171137]), - new Uint32Array([2120162,2120258,2151618,2151682,2151746,2151810,2151874,2151938,2152002,2120035,2120131,2120227,2152066,2120323,2152130,2120419]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2195361,2142433,2236065,2236097,2236129,2236161,2118241,2117473,2236193,2236225,2236257,2236289,0,0,0,0]), - new Uint32Array([2189281,6291456,2189313,6291456,2189345,6291456,2189377,6291456,2189409,6291456,2189441,6291456,2189473,6291456,2189505,6291456]), - new Uint32Array([6291456,6291456,2145922,6291456,6291456,6291456,6291456,2145986,6291456,6291456,6291456,6291456,2146050,6291456,6291456,6291456]), - new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10502113,10562017,10610401,10502177,10610433,10538049]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,2186401,0,2186433,0,2186465,0,2186497]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,23068672,23068672]), - new Uint32Array([0,0,2198241,2198273,2198305,2198337,2198369,2198401,0,0,2198433,2198465,2198497,0,0,0]), - new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,0,23068672,23068672,23068672,23068672,23068672,23068672,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), - new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,2133281,2097505,2105889,0,2097697,2135777,2097633,2097441]), - new Uint32Array([2197889,2197921,2197953,2197985,2198017,2198049,2198081,2198113,2198145,2198177,2198209,2198241,2198273,2198305,2198337,2198369]), - new Uint32Array([2132514,2132610,2160386,2133090,2133186,2160450,2160514,2133282,2160578,2133570,2106178,2160642,2133858,2160706,2160770,2134146]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,23068672,23068672,6291456,23068672,23068672,6291456,23068672,0,0,0,0,0,0,0,0]), - new Uint32Array([2184737,6291456,2184769,6291456,2184801,6291456,2184833,6291456,2184865,6291456,2184897,6291456,2184929,6291456,2184961,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,6291456]), - new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,0,0]), - new Uint32Array([6291456,6291456,6291456,2186753,6291456,6291456,6291456,6291456,2186785,2186817,2186849,2173569,2186881,10496355,10495395,10575521]), - new Uint32Array([0,0,2097729,0,0,0,0,2106017,0,2097505,0,2097185,0,2135777,2097633,2097441]), - new Uint32Array([2189537,6291456,2189569,6291456,2189601,6291456,2189633,6291456,2189665,6291456,2189697,6291456,2189729,6291456,2189761,6291456]), - new Uint32Array([2202497,6291456,2202529,6291456,2202561,6291456,2202593,6291456,2202625,6291456,2202657,6291456,2202689,6291456,2202721,6291456]), - new Uint32Array([2245217,2218369,2245249,2245282,2245345,2245377,2245410,2245474,2245537,2245569,2245601,2245633,2245665,2245665,2245697,2245729]), - new Uint32Array([6291456,0,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,23068672,6291456,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), - new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2097281,2105921,2097729,2106081,2097377,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), - new Uint32Array([2176641,6291456,2176673,6291456,2176705,6291456,2176737,6291456,2176769,6291456,2176801,6291456,2176833,6291456,2176865,6291456]), - new Uint32Array([2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2174369,2174369,0,0,2100833,2100737]), - new Uint32Array([2116513,2190817,2190849,2190881,2190913,2190945,2116609,2190977,2191009,2191041,2191073,2117185,2191105,2191137,2191169,2191201]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456]), - new Uint32Array([0,0,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), - new Uint32Array([2167617,2167649,2167681,2167713,2167745,2167777,2167809,6291456,2167841,2167873,2167905,2167937,2167969,2168001,2168033,4240130]), - new Uint32Array([2165122,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122,2134562,2132162,2132834,2136866]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2186209,2186241,2186273,2186305,2186337,2186369,0,0]), - new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,14680064,14680064,14680064,14680064,14680064]), - new Uint32Array([0,0,23068672,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), - new Uint32Array([0,10537921,10610689,10610273,10610497,10610529,10610305,10610721,10489601,10489697,10610337,10575617,10554529,2221761,2197217,10496577]), - new Uint32Array([2105473,2105569,2105601,2112289,0,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), - new Uint32Array([2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481]), - new Uint32Array([2125346,2153410,2153474,2127394,2153538,2153602,2153666,2153730,2105507,2105476,2153794,2153858,2153922,2153986,2154050,2105794]), - new Uint32Array([2200449,2119681,2200481,2153313,2199873,2199905,2199937,2200513,2200545,2200577,2200609,2119105,2119201,2119297,2119393,2119489]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2175777,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2222273,2197217,2221473,2221505,2221089,2222305,2200865,2099681,2104481,2222337,2099905,2120737,2222369,2103713,2100225,2098785]), - new Uint32Array([2201377,6291456,2201409,6291456,2201441,6291456,2201473,6291456,2201505,6291456,2201537,6291456,2201569,6291456,6291456,23068672]), - new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), - new Uint32Array([2200897,6291456,2200929,6291456,2200961,6291456,2200993,6291456,2201025,6291456,2180865,6291456,2201057,6291456,2201089,6291456]), - new Uint32Array([0,0,0,0,0,23068672,23068672,0,6291456,6291456,6291456,0,0,0,0,0]), - new Uint32Array([2161154,2161410,2138658,2161474,2161538,2097666,2097186,2097474,2162946,2132450,2163010,2163074,2136162,2163138,2161666,2161730]), - new Uint32Array([2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953]), - new Uint32Array([0,0,0,0,0,0,23068672,23068672,0,0,0,0,2145410,2145474,0,6291456]), - new Uint32Array([2244161,2216065,2212769,2244193,2244225,2244257,2244290,2244353,2244385,2244417,2244449,2218273,2244481,2244514,2244577,2244609]), - new Uint32Array([2125730,2125699,2125795,2125891,2125987,2154114,2154178,2154242,2154306,2154370,2154434,2154498,2126082,2126178,2126274,2126083]), - new Uint32Array([2237665,2237697,2237697,2237697,2237730,2237793,2237825,2237857,2237890,2237953,2237985,2238017,2238049,2238081,2238113,2238145]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150146,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), - new Uint32Array([2214369,2238593,2238625,2238657,2238689,2238721,2238753,2238785,2238817,2238850,2238913,2238945,2238977,2235457,2239009,2239041]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([2252066,2252130,2252193,2252225,2252257,2252290,2252353,2252385,2252417,2252449,2252481,2252513,2252545,2252578,2252641,2252673]), - new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,2197857]), - new Uint32Array([2224866,2224930,2224994,2225058,2225122,2225186,2225250,2225314,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2219490,2219554,2219617,2219649,2219681,2219714,2219778,2219842,2219905,2219937,0,0,0,0,0,0]), - new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), - new Uint32Array([2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), - new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665]), - new Uint32Array([2220161,2220161,2220193,2220193,2220193,2220193,2220225,2220225,2220225,2220225,2220257,2220257,2220257,2220257,2220289,2220289]), - new Uint32Array([2192673,2192705,2192737,2192769,2192801,2192833,2192865,2118049,2192897,2117473,2117761,2192929,2192961,2192993,2193025,2193057]), - new Uint32Array([2179297,6291456,2179329,6291456,2179361,6291456,2179393,6291456,2179425,6291456,2179457,6291456,2179489,6291456,2179521,6291456]), - new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2235745,2235777,2193633,2235809,2235841,2235873,2235905,2235937,2235969,2116513,2116705,2236001,2200513,2199905,2200545,2236033]), - new Uint32Array([2113153,2108481,2113345,2113441,2232993,2233025,0,0,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761]), - new Uint32Array([2170593,6291456,2170625,6291456,2170657,6291456,2170689,2170721,6291456,2170753,6291456,6291456,2170785,6291456,2170817,2170849]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2166786,2166850,0,0,0,0]), - new Uint32Array([23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), - new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,0]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2134562,2132162,2132834,2136866,2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058]), - new Uint32Array([6291456,6291456,2098337,2101441,10531458,2153473,6291456,6291456,10531522,2100737,2108193,6291456,2106499,2106595,2106691,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2233122,2233186,2233250,2233314,2233378,2233442,2233506,2233570,2233634,2233698,2233762,2233826,2233890,2233954,2234018,2234082]), - new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2205217,2205249,2205281,2205313,2205345,2205377,2205409,2205441,2205473,2205505,2205537,2205569,2205601,2205633,2205665,2205697]), - new Uint32Array([6291456,0,6291456,0,0,0,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), - new Uint32Array([2173601,2173761,2174081,2173569,2174241,2174113,2173953,6291456,2174305,6291456,2174337,6291456,2174369,6291456,2174401,6291456]), - new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), - new Uint32Array([2152450,2152514,2099653,2104452,2099813,2122243,2099973,2152578,2122339,2122435,2122531,2122627,2122723,2104580,2122819,2152642]), - new Uint32Array([2236385,2236417,2236449,2236482,2236545,2215425,2236577,2236609,2236641,2236673,2215457,2236705,2236737,2236770,2215489,2236833]), - new Uint32Array([2163394,2159746,2163458,2131362,2163522,2160130,2163778,2132226,2163842,2132898,2163906,2161410,2138658,2097666,2136162,2163650]), - new Uint32Array([2218721,2246913,2246946,2216385,2247010,2247074,2215009,2247137,2247169,2216481,2247201,2247233,2247266,2247330,2247330,0]), - new Uint32Array([2129730,2129762,2129858,2129731,2129827,2156482,2156482,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0,0,0,0,6291456,0,0]), - new Uint32Array([2203969,2204001,2181377,2204033,2204065,6291456,2204097,6291456,0,0,0,0,0,0,0,0]), - new Uint32Array([2169473,6291456,2169505,6291456,2169537,6291456,2169569,6291456,2169601,6291456,2169633,6291456,2169665,6291456,2169697,6291456]), - new Uint32Array([2141542,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2220801,2220801,2220801,2220801,2220833,2220833,2220865,2220865,2220865,2220865,2220897,2220897,2220897,2220897,2139873,2139873]), - new Uint32Array([0,0,0,0,0,23068672,23068672,0,0,0,0,0,0,0,6291456,0]), - new Uint32Array([2214849,2218433,2218465,2218497,2218529,2218561,2214881,2218593,2218625,2218657,2218689,2218721,2218753,2216545,2218785,2218817]), - new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,6291456]), - new Uint32Array([2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058,2165122,2132802,2132706,2164866]), - new Uint32Array([2207649,2207681,2207713,2207745,2207777,2207809,2207841,2207873,2207905,2207937,2207969,2208001,2208033,2208065,2208097,2208129]), - new Uint32Array([2123683,2105092,2152706,2123779,2105220,2152770,2100453,2098755,2123906,2124002,2124098,2124194,2124290,2124386,2124482,2124578]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,0,0,0,0,0,0,0,10485857]), - new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([10508163,10508259,10508355,10508451,2200129,2200161,2192737,2200193,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2203553,6291456,2203585,6291456,6291456,6291456,2203617,6291456,2203649,6291456,2203681,6291456,2203713,6291456,2203745,6291456]), - new Uint32Array([18884449,18884065,23068672,18884417,18884034,18921185,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18874368]), - new Uint32Array([2247393,2247426,2247489,2247521,2247553,2247586,2247649,2247681,2247713,2247745,2247777,2247810,2247873,2247905,2247937,2247969]), - new Uint32Array([6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), - new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,2160577,2133857,2235297,0,2235329,0]), - new Uint32Array([2182593,6291456,2182625,6291456,2182657,6291456,2182689,6291456,2182721,6291456,2182753,6291456,2182785,6291456,2182817,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102402,2102403,6291456,2110050]), - new Uint32Array([2149890,2108323,2149954,6291456,2113441,6291456,2149057,6291456,2113441,6291456,2105473,2167265,2111137,2105505,6291456,2108353]), - new Uint32Array([2219105,2219137,2195233,2251554,2251617,2251649,2251681,2251713,2251746,2251810,2251873,2251905,2251937,2251970,2252033,2219169]), - new Uint32Array([2203009,6291456,2203041,6291456,2203073,6291456,2203105,6291456,2203137,6291456,2203169,6291456,2203201,6291456,2203233,6291456]), - new Uint32Array([2128195,2128291,2128387,2128483,2128579,2128675,2128771,2128867,2128963,2129059,2129155,2129251,2129347,2129443,2129539,2129635]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2140964,2141156,2140966,2141158,2141350]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2225378,2225442,2225506,2225570,2225634,2225698,2225762,2225826,2225890,2225954,2226018,2226082,2226146,2226210,2226274,2226338]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417]), - new Uint32Array([2108353,2108417,0,2105601,2108193,2157121,2157313,2157377,2157441,2100897,6291456,2108419,2173953,2173633,2173633,2173953]), - new Uint32Array([2111713,2173121,2111905,2098177,2173153,2173185,2173217,2113153,2113345,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2190753]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,2197249,6291456,2117377,2197281,2197313,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,6291456,6291456,6291456]), - new Uint32Array([2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), - new Uint32Array([0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,23068672]), - new Uint32Array([2173281,6291456,2173313,6291456,2173345,6291456,2173377,6291456,0,0,10532546,6291456,6291456,6291456,10562017,2173441]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), - new Uint32Array([23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2159426,2159490,2159554,2159362,2159618,2159682,2139522,2136450,2159746,2159810,2159874,2130978,2131074,2131266,2131362,2159938]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2203233,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2203265,6291456,2203297,6291456,2203329,2203361,6291456]), - new Uint32Array([6291456,6291456,2148418,2148482,2148546,0,6291456,2148610,2186529,2186561,2148417,2148545,2148482,10495778,2143969,10495778]), - new Uint32Array([2134146,2139426,2160962,2134242,2161218,2161282,2161346,2161410,2138658,2134722,2134434,2134818,2097666,2097346,2097698,2105986]), - new Uint32Array([2198881,2198913,2198945,2198977,2199009,2199041,2199073,2199105,2199137,2199169,2199201,2199233,2199265,2199297,2199329,2199361]), - new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), - new Uint32Array([10610561,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), - new Uint32Array([2183873,6291456,2183905,6291456,2183937,6291456,2183969,6291456,2184001,6291456,2184033,6291456,2184065,6291456,2184097,6291456]), - new Uint32Array([2244642,2244706,2244769,2244801,2218305,2244833,2244865,2244897,2244929,2244961,2244993,2245026,2245089,2245122,2245185,0]), - new Uint32Array([6291456,6291456,2116513,2116609,2116705,2116801,2199873,2199905,2199937,2199969,2190913,2200001,2200033,2200065,2200097,2191009]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2180673,2180705,2180737,2180769,2180801,2180833,0,0]), - new Uint32Array([2098081,2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150402]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,2145666,2145730,6291456,6291456]), - new Uint32Array([2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665]), - new Uint32Array([2187073,6291456,6291456,6291456,6291456,2098241,2098241,2108353,2100897,2111905,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102404,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2100612,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10485857]), - new Uint32Array([2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), - new Uint32Array([2217697,2217729,2217761,2217793,2217825,2217857,2217889,2217921,2217953,2215873,2217985,2215905,2218017,2218049,2218081,2218113]), - new Uint32Array([2211233,2218849,2216673,2218881,2218913,2218945,2218977,2219009,2216833,2219041,2215137,2219073,2216865,2209505,2219105,2216897]), - new Uint32Array([2240097,2240129,2240161,2240193,2240225,2240257,2240289,2240321,2240353,2240386,2240449,2240481,2240513,2240545,2207905,2240578]), - new Uint32Array([6291456,6291456,2202273,6291456,2202305,6291456,2202337,6291456,2202369,6291456,2202401,6291456,2202433,6291456,2202465,6291456]), - new Uint32Array([0,23068672,23068672,18923394,23068672,18923458,18923522,18884099,18923586,18884195,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2201121,6291456,2201153,6291456,2201185,6291456,2201217,6291456,2201249,6291456,2201281,6291456,2201313,6291456,2201345,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), - new Uint32Array([2211041,2211073,2211105,2211137,2211169,2211201,2211233,2211265,2211297,2211329,2211361,2211393,2211425,2211457,2211489,2211521]), - new Uint32Array([2181825,6291456,2181857,6291456,2181889,6291456,2181921,6291456,2181953,6291456,2181985,6291456,2182017,6291456,2182049,6291456]), - new Uint32Array([2162337,2097633,2097633,2097633,2097633,2132705,2132705,2132705,2132705,2097153,2097153,2097153,2097153,2133089,2133089,2133089]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,2148545,6291456,2173473,6291456,2148865,6291456,2173505,6291456,2173537,6291456,2173569,6291456,2149121,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,0,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), - new Uint32Array([2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2207137,2207169,2207201,2207233,2207265,2207297,2207329,2207361,2207393,2207425,2207457,2207489,2207521,2207553,2207585,2207617]), - new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,23068672,23068672,0,0,0,0,0,0]), - new Uint32Array([2198401,2198433,2198465,2198497,0,2198529,2198561,2198593,2198625,2198657,2198689,2198721,2198753,2198785,2198817,2198849]), - new Uint32Array([2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), - new Uint32Array([2216385,2118721,2216417,2216449,2216481,2216513,2216545,2211233,2216577,2216609,2216641,2216673,2216705,2216737,2216737,2216769]), - new Uint32Array([2216801,2216833,2216865,2216897,2216929,2216961,2216993,2215169,2217025,2217057,2217089,2217121,2217154,2217217,0,0]), - new Uint32Array([2210593,2191809,2210625,2210657,2210689,2210721,2210753,2210785,2210817,2210849,2191297,2210881,2210913,2210945,2210977,2211009]), - new Uint32Array([0,0,2105825,0,0,2111905,2105473,0,0,2112289,2108193,2112481,2112577,0,2098305,2108321]), - new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,2097153,2134241,0,2132705,0,0,2131297,0,2133089,0,2133857,0,2220769,0,2235361]), - new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,6291456,6291456,14680064]), - new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), - new Uint32Array([2171873,6291456,2171905,6291456,2171937,6291456,2171969,6291456,2172001,6291456,2172033,6291456,2172065,6291456,2172097,6291456]), - new Uint32Array([2220929,2220929,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2133857,2134145,2134145,2134145,2134145,2134241,2134241,2134241,2134241,2105889,2105889,2105889,2105889,2097185,2097185,2097185]), - new Uint32Array([2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,10499619,10499715,10499811,10499907]), - new Uint32Array([0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,23068672,23068672]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2144322,2144386,2144450,2144514,2144578,2144642,2144706,2144770]), - new Uint32Array([23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456]), - new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0,0,2111905,2105473,2105569]), - new Uint32Array([2236321,2236353,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2152194,2121283,2103684,2103812,2097986,2098533,2097990,2098693,2098595,2098853,2099013,2103940,2121379,2121475,2121571,2104068]), - new Uint32Array([2206241,2206273,2206305,2206337,2206369,2206401,2206433,2206465,2206497,2206529,2206561,2206593,2206625,2206657,2206689,2206721]), - new Uint32Array([6291456,6291456,6291456,6291456,16777216,16777216,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,10538818,10538882,6291456,6291456,2150338]), - new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2214369,2214401,2214433,2214465,2214497,2214529,2214561,2214593,2194977,2214625,2195073,2214657,2214689,2214721,6291456,6291456]), - new Uint32Array([2097152,2097152,2097152,2097152,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2182081,6291456,2182113,6291456,2182145,6291456,2182177,6291456,2182209,6291456,2182241,6291456,2182273,6291456,2182305,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146881,2146945,2147009,2147073,2147137,2147201,2147265,2147329]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672]), - new Uint32Array([0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2122915,2123011,2123107,2104708,2123203,2123299,2123395,2100133,2104836,2100290,2100293,2104962,2104964,2098052,2123491,2123587]), - new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), - new Uint32Array([6291456,2171169,6291456,2171201,6291456,2171233,6291456,2171265,6291456,2171297,6291456,2171329,6291456,6291456,2171361,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,0,2148994,2149058,2149122,0,6291456,2149186,2186945,2173537,2148993,2149121,2149058,10531458,10496066,0]), - new Uint32Array([2195009,2195041,2195073,2195105,2195137,2195169,2195201,2195233,2195265,2195297,2195329,2195361,2195393,2195425,2195457,2195489]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,0,0,6291456,6291456]), - new Uint32Array([2182849,6291456,2182881,6291456,2182913,6291456,2182945,6291456,2182977,6291456,2183009,6291456,2183041,6291456,2183073,6291456]), - new Uint32Array([2211553,2210081,2211585,2211617,2211649,2211681,2211713,2211745,2211777,2211809,2209569,2211841,2211873,2211905,2211937,2211969]), - new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2166594,2127298,2166658,2142978,2141827,2166722]), - new Uint32Array([2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2185761,2185793,2185825,2185857,2185889,2185921,0,0]), - new Uint32Array([6291456,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456]), - new Uint32Array([0,0,0,2220961,2220961,2220961,2220961,2144193,2144193,2159201,2159201,2159265,2159265,2144194,2220993,2220993]), - new Uint32Array([2192641,2235393,2235425,2152257,2116609,2235457,2235489,2200065,2235521,2235553,2235585,2212449,2235617,2235649,2235681,2235713]), - new Uint32Array([2194049,2194081,2194113,2194145,2194177,2194209,2194241,2194273,2194305,2194337,2194369,2194401,2194433,2194465,2194497,2194529]), - new Uint32Array([2196673,2208641,2208673,2208705,2208737,2208769,2208801,2208833,2208865,2208897,2208929,2208961,2208993,2209025,2209057,2209089]), - new Uint32Array([2191681,2191713,2191745,2191777,2153281,2191809,2191841,2191873,2191905,2191937,2191969,2192001,2192033,2192065,2192097,2192129]), - new Uint32Array([2230946,2231010,2231074,2231138,2231202,2231266,2231330,2231394,2231458,2231522,2231586,2231650,2231714,2231778,2231842,2231906]), - new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2185953,2185985,2186017,2186049,2186081,2186113,2186145,2186177]), - new Uint32Array([2139811,2139907,2097284,2105860,2105988,2106116,2106244,2097444,2097604,2097155,10485778,10486344,2106372,6291456,0,0]), - new Uint32Array([2110051,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2172385,6291456,2172417,6291456,2172449,6291456,2172481,6291456,2172513,6291456,2172545,6291456,2172577,6291456,2172609,6291456]), - new Uint32Array([0,0,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2249345,2249377,2249409,2249441,2249473,2249505,2249537,2249570,2210209,2249633,2249665,2249697,2249729,2249761,2249793,2216769]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456]), - new Uint32Array([2187169,2187201,2187233,2187265,2187297,2187329,2187361,2187393,2187425,2187457,2187489,2187521,2187553,2187585,2187617,2187649]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([0,0,0,6291456,6291456,0,0,0,6291456,6291456,6291456,0,0,0,6291456,6291456]), - new Uint32Array([2182337,6291456,2182369,6291456,2182401,6291456,2182433,6291456,2182465,6291456,2182497,6291456,2182529,6291456,2182561,6291456]), - new Uint32Array([2138179,2138275,2138371,2138467,2134243,2134435,2138563,2138659,2138755,2138851,2138947,2139043,2138947,2138755,2139139,2139235]), - new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), - new Uint32Array([0,0,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2250498,2250562,2250625,2250657,2208321,2250689,2250721,2250753,2250785,2250817,2250849,2218945,2250881,2250913,2250945,0]), - new Uint32Array([2170369,2105569,2098305,2108481,2173249,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), - new Uint32Array([2100897,2111905,2105473,2105569,2105601,0,2108193,0,0,0,2098305,2108321,2108289,2100865,2113153,2108481]), - new Uint32Array([2100897,2100897,2105569,2105569,6291456,2112289,2149826,6291456,6291456,2112481,2112577,2098177,2098177,2098177,6291456,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456,6291456]), - new Uint32Array([6291456,2169953,2169985,6291456,2170017,6291456,2170049,2170081,6291456,2170113,2170145,2170177,6291456,6291456,2170209,2170241]), - new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2220641,2220641,2220673,2220673,2220673,2220673,2220705,2220705,2220705,2220705,2220737,2220737,2220737,2220737,2220769,2220769]), - new Uint32Array([2127650,2127746,2127842,2127938,2128034,2128130,2128226,2128322,2128418,2127523,2127619,2127715,2127811,2127907,2128003,2128099]), - new Uint32Array([2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177]), - new Uint32Array([0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([2204705,2204737,2204769,2204801,2204833,2204865,2204897,2204929,2204961,2204993,2205025,2205057,2205089,2205121,2205153,2205185]), - new Uint32Array([2176385,6291456,2176417,6291456,2176449,6291456,2176481,6291456,2176513,6291456,2176545,6291456,2176577,6291456,2176609,6291456]), - new Uint32Array([2195521,2195553,2195585,2195617,2195649,2195681,2117857,2195713,2195745,2195777,2195809,2195841,2195873,2195905,2195937,2195969]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456]), - new Uint32Array([2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113]), - new Uint32Array([2131586,2132450,2135970,2135778,2161602,2136162,2163650,2161794,2135586,2163714,2137186,2131810,2160290,2135170,2097506,2159554]), - new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,0,0,0,0]), - new Uint32Array([2116513,2116609,2116705,2116801,2116897,2116993,2117089,2117185,2117281,2117377,2117473,2117569,2117665,2117761,2117857,2117953]), - new Uint32Array([2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100802,2101154,2101282,2101410,2101538,2101666,2101794]), - new Uint32Array([2100289,2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2098977,2150241,2150305]), - new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,2109955,6291456,6291456,0,0,0,0]), - new Uint32Array([18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,0,0]), - new Uint32Array([2130979,2131075,2131075,2131171,2131267,2131363,2131459,2131555,2131651,2131651,2131747,2131843,2131939,2132035,2132131,2132227]), - new Uint32Array([0,2177793,6291456,2177825,6291456,2177857,6291456,2177889,6291456,2177921,6291456,2177953,6291456,2177985,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), - new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2113345,0,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), - new Uint32Array([2136643,2136739,2136835,2136931,2137027,2137123,2137219,2137315,2137411,2137507,2137603,2137699,2137795,2137891,2137987,2138083]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), - new Uint32Array([2174433,6291456,2174465,6291456,2174497,6291456,2174529,6291456,2174561,6291456,2174593,6291456,2174625,6291456,2174657,6291456]), - new Uint32Array([0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), - new Uint32Array([10496547,10496643,2105505,2149698,6291456,10496739,10496835,2170273,6291456,2149762,2105825,2111713,2111713,2111713,2111713,2168673]), - new Uint32Array([6291456,2143490,2143490,2143490,2171649,6291456,2171681,2171713,2171745,6291456,2171777,6291456,2171809,6291456,2171841,6291456]), - new Uint32Array([2159106,2159106,2159170,2159170,2159234,2159234,2159298,2159298,2159298,2159362,2159362,2159362,2106401,2106401,2106401,2106401]), - new Uint32Array([2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137]), - new Uint32Array([2108417,2181217,2181249,2181281,2170433,2170401,2181313,2181345,2181377,2181409,2181441,2181473,2181505,2181537,2170529,2181569]), - new Uint32Array([2218433,2245761,2245793,2245825,2245857,2245890,2245953,2245986,2209665,2246050,2246113,2246146,2246210,2246274,2246337,2246369]), - new Uint32Array([2230754,2230818,2230882,0,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2184129,6291456,2184161,6291456,2184193,6291456,6291456,6291456,6291456,6291456,2146818,2183361,6291456,6291456,2142978,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2135170,2097506,2130691,2130787,2130883,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122]), - new Uint32Array([2108515,2108611,2100740,2108707,2108803,2108899,2108995,2109091,2109187,2109283,2109379,2109475,2109571,2109667,2109763,2100738]), - new Uint32Array([2102788,2102916,2103044,2120515,2103172,2120611,2120707,2098373,2103300,2120803,2120899,2120995,2103428,2103556,2121091,2121187]), - new Uint32Array([2158082,2158146,0,2158210,2158274,0,2158338,2158402,2158466,2129922,2158530,2158594,2158658,2158722,2158786,2158850]), - new Uint32Array([10499619,10499715,10499811,10499907,10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059]), - new Uint32Array([2239585,2239618,2239681,2239713,0,2191969,2239745,2239777,2192033,2239809,2239841,2239874,2239937,2239970,2240033,2240065]), - new Uint32Array([2252705,2252738,2252801,2252833,2252865,2252897,2252930,2252994,2253057,2253089,2253121,2253154,2253217,2253250,2219361,2219361]), - new Uint32Array([2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,10538050,10538114,10538178,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([2226402,2226466,2226530,2226594,2226658,2226722,2226786,2226850,2226914,2226978,2227042,2227106,2227170,2227234,2227298,2227362]), - new Uint32Array([23068672,6291456,6291456,6291456,6291456,2144066,2144130,2144194,2144258,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,23068672,23068672]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), - new Uint32Array([2124674,2124770,2123875,2123971,2124067,2124163,2124259,2124355,2124451,2124547,2124643,2124739,2124835,2124931,2125027,2125123]), - new Uint32Array([2168065,6291456,2168097,6291456,2168129,6291456,2168161,6291456,2168193,6291456,2168225,6291456,2168257,6291456,2168289,6291456]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0]), - new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,2100610,2100611,6291456,2107842,2107843,6291456,6291456,6291456,6291456,10537922,6291456,10537986,6291456]), - new Uint32Array([2174849,2174881,2174913,2174945,2174977,2175009,2175041,2175073,2175105,2175137,2175169,2175201,2175233,2175265,2175297,2175329]), - new Uint32Array([2154562,2154626,2154690,2154754,2141858,2154818,2154882,2127298,2154946,2127298,2155010,2155074,2155138,2155202,2155266,2155202]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0]), - new Uint32Array([2200641,2150786,2150850,2150914,2150978,2151042,2106562,2151106,2150562,2151170,2151234,2151298,2151362,2151426,2151490,2151554]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456]), - new Uint32Array([2220289,2220289,2220321,2220321,2220321,2220321,2220353,2220353,2220353,2220353,2220385,2220385,2220385,2220385,2220417,2220417]), - new Uint32Array([2155330,2155394,0,2155458,2155522,2155586,2105732,0,2155650,2155714,2155778,2125314,2155842,2155906,2126274,2155970]), - new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), - new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0]), - new Uint32Array([2097729,2106017,2106017,2106017,2106017,2131297,2131297,2131297,2131297,2106081,2106081,2162049,2162049,2105953,2105953,2162337]), - new Uint32Array([2097185,2097697,2097697,2097697,2097697,2135777,2135777,2135777,2135777,2097377,2097377,2097377,2097377,2097601,2097601,2097217]), - new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), - new Uint32Array([2139331,2139427,2139523,2139043,2133571,2132611,2139619,2139715,0,0,0,0,0,0,0,0]), - new Uint32Array([2174113,2174145,2100897,2098177,2108289,2100865,2173601,2173633,2173985,2174113,2174145,6291456,6291456,6291456,6291456,6291456]), - new Uint32Array([6291456,6291456,23068672,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456]), - new Uint32Array([23068672,23068672,18923778,23068672,23068672,23068672,23068672,18923842,23068672,23068672,23068672,23068672,18923906,23068672,23068672,23068672]), - new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,0,2133857,0,0,0,0]), - new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2177537,6291456,2177569,6291456,2177601,6291456,2177633,6291456,2177665,6291456,2177697,6291456,2177729,6291456,2177761,6291456]), - new Uint32Array([2212481,2212513,2212545,2212577,2197121,2212609,2212641,2212673,2212705,2212737,2212769,2212801,2212833,2212865,2212897,2212929]), - new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,0,0,0,0,0,0,0,0]), - new Uint32Array([2098241,2108353,2170209,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,6291456,2108193,2172417,2112481,2098177]), - new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), -]; -var blockIdxes = new Uint16Array([616,616,565,147,161,411,330,2,131,131,328,454,241,408,86,86,696,113,285,350,325,301,473,214,639,232,447,64,369,598,124,672,567,223,621,154,107,86,86,86,86,86,86,505,86,68,634,86,218,218,218,218,486,218,218,513,188,608,216,86,217,463,668,85,700,360,184,86,86,86,647,402,153,10,346,718,662,260,145,298,117,1,443,342,138,54,563,86,240,572,218,70,387,86,118,460,641,602,86,86,306,218,86,692,86,86,86,86,86,162,707,86,458,26,86,218,638,86,86,86,86,86,65,449,86,86,306,183,86,58,391,667,86,157,131,131,131,131,86,433,131,406,31,218,247,86,86,693,218,581,351,86,438,295,69,462,45,126,173,650,14,295,69,97,168,187,641,78,523,390,69,108,287,664,173,219,83,295,69,108,431,426,173,694,412,115,628,52,257,398,641,118,501,121,69,579,151,423,173,620,464,121,69,382,151,476,173,27,53,121,86,594,578,226,173,86,632,130,86,96,228,268,641,622,563,86,86,21,148,650,131,131,321,43,144,343,381,531,131,131,178,20,86,399,156,375,164,541,30,60,715,198,92,118,131,131,86,86,306,407,86,280,457,196,488,358,131,131,244,86,86,143,86,86,86,86,86,667,563,86,86,86,86,86,86,86,86,86,86,86,86,86,336,363,86,86,336,86,86,380,678,67,86,86,86,678,86,86,86,512,86,307,86,708,86,86,86,86,86,528,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,563,307,86,86,86,86,86,104,450,337,86,720,86,32,450,397,86,86,86,587,218,558,708,708,293,708,86,86,86,86,86,694,205,86,8,86,86,86,86,549,86,667,697,697,679,86,458,460,86,86,650,86,708,543,86,86,86,245,86,86,86,140,218,127,708,708,458,197,131,131,131,131,500,86,86,483,251,86,306,510,515,86,722,86,86,86,65,201,86,86,483,580,470,86,86,86,368,131,131,131,694,114,110,555,86,86,123,721,163,142,713,418,86,317,675,209,218,218,218,371,545,592,629,490,603,199,46,320,525,680,310,279,388,111,42,252,593,607,235,617,410,377,50,548,135,356,17,520,189,116,392,600,349,332,482,699,690,535,119,106,451,71,152,667,131,218,218,265,671,637,492,504,533,683,269,269,658,86,86,86,86,86,86,86,86,86,491,619,86,86,6,86,86,86,86,86,86,86,86,86,86,86,229,86,86,86,86,86,86,86,86,86,86,86,86,667,86,86,171,131,118,131,656,206,234,571,89,334,670,246,311,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,534,86,86,86,86,86,86,82,86,86,86,86,86,430,86,86,86,86,86,86,86,86,86,599,86,324,86,470,69,640,264,131,626,101,174,86,86,667,233,105,73,374,394,221,204,84,28,326,86,86,471,86,86,86,109,573,86,171,200,200,200,200,218,218,86,86,86,86,460,131,131,131,86,506,86,86,86,86,86,220,404,34,614,47,442,305,25,612,338,601,648,7,344,255,131,131,51,86,312,507,563,86,86,86,86,588,86,86,86,86,86,530,511,86,458,3,435,384,556,522,230,527,86,118,86,86,717,86,137,273,79,181,484,23,93,112,655,249,417,703,370,87,98,313,684,585,155,465,596,481,695,18,416,428,61,701,706,282,643,495,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,86,86,86,171,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,650,131,422,542,420,263,24,172,86,86,86,86,86,566,86,86,132,540,395,353,494,519,19,485,284,472,131,131,131,16,714,86,211,708,86,86,86,694,698,86,86,483,704,708,218,272,86,86,120,86,159,478,86,307,247,86,86,663,597,459,627,667,86,86,277,455,39,302,86,250,86,86,86,271,99,452,306,281,329,400,200,86,86,362,549,352,646,461,323,586,86,86,4,708,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,717,86,518,86,86,650,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,125,554,480,300,613,72,333,288,561,544,604,48,719,91,169,176,590,224,76,191,29,559,560,231,537,166,477,538,256,437,131,131,469,167,40,0,685,266,441,705,239,642,475,568,640,610,299,673,517,318,385,22,202,180,179,359,424,215,90,66,521,653,467,682,453,409,479,88,131,661,35,303,15,262,666,630,712,131,131,618,659,175,218,195,347,193,227,261,150,165,709,546,294,569,710,270,413,376,524,55,242,38,419,529,170,657,3,304,122,379,278,131,651,86,67,576,458,458,131,131,86,86,86,86,86,86,86,118,309,86,86,547,86,86,86,86,667,650,664,131,131,86,86,56,131,131,131,131,131,131,131,131,86,307,86,86,86,664,238,650,86,86,717,86,118,86,86,315,86,59,86,86,574,549,131,131,340,57,436,86,86,86,86,86,86,458,708,499,691,62,86,650,86,86,694,86,86,86,319,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,86,549,694,131,131,131,131,131,131,131,131,131,77,86,86,139,86,502,86,86,86,667,595,131,131,131,86,12,86,13,86,609,131,131,131,131,86,86,86,625,86,669,86,86,182,129,86,5,694,104,86,86,86,86,131,131,86,86,386,171,86,86,86,345,86,324,86,589,86,213,36,131,131,131,131,131,86,86,86,86,104,131,131,131,141,290,80,677,86,86,86,267,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,515,86,86,33,136,669,86,711,515,86,86,550,640,86,104,708,515,86,159,372,717,86,86,444,515,86,86,663,37,86,563,460,86,390,624,702,131,131,131,131,389,59,708,86,86,341,208,708,635,295,69,108,431,508,100,190,131,131,131,131,131,131,131,131,86,86,86,649,516,660,131,131,86,86,86,218,631,708,131,131,131,131,131,131,131,131,131,131,86,86,341,575,238,514,131,131,86,86,86,218,291,708,307,131,86,86,306,367,708,131,131,131,86,378,697,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,615,253,86,86,86,292,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,104,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,69,86,341,553,549,86,307,86,86,645,275,455,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,708,131,131,131,131,131,131,86,86,86,86,86,86,667,460,86,86,86,86,86,86,86,86,86,86,86,86,717,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,104,86,667,459,131,131,131,131,131,131,86,458,225,86,86,86,516,549,11,390,405,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,460,44,218,197,711,515,131,131,131,131,664,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,118,307,104,286,591,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,681,86,86,75,185,314,582,86,358,496,474,86,104,131,86,86,86,86,146,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,171,86,640,131,131,131,131,131,131,131,131,246,503,689,339,674,81,258,415,439,128,562,366,414,246,503,689,583,222,557,316,636,665,186,355,95,670,246,503,689,339,674,557,258,415,439,186,355,95,670,246,503,689,446,644,536,652,331,532,335,440,274,421,297,570,74,425,364,425,606,552,403,509,134,365,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,218,218,218,498,218,218,577,627,551,497,572,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,553,354,236,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,296,455,131,131,456,243,103,86,41,459,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,9,276,158,716,393,564,383,489,401,654,210,654,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,650,86,86,86,86,86,86,717,667,563,563,563,86,549,102,686,133,246,605,86,448,86,86,207,307,131,131,131,641,86,177,611,445,373,194,584,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,307,171,86,86,86,86,86,86,86,717,86,86,86,86,86,460,131,131,650,86,86,86,694,708,86,86,694,86,458,131,131,131,131,131,131,667,694,289,650,667,131,131,86,640,131,131,664,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,460,86,86,86,86,86,86,86,86,86,86,86,86,86,458,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,466,203,149,429,94,432,160,687,539,63,237,283,192,248,348,259,427,526,396,676,254,468,487,212,327,623,49,633,322,493,434,688,357,361,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131]); -var mappingStr = "صلى الله عليه وسلمجل جلالهキロメートルrad∕s2エスクードキログラムキロワットグラムトンクルゼイロサンチームパーセントピアストルファラッドブッシェルヘクタールマンションミリバールレントゲン′′′′1⁄10viii(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)∫∫∫∫(오전)(오후)アパートアルファアンペアイニングエーカーカラットカロリーキュリーギルダークローネサイクルシリングバーレルフィートポイントマイクロミクロンメガトンリットルルーブル株式会社kcalm∕s2c∕kgاكبرمحمدصلعمرسولریال1⁄41⁄23⁄4 ̈́ྲཱྀླཱྀ ̈͂ ̓̀ ̓́ ̓͂ ̔̀ ̔́ ̔͂ ̈̀‵‵‵a/ca/sc/oc/utelfax1⁄71⁄91⁄32⁄31⁄52⁄53⁄54⁄51⁄65⁄61⁄83⁄85⁄87⁄8xii0⁄3∮∮∮(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)::====(ᄀ)(ᄂ)(ᄃ)(ᄅ)(ᄆ)(ᄇ)(ᄉ)(ᄋ)(ᄌ)(ᄎ)(ᄏ)(ᄐ)(ᄑ)(ᄒ)(가)(나)(다)(라)(마)(바)(사)(아)(자)(차)(카)(타)(파)(하)(주)(一)(二)(三)(四)(五)(六)(七)(八)(九)(十)(月)(火)(水)(木)(金)(土)(日)(株)(有)(社)(名)(特)(財)(祝)(労)(代)(呼)(学)(監)(企)(資)(協)(祭)(休)(自)(至)pte10月11月12月ergltdアールインチウォンオンスオームカイリガロンガンマギニーケースコルナコーポセンチダースノットハイツパーツピクルフランペニヒヘルツペンスページベータボルトポンドホールホーンマイルマッハマルクヤードヤールユアンルピー10点11点12点13点14点15点16点17点18点19点20点21点22点23点24点hpabardm2dm3khzmhzghzthzmm2cm2km2mm3cm3km3kpampagpalogmilmolppmv∕ma∕m10日11日12日13日14日15日16日17日18日19日20日21日22日23日24日25日26日27日28日29日30日31日galffifflשּׁשּׂ ٌّ ٍّ َّ ُّ ِّ ّٰـَّـُّـِّتجمتحجتحمتخمتمجتمحتمخجمححميحمىسحجسجحسجىسمحسمجسممصححصممشحمشجيشمخشممضحىضخمطمحطممطميعجمعممعمىغممغميغمىفخمقمحقمملحملحيلحىلججلخملمحمحجمحيمجحمجممخممجخهمجهممنحمنحىنجمنجىنمينمىيممبخيتجيتجىتخيتخىتميتمىجميجحىجمىسخىصحيشحيضحيلجيلمييحييجييميمميقمينحيعميكمينجحمخيلجمكممجحيحجيمجيفميبحيسخينجيصلےقلے𝅘𝅥𝅮𝅘𝅥𝅯𝅘𝅥𝅰𝅘𝅥𝅱𝅘𝅥𝅲𝆹𝅥𝅮𝆺𝅥𝅮𝆹𝅥𝅯𝆺𝅥𝅯〔s〕ppv〔本〕〔三〕〔二〕〔安〕〔点〕〔打〕〔盗〕〔勝〕〔敗〕 ̄ ́ ̧ssi̇ijl·ʼndžljnjdz ̆ ̇ ̊ ̨ ̃ ̋ ιեւاٴوٴۇٴيٴक़ख़ग़ज़ड़ढ़फ़य़ড়ঢ়য়ਲ਼ਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ଡ଼ଢ଼ําໍາຫນຫມགྷཌྷདྷབྷཛྷཀྵཱཱིུྲྀླྀྒྷྜྷྡྷྦྷྫྷྐྵaʾἀιἁιἂιἃιἄιἅιἆιἇιἠιἡιἢιἣιἤιἥιἦιἧιὠιὡιὢιὣιὤιὥιὦιὧιὰιαιάιᾶι ͂ὴιηιήιῆιὼιωιώιῶι ̳!! ̅???!!?rs°c°fnosmtmivix⫝̸ ゙ ゚よりコト333435참고주의363738394042444546474849503月4月5月6月7月8月9月hgevギガデシドルナノピコビルペソホンリラレムdaauovpciu平成昭和大正明治naμakakbmbgbpfnfμfμgmgμlmldlklfmnmμmpsnsμsmsnvμvkvpwnwμwmwkwkωmωbqcccddbgyhainkkktlnlxphprsrsvwbstմնմեմիվնմխיִײַשׁשׂאַאָאּבּגּדּהּוּזּטּיּךּכּלּמּנּסּףּפּצּקּרּתּוֹבֿכֿפֿאלئائەئوئۇئۆئۈئېئىئجئحئمئيبجبمبىبيتىتيثجثمثىثيخحضجضمطحظمغجفجفحفىفيقحقىقيكاكجكحكخكلكىكينخنىنيهجهىهييىذٰرٰىٰئرئزئنبزبنترتزتنثرثزثنمانرنزننيريزئخئهبهتهصخنههٰثهسهشهطىطيعىعيغىغيسىسيشىشيصىصيضىضيشخشرسرصرضراً ًـًـّ ْـْلآلألإ𝅗𝅥0,1,2,3,4,5,6,7,8,9,wzhvsdwcmcmddjほかココàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįĵķĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷÿźżɓƃƅɔƈɖɗƌǝəɛƒɠɣɩɨƙɯɲɵơƣƥʀƨʃƭʈưʊʋƴƶʒƹƽǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǵƕƿǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟƞȣȥȧȩȫȭȯȱȳⱥȼƚⱦɂƀʉʌɇɉɋɍɏɦɹɻʁʕͱͳʹͷ;ϳέίόύβγδεζθκλνξοπρστυφχψϊϋϗϙϛϝϟϡϣϥϧϩϫϭϯϸϻͻͼͽѐёђѓєѕіїјљњћќѝўџабвгдежзийклмнопрстуфхцчшщъыьэюяѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯաբգդզէըթժլծկհձղճյշոչպջռստրցփքօֆ་ⴧⴭნᏰᏱᏲᏳᏴᏵꙋɐɑᴂɜᴖᴗᴝᴥɒɕɟɡɥɪᵻʝɭᶅʟɱɰɳɴɸʂƫᴜʐʑḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἐἑἒἓἔἕἰἱἲἳἴἵἶἷὀὁὂὃὄὅὑὓὕὗᾰᾱὲΐῐῑὶΰῠῡὺῥ`ὸ‐+−∑〈〉ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡɫᵽɽⱨⱪⱬⱳⱶȿɀⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⳳⵡ母龟丨丶丿乙亅亠人儿入冂冖冫几凵刀力勹匕匚匸卜卩厂厶又口囗士夂夊夕女子宀寸小尢尸屮山巛工己巾干幺广廴廾弋弓彐彡彳心戈戶手支攴文斗斤方无曰欠止歹殳毋比毛氏气爪父爻爿片牙牛犬玄玉瓜瓦甘生用田疋疒癶白皮皿目矛矢石示禸禾穴立竹米糸缶网羊羽老而耒耳聿肉臣臼舌舛舟艮色艸虍虫血行衣襾見角言谷豆豕豸貝赤走足身車辛辰辵邑酉釆里長門阜隶隹雨靑非面革韋韭音頁風飛食首香馬骨高髟鬥鬯鬲鬼魚鳥鹵鹿麥麻黃黍黑黹黽鼎鼓鼠鼻齊齒龍龜龠.〒卄卅ᄁᆪᆬᆭᄄᆰᆱᆲᆳᆴᆵᄚᄈᄡᄊ짜ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᄔᄕᇇᇈᇌᇎᇓᇗᇙᄜᇝᇟᄝᄞᄠᄢᄣᄧᄩᄫᄬᄭᄮᄯᄲᄶᅀᅇᅌᇱᇲᅗᅘᅙᆄᆅᆈᆑᆒᆔᆞᆡ上中下甲丙丁天地問幼箏우秘男適優印注項写左右医宗夜テヌモヨヰヱヲꙁꙃꙅꙇꙉꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼᵹꝿꞁꞃꞅꞇꞌꞑꞓꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩɬʞʇꭓꞵꞷꬷꭒᎠᎡᎢᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯ豈更賈滑串句契喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛蘭鸞嵐濫藍襤拉臘蠟廊朗浪狼郎來冷勞擄櫓爐盧蘆虜路露魯鷺碌祿綠菉錄論壟弄籠聾牢磊賂雷壘屢樓淚漏累縷陋勒肋凜凌稜綾菱陵讀拏諾丹寧怒率異北磻便復不泌數索參塞省葉說殺沈拾若掠略亮兩凉梁糧良諒量勵呂廬旅濾礪閭驪麗黎曆歷轢年憐戀撚漣煉璉秊練聯輦蓮連鍊列劣咽烈裂廉念捻殮簾獵令囹嶺怜玲瑩羚聆鈴零靈領例禮醴隸惡了僚寮尿料燎療蓼遼暈阮劉杻柳流溜琉留硫紐類戮陸倫崙淪輪律慄栗隆利吏履易李梨泥理痢罹裏裡離匿溺吝燐璘藺隣鱗麟林淋臨笠粒狀炙識什茶刺切度拓糖宅洞暴輻降廓兀嗀塚晴凞猪益礼神祥福靖精蘒諸逸都飯飼館鶴郞隷侮僧免勉勤卑喝嘆器塀墨層悔慨憎懲敏既暑梅海渚漢煮爫琢碑祉祈祐祖禍禎穀突節縉繁署者臭艹著褐視謁謹賓贈辶難響頻恵𤋮舘並况全侀充冀勇勺啕喙嗢墳奄奔婢嬨廒廙彩徭惘慎愈慠戴揄搜摒敖望杖滛滋瀞瞧爵犯瑱甆画瘝瘟盛直睊着磌窱类絛缾荒華蝹襁覆調請諭變輸遲醙鉶陼韛頋鬒𢡊𢡄𣏕㮝䀘䀹𥉉𥳐𧻓齃龎עםٱٻپڀٺٿٹڤڦڄڃچڇڍڌڎڈژڑکگڳڱںڻۀہھۓڭۋۅۉ、〖〗—–_{}【】《》「」『』[]#&*-<>\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀"; - -function mapChar(codePoint) { - if (codePoint >= 0x30000) { - // High planes are special cased. - if (codePoint >= 0xE0100 && codePoint <= 0xE01EF) - return 18874368; - return 0; - } - return blocks[blockIdxes[codePoint >> 4]][codePoint & 15]; -} - -return { - mapStr: mappingStr, - mapChar: mapChar -}; -})); - -},{}],450:[function(require,module,exports){ -(function(root, factory) { - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define(['punycode', './idna-map'], function(punycode, idna_map) { - return factory(punycode, idna_map); - }); - } - else if (typeof exports === 'object') { - module.exports = factory(require('punycode'), require('./idna-map')); - } - else { - root.uts46 = factory(root.punycode, root.idna_map); - } -}(this, function(punycode, idna_map) { - - function mapLabel(label, useStd3ASCII, transitional) { - var mapped = []; - var chars = punycode.ucs2.decode(label); - for (var i = 0; i < chars.length; i++) { - var cp = chars[i]; - var ch = punycode.ucs2.encode([chars[i]]); - var composite = idna_map.mapChar(cp); - var flags = (composite >> 23); - var kind = (composite >> 21) & 3; - var index = (composite >> 5) & 0xffff; - var length = composite & 0x1f; - var value = idna_map.mapStr.substr(index, length); - if (kind === 0 || (useStd3ASCII && (flags & 1))) { - throw new Error("Illegal char " + ch); - } - else if (kind === 1) { - mapped.push(value); - } - else if (kind === 2) { - mapped.push(transitional ? value : ch); - } - /* istanbul ignore next */ - else if (kind === 3) { - mapped.push(ch); - } - } - - var newLabel = mapped.join("").normalize("NFC"); - return newLabel; - } - - function process(domain, transitional, useStd3ASCII) { - /* istanbul ignore if */ - if (useStd3ASCII === undefined) - useStd3ASCII = false; - var mappedIDNA = mapLabel(domain, useStd3ASCII, transitional); - - // Step 3. Break - var labels = mappedIDNA.split("."); - - // Step 4. Convert/Validate - labels = labels.map(function(label) { - if (label.startsWith("xn--")) { - label = punycode.decode(label.substring(4)); - validateLabel(label, useStd3ASCII, false); - } - else { - validateLabel(label, useStd3ASCII, transitional); - } - return label; - }); - - return labels.join("."); - } - - function validateLabel(label, useStd3ASCII, transitional) { - // 2. The label must not contain a U+002D HYPHEN-MINUS character in both the - // third position and fourth positions. - if (label[2] === '-' && label[3] === '-') - throw new Error("Failed to validate " + label); - - // 3. The label must neither begin nor end with a U+002D HYPHEN-MINUS - // character. - if (label.startsWith('-') || label.endsWith('-')) - throw new Error("Failed to validate " + label); - - // 4. The label must not contain a U+002E ( . ) FULL STOP. - // this should nerver happen as label is chunked internally by this character - /* istanbul ignore if */ - if (label.includes('.')) - throw new Error("Failed to validate " + label); - - if (mapLabel(label, useStd3ASCII, transitional) !== label) - throw new Error("Failed to validate " + label); - - // 5. The label must not begin with a combining mark, that is: - // General_Category=Mark. - var ch = label.codePointAt(0); - if (idna_map.mapChar(ch) & (0x2 << 23)) - throw new Error("Label contains illegal character: " + ch); - } - - function toAscii(domain, options) { - if (options === undefined) - options = {}; - var transitional = 'transitional' in options ? options.transitional : true; - var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; - var verifyDnsLength = 'verifyDnsLength' in options ? options.verifyDnsLength : false; - var labels = process(domain, transitional, useStd3ASCII).split('.'); - var asciiLabels = labels.map(punycode.toASCII); - var asciiString = asciiLabels.join('.'); - var i; - if (verifyDnsLength) { - if (asciiString.length < 1 || asciiString.length > 253) { - throw new Error("DNS name has wrong length: " + asciiString); - } - for (i = 0; i < asciiLabels.length; i++) {//for .. of replacement - var label = asciiLabels[i]; - if (label.length < 1 || label.length > 63) - throw new Error("DNS label has wrong length: " + label); - } - } - return asciiString; - } - - function toUnicode(domain, options) { - if (options === undefined) - options = {}; - var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; - return process(domain, false, useStd3ASCII); - } - - return { - toUnicode: toUnicode, - toAscii: toAscii, - }; -})); - -},{"./idna-map":449,"punycode":1538}],451:[function(require,module,exports){ +},{"stream":1459,"xtend":314}],314:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],315:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 @@ -66142,7 +43842,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],452:[function(require,module,exports){ +},{}],316:[function(require,module,exports){ var indexOf = [].indexOf; @@ -66153,36 +43853,9 @@ module.exports = function(arr, obj){ } return -1; }; -},{}],453:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],454:[function(require,module,exports){ +},{}],317:[function(require,module,exports){ +arguments[4][27][0].apply(exports,arguments) +},{"dup":27}],318:[function(require,module,exports){ 'use strict' const defer = require('pull-defer/duplex') @@ -66244,14 +43917,14 @@ module.exports = class Connection { } } -},{"pull-defer/duplex":1466}],455:[function(require,module,exports){ +},{"pull-defer/duplex":1284}],319:[function(require,module,exports){ 'use strict' exports.Connection = require('./connection') -},{"./connection":454}],456:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],457:[function(require,module,exports){ +},{"./connection":318}],320:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],321:[function(require,module,exports){ 'use strict' const errcode = require('err-code') @@ -66276,7 +43949,7 @@ module.exports.notFoundError = (err) => { return errcode(err, 'ERR_NOT_FOUND') } -},{"err-code":456}],458:[function(require,module,exports){ +},{"err-code":320}],322:[function(require,module,exports){ /* @flow */ 'use strict' @@ -66346,7 +44019,7 @@ export type Order = (QueryResult, Callback>) => */ -},{"./errors":457,"./key":459,"./memory":460,"./utils":461}],459:[function(require,module,exports){ +},{"./errors":321,"./key":323,"./memory":324,"./utils":325}],323:[function(require,module,exports){ (function (Buffer){ /* @flow */ 'use strict' @@ -66728,7 +44401,7 @@ const _Key = withIs(Key, { className: 'Key', symbolName: '@ipfs/interface-datast module.exports = _Key }).call(this,require("buffer").Buffer) -},{"buffer":217,"class-is":224,"uuid/v4":1781}],460:[function(require,module,exports){ +},{"buffer":181,"class-is":187,"uuid/v4":1517}],324:[function(require,module,exports){ /* @flow */ 'use strict' @@ -66863,7 +44536,7 @@ class MemoryDatastore { module.exports = MemoryDatastore -},{"./errors":457,"./key":459,"./utils":461,"async/setImmediate":146,"pull-stream":1495}],461:[function(require,module,exports){ +},{"./errors":321,"./key":323,"./utils":325,"async/setImmediate":96,"pull-stream":1311}],325:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -66944,7 +44617,7 @@ exports.tmpdir = () => { return path.join(os.tmpdir(), uuid()) } -},{"os":1395,"path":1425,"pull-defer/source":1469,"pull-stream":1495,"uuid/v4":1781}],462:[function(require,module,exports){ +},{"os":1229,"path":1246,"pull-defer/source":1287,"pull-stream":1311,"uuid/v4":1517}],326:[function(require,module,exports){ 'use strict'; const v4 = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3}'; @@ -66970,7 +44643,7 @@ const ip = module.exports = opts => opts && opts.exact ? ip.v4 = opts => opts && opts.exact ? new RegExp(`^${v4}$`) : new RegExp(v4, 'g'); ip.v6 = opts => opts && opts.exact ? new RegExp(`^${v6}$`) : new RegExp(v6, 'g'); -},{}],463:[function(require,module,exports){ +},{}],327:[function(require,module,exports){ 'use strict'; var ip = exports; @@ -67388,7 +45061,7 @@ ip.fromLong = function(ipl) { (ipl & 255) ); }; -},{"buffer":217,"os":1395}],464:[function(require,module,exports){ +},{"buffer":181,"os":1229}],328:[function(require,module,exports){ ;(function (globalObject) { 'use strict'; @@ -70301,11 +47974,19957 @@ ip.fromLong = function(ipl) { } })(this); -},{}],465:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":466,"_process":1438,"dup":247}],466:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":468}],467:[function(require,module,exports){ +},{}],329:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":330,"_process":1258,"dup":208}],330:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],331:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const blake = require('blakejs') + +const toCallback = require('./utils').toCallback + +const minB = 0xb201 +const minS = 0xb241 + +const blake2b = { + init: blake.blake2bInit, + update: blake.blake2bUpdate, + digest: blake.blake2bFinal +} + +const blake2s = { + init: blake.blake2sInit, + update: blake.blake2sUpdate, + digest: blake.blake2sFinal +} + +const makeB2Hash = (size, hf) => toCallback((buf) => { + const ctx = hf.init(size, null) + hf.update(ctx, buf) + return Buffer.from(hf.digest(ctx)) +}) + +module.exports = (table) => { + for (let i = 0; i < 64; i++) { + table[minB + i] = makeB2Hash(i + 1, blake2b) + } + for (let i = 0; i < 32; i++) { + table[minS + i] = makeB2Hash(i + 1, blake2s) + } +} + +}).call(this,require("buffer").Buffer) +},{"./utils":335,"blakejs":132,"buffer":181}],332:[function(require,module,exports){ +(function (Buffer){ +/* global self */ + +'use strict' + +const nodeify = require('nodeify') + +const webCrypto = getWebCrypto() + +function getWebCrypto () { + if (self.crypto) { + return self.crypto.subtle || self.crypto.webkitSubtle + } + + if (self.msCrypto) { + return self.msCrypto.subtle + } +} + +function webCryptoHash (type) { + if (!webCrypto) { + throw new Error('Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context') + } + + return (data, callback) => { + const res = webCrypto.digest({ name: type }, data) + + if (typeof res.then !== 'function') { // IE11 + res.onerror = () => { + callback(new Error(`hashing data using ${type}`)) + } + res.oncomplete = (e) => { + callback(null, e.target.result) + } + return + } + + nodeify( + res.then((raw) => Buffer.from(new Uint8Array(raw))), + callback + ) + } +} + +function sha1 (buf, callback) { + webCryptoHash('SHA-1')(buf, callback) +} + +function sha2256 (buf, callback) { + webCryptoHash('SHA-256')(buf, callback) +} + +function sha2512 (buf, callback) { + webCryptoHash('SHA-512')(buf, callback) +} + +module.exports = { + sha1: sha1, + sha2256: sha2256, + sha2512: sha2512 +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"nodeify":1225}],333:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const sha3 = require('js-sha3') +const murmur3 = require('murmurhash3js') + +const utils = require('./utils') +const sha = require('./crypto-sha1-2') + +const toCallback = utils.toCallback +const toBuf = utils.toBuf +const fromString = utils.fromString +const fromNumberTo32BitBuf = utils.fromNumberTo32BitBuf + +const dblSha2256 = (buf, cb) => { + sha.sha2256(buf, (err, firstHash) => { + if (err) { + cb(err) + } + sha.sha2256((Buffer.from(firstHash)), cb) + }) +} + +module.exports = { + sha1: sha.sha1, + sha2256: sha.sha2256, + sha2512: sha.sha2512, + sha3512: toCallback(toBuf(sha3.sha3_512)), + sha3384: toCallback(toBuf(sha3.sha3_384)), + sha3256: toCallback(toBuf(sha3.sha3_256)), + sha3224: toCallback(toBuf(sha3.sha3_224)), + shake128: toCallback(toBuf(sha3.shake_128, 128)), + shake256: toCallback(toBuf(sha3.shake_256, 256)), + keccak224: toCallback(toBuf(sha3.keccak_224)), + keccak256: toCallback(toBuf(sha3.keccak_256)), + keccak384: toCallback(toBuf(sha3.keccak_384)), + keccak512: toCallback(toBuf(sha3.keccak_512)), + murmur3128: toCallback(toBuf(fromString(murmur3.x64.hash128))), + murmur332: toCallback(fromNumberTo32BitBuf(fromString(murmur3.x86.hash32))), + addBlake: require('./blake'), + dblSha2256: dblSha2256 +} + +}).call(this,require("buffer").Buffer) +},{"./blake":331,"./crypto-sha1-2":332,"./utils":335,"buffer":181,"js-sha3":666,"murmurhash3js":1179}],334:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const multihash = require('multihashes') +const crypto = require('./crypto') + +module.exports = Multihashing + +/** + * Hash the given `buf` using the algorithm specified + * by `func`. + * + * @param {Buffer} buf - The value to hash. + * @param {number|string} func - The algorithm to use. + * @param {number} [length] - Optionally trim the result to this length. + * @param {function(Error, Buffer)} callback + * @returns {undefined} + */ +function Multihashing (buf, func, length, callback) { + if (typeof length === 'function') { + callback = length + length = undefined + } + + if (!callback) { + throw new Error('Missing callback') + } + + Multihashing.digest(buf, func, length, (err, digest) => { + if (err) { + return callback(err) + } + + callback(null, multihash.encode(digest, func, length)) + }) +} + +/** + * The `buffer` module for easy use in the browser. + * + * @type {Buffer} + */ +Multihashing.Buffer = Buffer // for browser things + +/** + * Expose multihash itself, to avoid silly double requires. + */ +Multihashing.multihash = multihash + +/** + * @param {Buffer} buf - The value to hash. + * @param {number|string} func - The algorithm to use. + * @param {number} [length] - Optionally trim the result to this length. + * @param {function(Error, Buffer)} callback + * @returns {undefined} + */ +Multihashing.digest = function (buf, func, length, callback) { + if (typeof length === 'function') { + callback = length + length = undefined + } + + if (!callback) { + throw new Error('Missing callback') + } + + let cb = callback + if (length) { + cb = (err, digest) => { + if (err) { + return callback(err) + } + + callback(null, digest.slice(0, length)) + } + } + + let hash + try { + hash = Multihashing.createHash(func) + } catch (err) { + return cb(err) + } + + hash(buf, cb) +} + +/** + * @param {string|number} func + * + * @returns {function} - The to `func` corresponding hash function. + */ +Multihashing.createHash = function (func) { + func = multihash.coerceCode(func) + if (!Multihashing.functions[func]) { + throw new Error('multihash function ' + func + ' not yet supported') + } + + return Multihashing.functions[func] +} + +/** + * Mapping of multihash codes to their hashing functions. + * @type {Object} + */ +Multihashing.functions = { + // sha1 + 0x11: crypto.sha1, + // sha2-256 + 0x12: crypto.sha2256, + // sha2-512 + 0x13: crypto.sha2512, + // sha3-512 + 0x14: crypto.sha3512, + // sha3-384 + 0x15: crypto.sha3384, + // sha3-256 + 0x16: crypto.sha3256, + // sha3-224 + 0x17: crypto.sha3224, + // shake-128 + 0x18: crypto.shake128, + // shake-256 + 0x19: crypto.shake256, + // keccak-224 + 0x1A: crypto.keccak224, + // keccak-256 + 0x1B: crypto.keccak256, + // keccak-384 + 0x1C: crypto.keccak384, + // keccak-512 + 0x1D: crypto.keccak512, + // murmur3-128 + 0x22: crypto.murmur3128, + // murmur3-32 + 0x23: crypto.murmur332, + // dbl-sha2-256 + 0x56: crypto.dblSha2256 +} + +// add blake functions +crypto.addBlake(Multihashing.functions) + +}).call(this,require("buffer").Buffer) +},{"./crypto":333,"buffer":181,"multihashes":1157}],335:[function(require,module,exports){ +(function (process,Buffer){ +'use strict' + +exports.toCallback = (doWork) => { + return function (input, callback) { + let res + try { + res = doWork(input) + } catch (err) { + process.nextTick(callback, err) + return + } + + process.nextTick(callback, null, res) + } +} + +exports.toBuf = (doWork, other) => (input) => { + let result = doWork(input, other) + return Buffer.from(result, 'hex') +} + +exports.fromString = (doWork, other) => (_input) => { + const input = Buffer.isBuffer(_input) ? _input.toString() : _input + return doWork(input, other) +} + +exports.fromNumberTo32BitBuf = (doWork, other) => (input) => { + let number = doWork(input, other) + const bytes = new Array(4) + + for (let i = 0; i < 4; i++) { + bytes[i] = number & 0xff + number = number >> 8 + } + + return Buffer.from(bytes) +} + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":1258,"buffer":181}],336:[function(require,module,exports){ +'use strict' + +const SECOND = 1000 + +module.exports = { + maxProvidersPerRequest: 3, + providerRequestTimeout: 10 * SECOND, + hasBlockTimeout: 15 * SECOND, + provideTimeout: 15 * SECOND, + kMaxPriority: Math.pow(2, 31) - 1, + rebroadcastDelay: 10 * SECOND, + maxListeners: 1000 +} + +},{}],337:[function(require,module,exports){ +'use strict' + +const each = require('async/each') +const eachSeries = require('async/eachSeries') +const waterfall = require('async/waterfall') +const nextTick = require('async/nextTick') + +const map = require('async/map') +const debounce = require('just-debounce-it') + +const Message = require('../types/message') +const Wantlist = require('../types/wantlist') +const Ledger = require('./ledger') +const { logger, groupBy, pullAllWith, uniqWith } = require('../utils') + +const MAX_MESSAGE_SIZE = 512 * 1024 + +class DecisionEngine { + constructor (peerId, blockstore, network, stats) { + this._log = logger(peerId, 'engine') + this.blockstore = blockstore + this.network = network + this._stats = stats + + // A list of of ledgers by their partner id + this.ledgerMap = new Map() + this._running = false + + // List of tasks to be processed + this._tasks = [] + + this._outbox = debounce(this._processTasks.bind(this), 100) + } + + _sendBlocks (peer, blocks, cb) { + // split into messges of max 512 * 1024 bytes + const total = blocks.reduce((acc, b) => { + return acc + b.data.byteLength + }, 0) + + if (total < MAX_MESSAGE_SIZE) { + return this._sendSafeBlocks(peer, blocks, cb) + } + + let size = 0 + let batch = [] + let outstanding = blocks.length + + eachSeries(blocks, (b, cb) => { + outstanding-- + batch.push(b) + size += b.data.byteLength + + if (size >= MAX_MESSAGE_SIZE || + // need to ensure the last remaining items get sent + outstanding === 0) { + size = 0 + const nextBatch = batch.slice() + batch = [] + this._sendSafeBlocks(peer, nextBatch, (err) => { + if (err) { + this._log('sendblock error: %s', err.message) + } + // not returning the error, so we send as much as we can + // as otherwise `eachSeries` would cancel + cb() + }) + } else { + nextTick(cb) + } + }, cb) + } + + _sendSafeBlocks (peer, blocks, cb) { + const msg = new Message(false) + blocks.forEach((b) => msg.addBlock(b)) + + this.network.sendMessage(peer, msg, cb) + } + + _processTasks () { + if (!this._running || !this._tasks.length) { + return + } + + const tasks = this._tasks + this._tasks = [] + const entries = tasks.map((t) => t.entry) + const cids = entries.map((e) => e.cid) + const uniqCids = uniqWith((a, b) => a.equals(b), cids) + const groupedTasks = groupBy(task => task.target.toB58String(), tasks) + + waterfall([ + (callback) => map(uniqCids, (cid, cb) => { + this.blockstore.get(cid, cb) + }, callback), + (blocks, callback) => each(Object.values(groupedTasks), (tasks, cb) => { + // all tasks have the same target + const peer = tasks[0].target + const blockList = cids.map((cid) => { + return blocks.find(b => b.cid.equals(cid)) + }) + + this._sendBlocks(peer, blockList, (err) => { + if (err) { + // `_sendBlocks` actually doesn't return any errors + this._log.error('should never happen: ', err) + } else { + blockList.forEach((block) => this.messageSent(peer, block)) + } + + cb() + }) + }, callback) + ], (err) => { + this._tasks = [] + + if (err) { + this._log.error(err) + } + }) + } + + wantlistForPeer (peerId) { + const peerIdStr = peerId.toB58String() + if (!this.ledgerMap.has(peerIdStr)) { + return new Map() + } + + return this.ledgerMap.get(peerIdStr).wantlist.sortedEntries() + } + + ledgerForPeer (peerId) { + const peerIdStr = peerId.toB58String() + + const ledger = this.ledgerMap.get(peerIdStr) + if (!ledger) { + return null + } + return { + peer: ledger.partner.toPrint(), + value: ledger.debtRatio(), + sent: ledger.accounting.bytesSent, + recv: ledger.accounting.bytesRecv, + exchanged: ledger.exchangeCount + } + } + + peers () { + return Array.from(this.ledgerMap.values()).map((l) => l.partner) + } + + receivedBlocks (cids) { + if (!cids.length) { + return + } + // Check all connected peers if they want the block we received + this.ledgerMap.forEach((ledger) => { + cids + .map((cid) => ledger.wantlistContains(cid)) + .filter(Boolean) + .forEach((entry) => { + this._tasks.push({ + entry: entry, + target: ledger.partner + }) + }) + }) + this._outbox() + } + + // Handle incoming messages + messageReceived (peerId, msg, cb) { + const ledger = this._findOrCreate(peerId) + + if (msg.empty) { + return nextTick(cb) + } + + // If the message was a full wantlist clear the current one + if (msg.full) { + ledger.wantlist = new Wantlist() + } + + this._processBlocks(msg.blocks, ledger) + + if (msg.wantlist.size === 0) { + return nextTick(cb) + } + + let cancels = [] + let wants = [] + msg.wantlist.forEach((entry) => { + if (entry.cancel) { + ledger.cancelWant(entry.cid) + cancels.push(entry) + } else { + ledger.wants(entry.cid, entry.priority) + wants.push(entry) + } + }) + + this._cancelWants(ledger, peerId, cancels) + this._addWants(ledger, peerId, wants, cb) + } + + _cancelWants (ledger, peerId, entries) { + const id = peerId.toB58String() + + this._tasks = pullAllWith((t, e) => { + const sameTarget = t.target.toB58String() === id + const sameCid = t.entry.cid.equals(e.cid) + return sameTarget && sameCid + }, this._tasks, entries) + } + + _addWants (ledger, peerId, entries, callback) { + each(entries, (entry, cb) => { + // If we already have the block, serve it + this.blockstore.has(entry.cid, (err, exists) => { + if (err) { + this._log.error('failed existence check') + } else if (exists) { + this._tasks.push({ + entry: entry.entry, + target: peerId + }) + } + cb() + }) + }, () => { + this._outbox() + callback() + }) + } + + _processBlocks (blocks, ledger, callback) { + const cids = [] + blocks.forEach((b, cidStr) => { + this._log('got block (%s bytes)', b.data.length) + ledger.receivedBytes(b.data.length) + cids.push(b.cid) + }) + + this.receivedBlocks(cids) + } + + // Clear up all accounting things after message was sent + messageSent (peerId, block) { + const ledger = this._findOrCreate(peerId) + ledger.sentBytes(block ? block.data.length : 0) + if (block && block.cid) { + ledger.wantlist.remove(block.cid) + } + } + + numBytesSentTo (peerId) { + return this._findOrCreate(peerId).accounting.bytesSent + } + + numBytesReceivedFrom (peerId) { + return this._findOrCreate(peerId).accounting.bytesRecv + } + + peerDisconnected (peerId) { + // if (this.ledgerMap.has(peerId.toB58String())) { + // this.ledgerMap.delete(peerId.toB58String()) + // } + // + // TODO: figure out how to remove all other references + // in the peer request queue + } + + _findOrCreate (peerId) { + const peerIdStr = peerId.toB58String() + if (this.ledgerMap.has(peerIdStr)) { + return this.ledgerMap.get(peerIdStr) + } + + const l = new Ledger(peerId) + + this.ledgerMap.set(peerIdStr, l) + if (this._stats) { + this._stats.push(peerIdStr, 'peerCount', 1) + } + + return l + } + + start (callback) { + this._running = true + nextTick(() => callback()) + } + + stop (callback) { + this._running = false + nextTick(() => callback()) + } +} + +module.exports = DecisionEngine + +},{"../types/message":345,"../types/wantlist":348,"../utils":349,"./ledger":338,"async/each":56,"async/eachSeries":61,"async/map":87,"async/nextTick":90,"async/waterfall":102,"just-debounce-it":668}],338:[function(require,module,exports){ +'use strict' + +const Wantlist = require('../types/wantlist') + +class Ledger { + constructor (peerId) { + this.partner = peerId + this.wantlist = new Wantlist() + + this.exchangeCount = 0 + this.sentToPeer = new Map() + + this.accounting = { + bytesSent: 0, + bytesRecv: 0 + } + } + + sentBytes (n) { + this.exchangeCount++ + this.lastExchange = (new Date()).getTime() + this.accounting.bytesSent += n + } + + receivedBytes (n) { + this.exchangeCount++ + this.lastExchange = (new Date()).getTime() + this.accounting.bytesRecv += n + } + + wants (cid, priority) { + this.wantlist.add(cid, priority) + } + + cancelWant (cid) { + this.wantlist.remove(cid) + } + + wantlistContains (cid) { + return this.wantlist.contains(cid) + } + + debtRatio () { + return (this.accounting.bytesSent / (this.accounting.bytesRecv + 1)) // +1 is to prevent division by zero + } +} + +module.exports = Ledger + +},{"../types/wantlist":348}],339:[function(require,module,exports){ +'use strict' + +const waterfall = require('async/waterfall') +const reject = require('async/reject') +const each = require('async/each') +const series = require('async/series') +const map = require('async/map') +const nextTick = require('async/nextTick') + +const WantManager = require('./want-manager') +const Network = require('./network') +const DecisionEngine = require('./decision-engine') +const Notifications = require('./notifications') +const logger = require('./utils').logger +const Stats = require('./stats') + +const defaultOptions = { + statsEnabled: false, + statsComputeThrottleTimeout: 1000, + statsComputeThrottleMaxQueueSize: 1000 +} +const statsKeys = [ + 'blocksReceived', + 'dataReceived', + 'dupBlksReceived', + 'dupDataReceived', + 'blocksSent', + 'dataSent', + 'providesBufferLength', + 'wantListLength', + 'peerCount' +] + +/** + * JavaScript implementation of the Bitswap 'data exchange' protocol + * used by IPFS. + * + * @param {Libp2p} libp2p + * @param {Blockstore} blockstore + */ +class Bitswap { + constructor (libp2p, blockstore, options) { + this._libp2p = libp2p + this._log = logger(this.peerInfo.id) + + this._options = Object.assign({}, defaultOptions, options) + + // stats + this._stats = new Stats(statsKeys, { + enabled: this._options.statsEnabled, + computeThrottleTimeout: this._options.statsComputeThrottleTimeout, + computeThrottleMaxQueueSize: this._options.statsComputeThrottleMaxQueueSize + }) + + // the network delivers messages + this.network = new Network(libp2p, this, {}, this._stats) + + // local database + this.blockstore = blockstore + + this.engine = new DecisionEngine(this.peerInfo.id, blockstore, this.network, this._stats) + + // handle message sending + this.wm = new WantManager(this.peerInfo.id, this.network, this._stats) + + this.notifications = new Notifications(this.peerInfo.id) + } + + get peerInfo () { + return this._libp2p.peerInfo + } + + // handle messages received through the network + _receiveMessage (peerId, incoming, callback) { + this.engine.messageReceived(peerId, incoming, (err) => { + if (err) { + // Only logging the issue to process as much as possible + // of the message. Currently `messageReceived` does not + // return any errors, but this could change in the future. + this._log('failed to receive message', incoming) + } + + if (incoming.blocks.size === 0) { + return callback() + } + + const blocks = Array.from(incoming.blocks.values()) + + // quickly send out cancels, reduces chances of duplicate block receives + const wanted = blocks + .filter((b) => this.wm.wantlist.contains(b.cid)) + .map((b) => b.cid) + + this.wm.cancelWants(wanted) + + each( + blocks, + (b, cb) => { + const wasWanted = wanted.includes(b.cid) + this._handleReceivedBlock(peerId, b, wasWanted, cb) + }, + callback + ) + }) + } + + _handleReceivedBlock (peerId, block, wasWanted, callback) { + this._log('received block') + + waterfall([ + (cb) => this.blockstore.has(block.cid, cb), + (has, cb) => { + this._updateReceiveCounters(peerId.toB58String(), block, has) + if (has || !wasWanted) { + return nextTick(cb) + } + + this._putBlock(block, cb) + } + ], callback) + } + + _updateReceiveCounters (peerId, block, exists) { + this._stats.push(peerId, 'blocksReceived', 1) + this._stats.push(peerId, 'dataReceived', block.data.length) + + if (exists) { + this._stats.push(peerId, 'dupBlksReceived', 1) + this._stats.push(peerId, 'dupDataReceived', block.data.length) + } + } + + // handle errors on the receiving channel + _receiveError (err) { + this._log.error('ReceiveError: %s', err.message) + } + + // handle new peers + _onPeerConnected (peerId) { + this.wm.connected(peerId) + } + + // handle peers being disconnected + _onPeerDisconnected (peerId) { + this.wm.disconnected(peerId) + this.engine.peerDisconnected(peerId) + this._stats.disconnected(peerId) + } + + _putBlock (block, callback) { + this.blockstore.put(block, (err) => { + if (err) { + return callback(err) + } + + this.notifications.hasBlock(block) + this.network.provide(block.cid, (err) => { + if (err) { + this._log.error('Failed to provide: %s', err.message) + } + }) + + this.engine.receivedBlocks([block.cid]) + callback() + }) + } + + enableStats () { + this._stats.enable() + } + + disableStats () { + this._stats.disable() + } + + /** + * Return the current wantlist for a given `peerId` + * + * @param {PeerId} peerId + * @returns {Wantlist} + */ + wantlistForPeer (peerId) { + return this.engine.wantlistForPeer(peerId) + } + + /** + * Return ledger information for a given `peerId` + * + * @param {PeerId} peerId + * @returns {?Object} + */ + ledgerForPeer (peerId) { + return this.engine.ledgerForPeer(peerId) + } + + /** + * Fetch a given block by cid. If the block is in the local + * blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us. + * + * @param {CID} cid + * @param {function(Error, Block)} callback + * @returns {void} + */ + get (cid, callback) { + this.getMany([cid], (err, blocks) => { + if (err) { + return callback(err) + } + + if (blocks && blocks.length > 0) { + callback(null, blocks[0]) + } else { + // when a unwant happens + callback() + } + }) + } + + /** + * Fetch a a list of blocks by cid. If the blocks are in the local + * blockstore they are returned, otherwise the blocks are added to the wantlist and returned once another node sends them to us. + * + * @param {Array} cids + * @param {function(Error, Blocks)} callback + * @returns {void} + */ + getMany (cids, callback) { + let pendingStart = cids.length + const wantList = [] + let promptedNetwork = false + + const getFromOutside = (cid, cb) => { + wantList.push(cid) + + this.notifications.wantBlock( + cid, + // called on block receive + (block) => { + this.wm.cancelWants([cid]) + cb(null, block) + }, + // called on unwant + () => { + this.wm.cancelWants([cid]) + cb(null, undefined) + } + ) + + if (!pendingStart) { + this.wm.wantBlocks(wantList) + } + } + + map(cids, (cid, cb) => { + waterfall( + [ + (cb) => this.blockstore.has(cid, cb), + (has, cb) => { + pendingStart-- + if (has) { + if (!pendingStart) { + this.wm.wantBlocks(wantList) + } + return this.blockstore.get(cid, cb) + } + + if (!promptedNetwork) { + promptedNetwork = true + this.network.findAndConnect(cids[0], (err) => { + if (err) { + this._log.error(err) + } + }) + } + + // we don't have the block here + getFromOutside(cid, cb) + } + ], + cb) + }, callback) + } + + // removes the given cids from the wantlist independent of any ref counts + unwant (cids) { + if (!Array.isArray(cids)) { + cids = [cids] + } + + this.wm.unwantBlocks(cids) + cids.forEach((cid) => this.notifications.unwantBlock(cid)) + } + + // removes the given keys from the want list + cancelWants (cids) { + if (!Array.isArray(cids)) { + cids = [cids] + } + this.wm.cancelWants(cids) + } + + /** + * Put the given block to the underlying blockstore and + * send it to nodes that have it in their wantlist. + * + * @param {Block} block + * @param {function(Error)} callback + * @returns {void} + */ + put (block, callback) { + this._log('putting block') + + waterfall([ + (cb) => this.blockstore.has(block.cid, cb), + (has, cb) => { + if (has) { + return nextTick(cb) + } + + this._putBlock(block, cb) + } + ], callback) + } + + /** + * Put the given blocks to the underlying blockstore and + * send it to nodes that have it them their wantlist. + * + * @param {Array} blocks + * @param {function(Error)} callback + * @returns {void} + */ + putMany (blocks, callback) { + waterfall([ + (cb) => reject(blocks, (b, cb) => { + this.blockstore.has(b.cid, cb) + }, cb), + (newBlocks, cb) => this.blockstore.putMany(newBlocks, (err) => { + if (err) { + return cb(err) + } + + newBlocks.forEach((block) => { + this.notifications.hasBlock(block) + this.engine.receivedBlocks([block.cid]) + this.network.provide(block.cid, (err) => { + if (err) { + this._log.error('Failed to provide: %s', err.message) + } + }) + }) + cb() + }) + ], callback) + } + + /** + * Get the current list of wants. + * + * @returns {Iterator} + */ + getWantlist () { + return this.wm.wantlist.entries() + } + + /** + * Get the current list of partners. + * + * @returns {Array} + */ + peers () { + return this.engine.peers() + } + + /** + * Get stats about the bitswap node. + * + * @returns {Object} + */ + stat () { + return this._stats + } + + /** + * Start the bitswap node. + * + * @param {function(Error)} callback + * + * @returns {void} + */ + start (callback) { + series([ + (cb) => this.wm.start(cb), + (cb) => this.network.start(cb), + (cb) => this.engine.start(cb) + ], callback) + } + + /** + * Stop the bitswap node. + * + * @param {function(Error)} callback + * + * @returns {void} + */ + stop (callback) { + this._stats.stop() + series([ + (cb) => this.wm.stop(cb), + (cb) => this.network.stop(cb), + (cb) => this.engine.stop(cb) + ], callback) + } +} + +module.exports = Bitswap + +},{"./decision-engine":337,"./network":340,"./notifications":341,"./stats":342,"./utils":349,"./want-manager":350,"async/each":56,"async/map":87,"async/nextTick":90,"async/reject":93,"async/series":95,"async/waterfall":102}],340:[function(require,module,exports){ +'use strict' + +const lp = require('pull-length-prefixed') +const pull = require('pull-stream') +const waterfall = require('async/waterfall') +const each = require('async/each') +const nextTick = require('async/nextTick') + +const Message = require('./types/message') +const CONSTANTS = require('./constants') +const logger = require('./utils').logger + +const BITSWAP100 = '/ipfs/bitswap/1.0.0' +const BITSWAP110 = '/ipfs/bitswap/1.1.0' + +class Network { + constructor (libp2p, bitswap, options, stats) { + this._log = logger(libp2p.peerInfo.id, 'network') + options = options || {} + this.libp2p = libp2p + this.bitswap = bitswap + this.b100Only = options.b100Only || false + + this._stats = stats + this._running = false + } + + start (callback) { + this._running = true + // bind event listeners + this._onPeerConnect = this._onPeerConnect.bind(this) + this._onPeerDisconnect = this._onPeerDisconnect.bind(this) + + this._onConnection = this._onConnection.bind(this) + this.libp2p.handle(BITSWAP100, this._onConnection) + if (!this.b100Only) { this.libp2p.handle(BITSWAP110, this._onConnection) } + + this.libp2p.on('peer:connect', this._onPeerConnect) + this.libp2p.on('peer:disconnect', this._onPeerDisconnect) + + // All existing connections are like new ones for us + this.libp2p.peerBook + .getAllArray() + .filter((peer) => peer.isConnected()) + .forEach((peer) => this._onPeerConnect((peer))) + + nextTick(() => callback()) + } + + stop (callback) { + this._running = false + + this.libp2p.unhandle(BITSWAP100) + if (!this.b100Only) { this.libp2p.unhandle(BITSWAP110) } + + this.libp2p.removeListener('peer:connect', this._onPeerConnect) + this.libp2p.removeListener('peer:disconnect', this._onPeerDisconnect) + + nextTick(() => callback()) + } + + // Handles both types of bitswap messgages + _onConnection (protocol, conn) { + if (!this._running) { return } + this._log('incomming new bitswap connection: %s', protocol) + + pull( + conn, + lp.decode(), + pull.asyncMap((data, cb) => Message.deserialize(data, cb)), + pull.asyncMap((msg, cb) => { + conn.getPeerInfo((err, peerInfo) => { + if (err) { return cb(err) } + + // this._log('data from', peerInfo.id.toB58String()) + this.bitswap._receiveMessage(peerInfo.id, msg, cb) + }) + }), + pull.onEnd((err) => { + this._log('ending connection') + if (err) { + this.bitswap._receiveError(err) + } + }) + ) + } + + _onPeerConnect (peerInfo) { + if (!this._running) { return } + + this.bitswap._onPeerConnected(peerInfo.id) + } + + _onPeerDisconnect (peerInfo) { + if (!this._running) { return } + + this.bitswap._onPeerDisconnected(peerInfo.id) + } + + findProviders (cid, maxProviders, callback) { + this.libp2p.contentRouting.findProviders(cid, { + maxTimeout: CONSTANTS.providerRequestTimeout, + maxNumProviders: maxProviders + }, callback) + } + + findAndConnect (cid, callback) { + waterfall([ + (cb) => this.findProviders(cid, CONSTANTS.maxProvidersPerRequest, cb), + (provs, cb) => { + this._log('connecting to providers', provs.map((p) => p.id.toB58String())) + each(provs, (p, cb) => this.connectTo(p, cb)) + } + ], callback) + } + + provide (cid, callback) { + this.libp2p.contentRouting.provide(cid, callback) + } + + // Connect to the given peer + // Send the given msg (instance of Message) to the given peer + sendMessage (peer, msg, callback) { + if (!this._running) { return callback(new Error(`network isn't running`)) } + + const stringId = peer.toB58String() ? peer.toB58String() : peer.id.toB58String() + this._log('sendMessage to %s', stringId, msg) + + this._dialPeer(peer, (err, conn, protocol) => { + if (err) { + return callback(err) + } + + let serialized + switch (protocol) { + case BITSWAP100: + serialized = msg.serializeToBitswap100() + break + case BITSWAP110: + serialized = msg.serializeToBitswap110() + break + default: + return callback(new Error('Unkown protocol: ' + protocol)) + } + // TODO: why doesn't the error get propageted back?? + writeMessage(conn, serialized, (err) => { + if (err) { + this._log.error(err) + } + }) + callback() + this._updateSentStats(peer, msg.blocks) + }) + } + + connectTo (peer, callback) { + if (!this._running) { return callback(new Error(`network isn't running`)) } + + this.libp2p.dial(peer, callback) + } + + // Dial to the peer and try to use the most recent Bitswap + _dialPeer (peer, callback) { + // Attempt Bitswap 1.1.0 + this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => { + if (err) { + // Attempt Bitswap 1.0.0 + this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => { + if (err) { return callback(err) } + + callback(null, conn, BITSWAP100) + }) + + return + } + + callback(null, conn, BITSWAP110) + }) + } + + _updateSentStats (peer, blocks) { + const peerId = peer.toB58String() + if (this._stats) { + blocks.forEach((block) => this._stats.push(peerId, 'dataSent', block.data.length)) + this._stats.push(peerId, 'blocksSent', blocks.size) + } + } +} + +function writeMessage (conn, msg, callback) { + pull( + pull.values([msg]), + lp.encode(), + conn, + pull.onEnd(callback) + ) +} + +module.exports = Network + +},{"./constants":336,"./types/message":345,"./utils":349,"async/each":56,"async/nextTick":90,"async/waterfall":102,"pull-length-prefixed":1292,"pull-stream":1311}],341:[function(require,module,exports){ +'use strict' + +const EventEmitter = require('events').EventEmitter + +const CONSTANTS = require('./constants') +const logger = require('./utils').logger + +const unwantEvent = (c) => `unwant:${c}` +const blockEvent = (c) => `block:${c}` + +/** + * Internal module used to track events about incoming blocks, + * wants and unwants. + * + * @param {PeerId} peerId + * @private + */ +class Notifications extends EventEmitter { + constructor (peerId) { + super() + + this.setMaxListeners(CONSTANTS.maxListeners) + + this._log = logger(peerId, 'notif') + + this._unwantListeners = {} + this._blockListeners = {} + } + + /** + * Signal the system that we received `block`. + * + * @param {Block} block + * @return {void} + */ + hasBlock (block) { + const cidStr = block.cid.toString('base58btc') + const str = `block:${cidStr}` + this._log(str) + this.emit(str, block) + } + + /** + * Signal the system that we are waiting to receive the + * block associated with the given `cid`. + * + * @param {CID} cid + * @param {function(Block)} onBlock - called when the block is received + * @param {function()} onUnwant - called when the block is unwanted + * @returns {void} + */ + wantBlock (cid, onBlock, onUnwant) { + const cidStr = cid.toString('base58btc') + this._log(`wantBlock:${cidStr}`) + + this._unwantListeners[cidStr] = () => { + this._log(`manual unwant: ${cidStr}`) + this._cleanup(cidStr) + onUnwant() + } + + this._blockListeners[cidStr] = (block) => { + this._cleanup(cidStr) + onBlock(block) + } + + this.once( + unwantEvent(cidStr), + this._unwantListeners[cidStr] + ) + this.once( + blockEvent(cidStr), + this._blockListeners[cidStr] + ) + } + + /** + * Signal that the block is not wanted anymore. + * + * @param {CID} cid - the CID of the block that is not wanted anymore. + * @returns {void} + */ + unwantBlock (cid) { + const str = `unwant:${cid.toString('base58btc')}` + this._log(str) + this.emit(str) + } + + /** + * Internal method to clean up once a block was received or unwanted. + * + * @private + * @param {string} cidStr + * @returns {void} + */ + _cleanup (cidStr) { + if (this._unwantListeners[cidStr]) { + this.removeListener( + unwantEvent(cidStr), + this._unwantListeners[cidStr] + ) + delete this._unwantListeners[cidStr] + } + + if (this._blockListeners[cidStr]) { + this.removeListener( + blockEvent(cidStr), + this._blockListeners[cidStr] + ) + delete this._blockListeners[cidStr] + } + } +} + +module.exports = Notifications + +},{"./constants":336,"./utils":349,"events":272}],342:[function(require,module,exports){ +'use strict' + +const EventEmitter = require('events') +const Stat = require('./stat') + +const defaultOptions = { + movingAverageIntervals: [ + 60 * 1000, // 1 minute + 5 * 60 * 1000, // 5 minutes + 15 * 60 * 1000 // 15 minutes + ] +} + +class Stats extends EventEmitter { + constructor (initialCounters, _options) { + super() + + const options = Object.assign({}, defaultOptions, _options) + + if (typeof options.computeThrottleTimeout !== 'number') { + throw new Error('need computeThrottleTimeout') + } + + if (typeof options.computeThrottleMaxQueueSize !== 'number') { + throw new Error('need computeThrottleMaxQueueSize') + } + + this._initialCounters = initialCounters + this._options = options + this._enabled = this._options.enabled + + this._global = new Stat(initialCounters, options) + this._global.on('update', (stats) => this.emit('update', stats)) + + this._peers = new Map() + } + + enable () { + this._enabled = true + this._options.enabled = true + this._global.enable() + } + + disable () { + this._enabled = false + this._options.enabled = false + this._global.disable() + } + + stop () { + this._enabled = false + this._global.stop() + for (let peerStat of this._peers) { + peerStat[1].stop() + } + } + + get snapshot () { + return this._global.snapshot + } + + get movingAverages () { + return this._global.movingAverages + } + + forPeer (peerId) { + if (peerId.toB58String) { + peerId = peerId.toB58String() + } + return this._peers.get(peerId) + } + + push (peer, counter, inc) { + if (this._enabled) { + this._global.push(counter, inc) + + if (peer) { + let peerStats = this._peers.get(peer) + if (!peerStats) { + peerStats = new Stat(this._initialCounters, this._options) + this._peers.set(peer, peerStats) + } + + peerStats.push(counter, inc) + } + } + } + + disconnected (peer) { + const peerId = peer.toB58String() + const peerStats = this._peers.get(peerId) + if (peerStats) { + peerStats.stop() + this._peers.delete(peerId) + } + } +} + +module.exports = Stats + +},{"./stat":343,"events":272}],343:[function(require,module,exports){ +'use strict' + +const EventEmitter = require('events') +const Big = require('bignumber.js') +const MovingAverage = require('moving-average') + +class Stats extends EventEmitter { + constructor (initialCounters, options) { + super() + + this._options = options + this._queue = [] + this._stats = {} + + this._frequencyLastTime = Date.now() + this._frequencyAccumulators = {} + this._movingAverages = {} + + this._update = this._update.bind(this) + + initialCounters.forEach((key) => { + this._stats[key] = Big(0) + this._movingAverages[key] = {} + this._options.movingAverageIntervals.forEach((interval) => { + const ma = this._movingAverages[key][interval] = MovingAverage(interval) + ma.push(this._frequencyLastTime, 0) + }) + }) + + this._enabled = this._options.enabled + } + + enable () { + this._enabled = true + } + + disable () { + this._disabled = true + } + + stop () { + if (this._timeout) { + clearTimeout(this._timeout) + } + } + + get snapshot () { + return Object.assign({}, this._stats) + } + + get movingAverages () { + return Object.assign({}, this._movingAverages) + } + + push (counter, inc) { + if (this._enabled) { + this._queue.push([counter, inc, Date.now()]) + this._resetComputeTimeout() + } + } + + _resetComputeTimeout () { + if (this._timeout) { + clearTimeout(this._timeout) + } + this._timeout = setTimeout(this._update, this._nextTimeout()) + } + + _nextTimeout () { + // calculate the need for an update, depending on the queue length + const urgency = this._queue.length / this._options.computeThrottleMaxQueueSize + return Math.max(this._options.computeThrottleTimeout * (1 - urgency), 0) + } + + _update () { + this._timeout = null + if (this._queue.length) { + let last + while (this._queue.length) { + const op = last = this._queue.shift() + this._applyOp(op) + } + + this._updateFrequency(last[2]) // contains timestamp of last op + + this.emit('update', this._stats) + } + } + + _updateFrequency (latestTime) { + const timeDiff = latestTime - this._frequencyLastTime + + Object.keys(this._stats).forEach((key) => { + this._updateFrequencyFor(key, timeDiff, latestTime) + }) + + this._frequencyLastTime = latestTime + } + + _updateFrequencyFor (key, timeDiffMS, latestTime) { + const count = this._frequencyAccumulators[key] || 0 + this._frequencyAccumulators[key] = 0 + const hz = (count / timeDiffMS) * 1000 + + let movingAverages = this._movingAverages[key] + if (!movingAverages) { + movingAverages = this._movingAverages[key] = {} + } + this._options.movingAverageIntervals.forEach((movingAverageInterval) => { + let movingAverage = movingAverages[movingAverageInterval] + if (!movingAverage) { + movingAverage = movingAverages[movingAverageInterval] = MovingAverage(movingAverageInterval) + } + movingAverage.push(latestTime, hz) + }) + } + + _applyOp (op) { + const key = op[0] + const inc = op[1] + + if (typeof inc !== 'number') { + throw new Error('invalid increment number:', inc) + } + + let n + + if (!this._stats.hasOwnProperty(key)) { + n = this._stats[key] = Big(0) + } else { + n = this._stats[key] + } + this._stats[key] = n.plus(inc) + + if (!this._frequencyAccumulators[key]) { + this._frequencyAccumulators[key] = 0 + } + this._frequencyAccumulators[key] += inc + } +} + +module.exports = Stats + +},{"bignumber.js":328,"events":272,"moving-average":1135}],344:[function(require,module,exports){ +'use strict' + +const WantlistEntry = require('../wantlist').Entry +const CID = require('cids') +const assert = require('assert') + +module.exports = class BitswapMessageEntry { + constructor (cid, priority, cancel) { + assert(CID.isCID(cid), 'needs valid cid') + this.entry = new WantlistEntry(cid, priority) + this.cancel = Boolean(cancel) + } + + get cid () { + return this.entry.cid + } + + set cid (cid) { + this.entry.cid = cid + } + + get priority () { + return this.entry.priority + } + + set priority (val) { + this.entry.priority = val + } + + get [Symbol.toStringTag] () { + const cidStr = this.cid.toString('base58btc') + return `BitswapMessageEntry ${cidStr} ` + } + + equals (other) { + return (this.cancel === other.cancel) && + this.entry.equals(other.entry) + } +} + +},{"../wantlist":348,"assert":26,"cids":185}],345:[function(require,module,exports){ +'use strict' + +const protons = require('protons') +const Block = require('ipfs-block') +const isEqualWith = require('lodash.isequalwith') +const assert = require('assert') +const each = require('async/each') +const nextTick = require('async/nextTick') +const CID = require('cids') +const codecName = require('multicodec/src/name-table') +const vd = require('varint-decoder') +const multihashing = require('multihashing-async') + +const pbm = protons(require('./message.proto')) +const Entry = require('./entry') + +class BitswapMessage { + constructor (full) { + this.full = full + this.wantlist = new Map() + this.blocks = new Map() + } + + get empty () { + return this.blocks.size === 0 && + this.wantlist.size === 0 + } + + addEntry (cid, priority, cancel) { + assert(cid && CID.isCID(cid), 'must be a valid cid') + const cidStr = cid.toString('base58btc') + + const entry = this.wantlist.get(cidStr) + + if (entry) { + entry.priority = priority + entry.cancel = Boolean(cancel) + } else { + this.wantlist.set(cidStr, new Entry(cid, priority, cancel)) + } + } + + addBlock (block) { + assert(Block.isBlock(block), 'must be a valid cid') + const cidStr = block.cid.toString('base58btc') + this.blocks.set(cidStr, block) + } + + cancel (cid) { + assert(CID.isCID(cid), 'must be a valid cid') + const cidStr = cid.toString('base58btc') + this.wantlist.delete(cidStr) + this.addEntry(cid, 0, true) + } + + /* + * Serializes to Bitswap Message protobuf of + * version 1.0.0 + */ + serializeToBitswap100 () { + const msg = { + wantlist: { + entries: Array.from(this.wantlist.values()).map((entry) => { + return { + block: entry.cid.buffer, // cid + priority: Number(entry.priority), + cancel: Boolean(entry.cancel) + } + }) + }, + blocks: Array.from(this.blocks.values()) + .map((block) => block.data) + } + + if (this.full) { + msg.wantlist.full = true + } + + return pbm.Message.encode(msg) + } + + /* + * Serializes to Bitswap Message protobuf of + * version 1.1.0 + */ + serializeToBitswap110 () { + const msg = { + wantlist: { + entries: Array.from(this.wantlist.values()).map((entry) => { + return { + block: entry.cid.buffer, // cid + priority: Number(entry.priority), + cancel: Boolean(entry.cancel) + } + }) + }, + payload: [] + } + + if (this.full) { + msg.wantlist.full = true + } + + this.blocks.forEach((block) => { + msg.payload.push({ + prefix: block.cid.prefix, + data: block.data + }) + }) + + return pbm.Message.encode(msg) + } + + equals (other) { + const cmp = (a, b) => { + if (a.equals && typeof a.equals === 'function') { + return a.equals(b) + } + } + + if (this.full !== other.full || + !isEqualWith(this.wantlist, other.wantlist, cmp) || + !isEqualWith(this.blocks, other.blocks, cmp) + ) { + return false + } + + return true + } + + get [Symbol.toStringTag] () { + const list = Array.from(this.wantlist.keys()) + const blocks = Array.from(this.blocks.keys()) + return `BitswapMessage ` + } +} + +BitswapMessage.deserialize = (raw, callback) => { + let decoded + try { + decoded = pbm.Message.decode(raw) + } catch (err) { + return nextTick(() => callback(err)) + } + + const isFull = (decoded.wantlist && decoded.wantlist.full) || false + const msg = new BitswapMessage(isFull) + + if (decoded.wantlist) { + decoded.wantlist.entries.forEach((entry) => { + // note: entry.block is the CID here + let cid + try { + cid = new CID(entry.block) + } catch (err) { + return callback(err) + } + msg.addEntry(cid, entry.priority, entry.cancel) + }) + } + + // Bitswap 1.0.0 + // decoded.blocks are just the byte arrays + if (decoded.blocks.length > 0) { + return each(decoded.blocks, (b, cb) => { + multihashing(b, 'sha2-256', (err, hash) => { + if (err) { + return cb(err) + } + let cid + try { + cid = new CID(hash) + } catch (err) { + return callback(err) + } + msg.addBlock(new Block(b, cid)) + cb() + }) + }, (err) => { + if (err) { + return callback(err) + } + callback(null, msg) + }) + } + + // Bitswap 1.1.0 + if (decoded.payload.length > 0) { + return each(decoded.payload, (p, cb) => { + if (!p.prefix || !p.data) { + return nextTick(cb) + } + const values = vd(p.prefix) + const cidVersion = values[0] + const multicodec = values[1] + const hashAlg = values[2] + // const hashLen = values[3] // We haven't need to use this so far + multihashing(p.data, hashAlg, (err, hash) => { + if (err) { + return cb(err) + } + + let cid + try { + cid = new CID(cidVersion, codecName[multicodec.toString('16')], hash) + } catch (err) { + return cb(err) + } + + msg.addBlock(new Block(p.data, cid)) + cb() + }) + }, (err) => { + if (err) { + return callback(err) + } + callback(null, msg) + }) + } + + callback(null, msg) +} + +BitswapMessage.Entry = Entry +module.exports = BitswapMessage + +},{"./entry":344,"./message.proto":346,"assert":26,"async/each":56,"async/nextTick":90,"cids":185,"ipfs-block":353,"lodash.isequalwith":1043,"multicodec/src/name-table":1152,"multihashing-async":334,"protons":1274,"varint-decoder":1518}],346:[function(require,module,exports){ +'use strict' + +// from: https://github.com/ipfs/go-ipfs/blob/master/exchange/bitswap/message/pb/message.proto + +module.exports = ` + message Message { + message Wantlist { + message Entry { + // changed from string to bytes, it makes a difference in JavaScript + optional bytes block = 1; // the block cid (cidV0 in bitswap 1.0.0, cidV1 in bitswap 1.1.0) + optional int32 priority = 2; // the priority (normalized). default to 1 + optional bool cancel = 3; // whether this revokes an entry + } + + repeated Entry entries = 1; // a list of wantlist entries + optional bool full = 2; // whether this is the full wantlist. default to false + } + + message Block { + optional bytes prefix = 1; // CID prefix (cid version, multicodec and multihash prefix (type + length) + optional bytes data = 2; + } + + optional Wantlist wantlist = 1; + repeated bytes blocks = 2; // used to send Blocks in bitswap 1.0.0 + repeated Block payload = 3; // used to send Blocks in bitswap 1.1.0 + } +` + +},{}],347:[function(require,module,exports){ +'use strict' + +const assert = require('assert') +const CID = require('cids') + +class WantListEntry { + constructor (cid, priority) { + assert(CID.isCID(cid), 'must be valid CID') + + // Keep track of how many requests we have for this key + this._refCounter = 1 + + this.cid = cid + this.priority = priority || 1 + } + + inc () { + this._refCounter += 1 + } + + dec () { + this._refCounter = Math.max(0, this._refCounter - 1) + } + + hasRefs () { + return this._refCounter > 0 + } + + // So that console.log prints a nice description of this object + get [Symbol.toStringTag] () { + const cidStr = this.cid.toString('base58btc') + return `WantlistEntry ` + } + + equals (other) { + return (this._refCounter === other._refCounter) && + this.cid.equals(other.cid) && + this.priority === other.priority + } +} + +module.exports = WantListEntry + +},{"assert":26,"cids":185}],348:[function(require,module,exports){ +'use strict' + +const { sortBy } = require('../../utils') +const Entry = require('./entry') + +class Wantlist { + constructor (stats) { + this.set = new Map() + this._stats = stats + } + + get length () { + return this.set.size + } + + add (cid, priority) { + const cidStr = cid.toString('base58btc') + const entry = this.set.get(cidStr) + + if (entry) { + entry.inc() + entry.priority = priority + } else { + this.set.set(cidStr, new Entry(cid, priority)) + if (this._stats) { + this._stats.push(null, 'wantListSize', 1) + } + } + } + + remove (cid) { + const cidStr = cid.toString('base58btc') + const entry = this.set.get(cidStr) + + if (!entry) { + return + } + + entry.dec() + + // only delete when no refs are held + if (entry.hasRefs()) { + return + } + + this.set.delete(cidStr) + if (this._stats) { + this._stats.push(null, 'wantListSize', -1) + } + } + + removeForce (cidStr) { + if (this.set.has(cidStr)) { + this.set.delete(cidStr) + } + } + + forEach (fn) { + return this.set.forEach(fn) + } + + entries () { + return this.set.entries() + } + + sortedEntries () { + return new Map(sortBy(o => o[1].key, Array.from(this.set.entries()))) + } + + contains (cid) { + const cidStr = cid.toString('base58btc') + return this.set.get(cidStr) + } +} + +Wantlist.Entry = Entry +module.exports = Wantlist + +},{"../../utils":349,"./entry":347}],349:[function(require,module,exports){ +'use strict' + +const debug = require('debug') + +/** + * Creates a logger for the given subsystem + * + * @param {PeerId} [id] + * @param {string} [subsystem] + * @returns {debug} + * + * @private + */ +const logger = (id, subsystem) => { + const name = ['bitswap'] + if (subsystem) { + name.push(subsystem) + } + if (id) { + name.push(`${id.toB58String().slice(0, 8)}`) + } + const logger = debug(name.join(':')) + logger.error = debug(name.concat(['error']).join(':')) + + return logger +} + +const includesWith = (pred, x, list) => { + let idx = 0 + const len = list.length + while (idx < len) { + if (pred(x, list[idx])) { + return true + } + idx += 1 + } + return false +} + +const uniqWith = (pred, list) => { + let idx = 0 + const len = list.length + const result = [] + let item + + while (idx < len) { + item = list[idx] + if (!includesWith(pred, item, result)) { + result[result.length] = item + } + idx += 1 + } + return result +} + +const groupBy = (pred, list) => { + return list.reduce((acc, v) => { + const k = pred(v) + + if (acc[k]) { + acc[k].push(v) + } else { + acc[k] = [v] + } + return acc + }, {}) +} + +const pullAllWith = (pred, list, values) => { + return list.filter(i => { + return !includesWith(pred, i, values) + }) +} + +const sortBy = (fn, list) => { + return Array.prototype.slice.call(list, 0).sort((a, b) => { + const aa = fn(a) + const bb = fn(b) + return aa < bb ? -1 : aa > bb ? 1 : 0 + }) +} + +module.exports = { + logger, + includesWith, + uniqWith, + groupBy, + pullAllWith, + sortBy +} + +},{"debug":329}],350:[function(require,module,exports){ +'use strict' + +const nextTick = require('async/nextTick') +const Message = require('../types/message') +const Wantlist = require('../types/wantlist') +const CONSTANTS = require('../constants') +const MsgQueue = require('./msg-queue') +const logger = require('../utils').logger + +module.exports = class WantManager { + constructor (peerId, network, stats) { + this.peers = new Map() + this.wantlist = new Wantlist(stats) + + this.network = network + this._stats = stats + + this._peerId = peerId + this._log = logger(peerId, 'want') + } + + _addEntries (cids, cancel, force) { + const entries = cids.map((cid, i) => { + return new Message.Entry(cid, CONSTANTS.kMaxPriority - i, cancel) + }) + + entries.forEach((e) => { + // add changes to our wantlist + if (e.cancel) { + if (force) { + this.wantlist.removeForce(e.cid) + } else { + this.wantlist.remove(e.cid) + } + } else { + this._log('adding to wl') + this.wantlist.add(e.cid, e.priority) + } + }) + + // broadcast changes + for (let p of this.peers.values()) { + p.addEntries(entries) + } + } + + _startPeerHandler (peerId) { + let mq = this.peers.get(peerId.toB58String()) + + if (mq) { + mq.refcnt++ + return + } + + mq = new MsgQueue(this._peerId, peerId, this.network) + + // new peer, give them the full wantlist + const fullwantlist = new Message(true) + + for (let entry of this.wantlist.entries()) { + fullwantlist.addEntry(entry[1].cid, entry[1].priority) + } + + mq.addMessage(fullwantlist) + + this.peers.set(peerId.toB58String(), mq) + return mq + } + + _stopPeerHandler (peerId) { + const mq = this.peers.get(peerId.toB58String()) + + if (!mq) { + return + } + + mq.refcnt-- + if (mq.refcnt > 0) { + return + } + + this.peers.delete(peerId.toB58String()) + } + + // add all the cids to the wantlist + wantBlocks (cids) { + this._addEntries(cids, false) + } + + // remove blocks of all the given keys without respecting refcounts + unwantBlocks (cids) { + this._log('unwant blocks: %s', cids.length) + this._addEntries(cids, true, true) + } + + // cancel wanting all of the given keys + cancelWants (cids) { + this._log('cancel wants: %s', cids.length) + this._addEntries(cids, true) + } + + // Returns a list of all currently connected peers + connectedPeers () { + return Array.from(this.peers.keys()) + } + + connected (peerId) { + this._startPeerHandler(peerId) + } + + disconnected (peerId) { + this._stopPeerHandler(peerId) + } + + start (callback) { + // resend entire wantlist every so often + this.timer = setInterval(() => { + this._log('resend full-wantlist') + const fullwantlist = new Message(true) + this.wantlist.forEach((entry) => { + fullwantlist.addEntry(entry.cid, entry.priority) + }) + + this.peers.forEach((p) => p.addMessage(fullwantlist)) + }, 60 * 1000) + + nextTick(() => callback()) + } + + stop (callback) { + this.peers.forEach((mq) => this.disconnected(mq.peerId)) + + clearInterval(this.timer) + nextTick(() => callback()) + } +} + +},{"../constants":336,"../types/message":345,"../types/wantlist":348,"../utils":349,"./msg-queue":351,"async/nextTick":90}],351:[function(require,module,exports){ +'use strict' + +const debounce = require('just-debounce-it') + +const Message = require('../types/message') +const logger = require('../utils').logger + +module.exports = class MsgQueue { + constructor (selfPeerId, otherPeerId, network) { + this.peerId = otherPeerId + this.network = network + this.refcnt = 1 + + this._entries = [] + this._log = logger(selfPeerId, 'msgqueue', otherPeerId.toB58String().slice(0, 8)) + this.sendEntries = debounce(this._sendEntries.bind(this), 200) + } + + addMessage (msg) { + if (msg.empty) { + return + } + + this.send(msg) + } + + addEntries (entries) { + this._entries = this._entries.concat(entries) + this.sendEntries() + } + + _sendEntries () { + if (!this._entries.length) { + return + } + + const msg = new Message(false) + this._entries.forEach((entry) => { + if (entry.cancel) { + msg.cancel(entry.cid) + } else { + msg.addEntry(entry.cid, entry.priority) + } + }) + this._entries = [] + this.addMessage(msg) + } + + send (msg) { + this.network.connectTo(this.peerId, (err) => { + if (err) { + this._log.error('cant connect to peer %s: %s', this.peerId.toB58String(), err.message) + return + } + + this._log('sending message') + this.network.sendMessage(this.peerId, msg, (err) => { + if (err) { + this._log.error('send error: %s', err.message) + } + }) + }) + } +} + +},{"../types/message":345,"../utils":349,"just-debounce-it":668}],352:[function(require,module,exports){ +'use strict' + +const asyncMap = require('async/map') + +/** + * BlockService is a hybrid block datastore. It stores data in a local + * datastore and may retrieve data from a remote Exchange. + * It uses an internal `datastore.Datastore` instance to store values. + */ +class BlockService { + /** + * Create a new BlockService + * + * @param {IPFSRepo} ipfsRepo + */ + constructor (ipfsRepo) { + this._repo = ipfsRepo + this._bitswap = null + } + + /** + * Add a bitswap instance that communicates with the + * network to retreive blocks that are not in the local store. + * + * If the node is online all requests for blocks first + * check locally and afterwards ask the network for the blocks. + * + * @param {Bitswap} bitswap + * @returns {void} + */ + setExchange (bitswap) { + this._bitswap = bitswap + } + + /** + * Go offline, i.e. drop the reference to bitswap. + * + * @returns {void} + */ + unsetExchange () { + this._bitswap = null + } + + /** + * Is the blockservice online, i.e. is bitswap present. + * + * @returns {bool} + */ + hasExchange () { + return this._bitswap != null + } + + /** + * Put a block to the underlying datastore. + * + * @param {Block} block + * @param {function(Error)} callback + * @returns {void} + */ + put (block, callback) { + if (this.hasExchange()) { + this._bitswap.put(block, callback) + } else { + this._repo.blocks.put(block, callback) + } + } + + /** + * Put a multiple blocks to the underlying datastore. + * + * @param {Array} blocks + * @param {function(Error)} callback + * @returns {void} + */ + putMany (blocks, callback) { + if (this.hasExchange()) { + this._bitswap.putMany(blocks, callback) + } else { + this._repo.blocks.putMany(blocks, callback) + } + } + + /** + * Get a block by cid. + * + * @param {CID} cid + * @param {function(Error, Block)} callback + * @returns {void} + */ + get (cid, callback) { + if (this.hasExchange()) { + this._bitswap.get(cid, callback) + } else { + this._repo.blocks.get(cid, callback) + } + } + + /** + * Get multiple blocks back from an array of cids. + * + * @param {Array} cids + * @param {function(Error, Block)} callback + * @returns {void} + */ + getMany (cids, callback) { + if (!Array.isArray(cids)) { + callback(new Error('first arg must be an array of cids')) + } else if (this.hasExchange()) { + this._bitswap.getMany(cids, callback) + } else { + asyncMap(cids, (cid, cb) => this._repo.blocks.get(cid, cb), callback) + } + } + + /** + * Delete a block from the blockstore. + * + * @param {CID} cid + * @param {function(Error)} callback + * @return {void} + */ + delete (cid, callback) { + this._repo.blocks.delete(cid, callback) + } +} + +module.exports = BlockService + +},{"async/map":87}],353:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') +const withIs = require('class-is') + +/** + * Represents an immutable block of data that is uniquely referenced with a cid. + * + * @constructor + * @param {Buffer} data - The data to be stored in the block as a buffer. + * @param {CID} cid - The cid of the data + * + * @example + * const block = new Block(new Buffer('a012d83b20f9371...')) + */ +class Block { + constructor (data, cid) { + if (!data || !Buffer.isBuffer(data)) { + throw new Error('first argument must be a buffer') + } + + if (!cid || !CID.isCID(cid)) { + throw new Error('second argument must be a CID') + } + + this._data = data + this._cid = cid + } + + /** + * The data of this block. + * + * @type {Buffer} + */ + get data () { + return this._data + } + + set data (val) { + throw new Error('Tried to change an immutable block') + } + + /** + * The cid of the data this block represents. + * + * @type {CID} + */ + get cid () { + return this._cid + } + + set cid (val) { + throw new Error('Tried to change an immutable block') + } +} + +module.exports = withIs(Block, { className: 'Block', symbolName: '@ipfs/js-ipfs-block/block' }) + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608,"cids":185,"class-is":187}],354:[function(require,module,exports){ +'use strict' + +module.exports = require('./src/core') + +},{"./src/core":360}],355:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":356,"_process":1258,"dup":208}],356:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],357:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],358:[function(require,module,exports){ +'use strict' + +const mkdir = require('./mkdir') +const stat = require('./stat') +const log = require('debug')('ipfs:mfs:cp') +const errCode = require('err-code') +const updateTree = require('./utils/update-tree') +const updateMfsRoot = require('./utils/update-mfs-root') +const addLink = require('./utils/add-link') +const applyDefaultOptions = require('./utils/apply-default-options') +const toMfsPath = require('./utils/to-mfs-path') +const toSourcesAndDestination = require('./utils/to-sources-and-destination') +const toTrail = require('./utils/to-trail') + +const defaultOptions = { + parents: false, + flush: true, + format: 'dag-pb', + hashAlg: 'sha2-256', + cidVersion: 0, + shardSplitThreshold: 1000 +} + +module.exports = (context) => { + return async function mfsCp (...args) { + const options = applyDefaultOptions(args, defaultOptions) + let { + sources, destination + } = await toSourcesAndDestination(context, args) + + if (!sources.length) { + throw errCode(new Error('Please supply at least one source'), 'ERR_INVALID_PARAMS') + } + + if (!destination) { + throw errCode(new Error('Please supply a destination'), 'ERR_INVALID_PARAMS') + } + + options.parents = options.p || options.parents + + // make sure all sources exist + const missing = sources.find(source => !source.exists) + + if (missing) { + throw errCode(new Error(`${missing.path} does not exist`), 'ERR_INVALID_PARAMS') + } + + const destinationIsDirectory = isDirectory(destination) + + if (destination.exists) { + log('Destination exists') + + if (sources.length === 1 && !destinationIsDirectory) { + throw errCode(new Error('directory already has entry by that name'), 'ERR_ALREADY_EXISTS') + } + } else { + log('Destination does not exist') + + if (sources.length > 1) { + // copying multiple files to one location, destination will be a directory + if (!options.parents) { + throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS') + } + + await mkdir(context)(destination.path, options) + destination = await toMfsPath(context, destination.path) + } else if (destination.parts.length > 1) { + // copying to a folder, create it if necessary + const parentFolder = `/${destination.parts.slice(0, -1).join('/')}` + + try { + await stat(context)(parentFolder, options) + } catch (err) { + if (err.code !== 'ERR_NOT_FOUND') { + throw err + } + + if (!options.parents) { + throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS') + } + + await mkdir(context)(parentFolder, options) + destination = await toMfsPath(context, destination.path) + } + } + } + + const destinationPath = isDirectory(destination) ? destination.mfsPath : destination.mfsDirectory + const trail = await toTrail(context, destinationPath, options) + + if (sources.length === 1) { + const source = sources.pop() + const destinationName = destinationIsDirectory ? source.name : destination.name + + log(`Only one source, copying to destination ${destinationIsDirectory ? 'directory' : 'file'} ${destinationName}`) + + return copyToFile(context, source, destinationName, trail, options) + } + + log('Multiple sources, wrapping in a directory') + return copyToDirectory(context, sources, destination, trail, options) + } +} + +const isDirectory = (destination) => { + return destination.unixfs && + destination.unixfs.type && + destination.unixfs.type.includes('directory') +} + +const copyToFile = async (context, source, destination, destinationTrail, options) => { + let parent = destinationTrail.pop() + + parent = await addSourceToParent(context, source, destination, parent, options) + + // update the tree with the new containg directory + destinationTrail.push(parent) + + const newRootCid = await updateTree(context, destinationTrail, options) + + // Update the MFS record with the new CID for the root of the tree + await updateMfsRoot(context, newRootCid) +} + +const copyToDirectory = async (context, sources, destination, destinationTrail, options) => { + // copy all the sources to the destination + for (let i = 0; i < sources.length; i++) { + const source = sources[i] + + destination = await addSourceToParent(context, source, source.name, destination, options) + } + + // update the tree with the new containg directory + destinationTrail[destinationTrail.length - 1] = destination + + const newRootCid = await updateTree(context, destinationTrail, options) + + // Update the MFS record with the new CID for the root of the tree + await updateMfsRoot(context, newRootCid) +} + +const addSourceToParent = async (context, source, childName, parent, options) => { + const sourceBlock = await context.repo.blocks.get(source.cid) + + const { + node, + cid + } = await addLink(context, { + parentCid: parent.cid, + size: sourceBlock.data.length, + cid: source.cid, + name: childName, + format: options.format, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion + }) + + parent.node = node + parent.cid = cid + parent.size = node.size + + return parent +} + +},{"./mkdir":362,"./stat":366,"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"./utils/to-sources-and-destination":377,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"debug":355,"err-code":357}],359:[function(require,module,exports){ +'use strict' + +const applyDefaultOptions = require('./utils/apply-default-options') +const stat = require('./stat') +const { + FILE_SEPARATOR +} = require('./utils/constants') + +const defaultOptions = {} + +module.exports = (context) => { + return async function mfsFlush (path = FILE_SEPARATOR, options = defaultOptions) { + options = applyDefaultOptions(options, defaultOptions) + + await stat(context)(path, options) + } +} + +},{"./stat":366,"./utils/apply-default-options":368,"./utils/constants":369}],360:[function(require,module,exports){ +'use strict' + +const assert = require('assert') +const promisify = require('promisify-es6') +const createLock = require('./utils/create-lock') + +// These operations are read-locked at the function level and will execute simultaneously +const readOperations = { + stat: require('./stat') +} + +// These operations are locked at the function level and will execute in series +const writeOperations = { + cp: require('./cp'), + flush: require('./flush'), + mkdir: require('./mkdir'), + mv: require('./mv'), + rm: require('./rm') +} + +// These operations are asynchronous and manage their own locking +const unwrappedOperations = { + write: require('./write'), + read: require('./read'), + ls: require('./ls') +} + +const wrap = ({ + options, mfs, operations, lock +}) => { + Object.keys(operations).forEach(key => { + mfs[key] = lock(operations[key](options)) + }) +} + +const defaultOptions = { + repoOwner: true, + ipld: null, + repo: null +} + +module.exports = (options) => { + const { + repoOwner + } = Object.assign({}, defaultOptions || {}, options) + + assert(options.ipld, 'MFS requires an IPLD instance') + assert(options.blocks, 'MFS requires an BlockStore instance') + assert(options.datastore, 'MFS requires a DataStore instance') + + // should be able to remove this when async/await PRs are in for datastore, blockstore & repo + options.repo = { + blocks: { + get: promisify(options.blocks.get, { + context: options.blocks + }) + }, + datastore: { + open: promisify(options.datastore.open, { + context: options.datastore + }), + get: promisify(options.datastore.get, { + context: options.datastore + }), + put: promisify(options.datastore.put, { + context: options.datastore + }) + } + } + + const lock = createLock(repoOwner) + + const readLock = (operation) => { + return lock.readLock(operation) + } + + const writeLock = (operation) => { + return lock.writeLock(operation) + } + + const mfs = {} + + wrap({ + options, mfs, operations: readOperations, lock: readLock + }) + wrap({ + options, mfs, operations: writeOperations, lock: writeLock + }) + + Object.keys(unwrappedOperations).forEach(key => { + mfs[key] = unwrappedOperations[key](options) + }) + + return mfs +} + +},{"./cp":358,"./flush":359,"./ls":361,"./mkdir":362,"./mv":363,"./read":364,"./rm":365,"./stat":366,"./utils/create-lock":370,"./write":383,"assert":26,"promisify-es6":1263}],361:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const applyDefaultOptions = require('./utils/apply-default-options') +const toMfsPath = require('./utils/to-mfs-path') +const { + FILE_SEPARATOR, + FILE_TYPES +} = require('./utils/constants') + +const defaultOptions = { + +} + +const toOutput = (fsEntry) => { + let type = 0 + let size = fsEntry.node.size || fsEntry.node.length + + if (fsEntry.unixfs) { + size = fsEntry.unixfs.fileSize() + type = FILE_TYPES[fsEntry.unixfs.type] + } + + return { + cid: fsEntry.cid, + name: fsEntry.name, + type, + size + } +} + +module.exports = (context) => { + return async function * mfsLs (path = FILE_SEPARATOR, options = {}) { + if (typeof path === 'object' && !(path instanceof String)) { + options = path + path = FILE_SEPARATOR + } + + options = applyDefaultOptions(options, defaultOptions) + + const mfsPath = await toMfsPath(context, path) + const fsDir = await exporter(mfsPath.mfsPath, context.ipld) + + // single file/node + if (!fsDir.unixfs || !fsDir.unixfs.type.includes('directory')) { + yield toOutput(fsDir) + + return + } + + // directory, perhaps sharded + for await (const fsEntry of fsDir.content(options)) { + yield toOutput(fsEntry) + } + } +} + +},{"./utils/apply-default-options":368,"./utils/constants":369,"./utils/to-mfs-path":375,"ipfs-unixfs-exporter":400}],362:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const log = require('debug')('ipfs:mfs:mkdir') +const exporter = require('ipfs-unixfs-exporter') +const createNode = require('./utils/create-node') +const toPathComponents = require('./utils/to-path-components') +const updateMfsRoot = require('./utils/update-mfs-root') +const updateTree = require('./utils/update-tree') +const addLink = require('./utils/add-link') +const withMfsRoot = require('./utils/with-mfs-root') +const applyDefaultOptions = require('./utils/apply-default-options') +const { + FILE_SEPARATOR +} = require('./utils/constants') + +const defaultOptions = { + parents: false, + hashAlg: 'sha2-256', + cidVersion: 0, + shardSplitThreshold: 1000, + format: 'dag-pb', + flush: true +} + +module.exports = (context) => { + return async function mfsMkdir (path, options) { + options = applyDefaultOptions(options, defaultOptions) + + if (!path) { + throw new Error('no path given to Mkdir') + } + + path = path.trim() + + if (path === FILE_SEPARATOR) { + if (options.parents) { + return + } + + throw errCode(new Error(`cannot create directory '${FILE_SEPARATOR}': Already exists`), 'ERR_INVALID_PATH') + } + + if (path.substring(0, 1) !== FILE_SEPARATOR) { + throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH') + } + + log(`Creating ${path}`) + + const pathComponents = toPathComponents(path) + + if (pathComponents[0] === 'ipfs') { + throw errCode(new Error("path cannot have the prefix 'ipfs'"), 'ERR_INVALID_PATH') + } + + let root = await withMfsRoot(context) + let parent + let trail = [] + const emptyDir = await createNode(context, 'directory', options) + + // make sure the containing folder exists, creating it if necessary + for (let i = 0; i <= pathComponents.length; i++) { + const subPathComponents = pathComponents.slice(0, i) + const subPath = `/ipfs/${root}/${subPathComponents.join('/')}` + + try { + parent = await exporter(subPath, context.ipld) + log(`${subPath} existed`) + log(`${subPath} had children ${parent.node.Links.map(link => link.Name)}`) + + if (i === pathComponents.length) { + if (options.parents) { + return + } + + throw errCode(new Error('file already exists'), 'ERR_ALREADY_EXISTS') + } + + trail.push({ + name: parent.name, + cid: parent.cid + }) + } catch (err) { + if (err.code === 'ERR_NOT_FOUND') { + if (i < pathComponents.length && !options.parents) { + throw errCode(new Error(`Intermediate directory path ${subPath} does not exist, use the -p flag to create it`), 'ERR_NOT_FOUND') + } + + // add the intermediate directory + await addEmptyDir(context, subPathComponents[subPathComponents.length - 1], emptyDir, trail[trail.length - 1], trail, options) + } else { + throw err + } + } + } + + // add an empty dir to the last path component + // await addEmptyDir(context, pathComponents[pathComponents.length - 1], emptyDir, parent, trail) + + // update the tree from the leaf to the root + const newRootCid = await updateTree(context, trail, options) + + // Update the MFS record with the new CID for the root of the tree + await updateMfsRoot(context, newRootCid) + } +} + +const addEmptyDir = async (context, childName, emptyDir, parent, trail, options) => { + log(`Adding empty dir called ${childName} to ${parent.cid}`) + + const result = await addLink(context, { + parent: parent.node, + parentCid: parent.cid, + size: emptyDir.node.size, + cid: emptyDir.cid, + name: childName, + format: options.format, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion + }) + + trail[trail.length - 1].cid = result.cid + + trail.push({ + name: childName, + cid: emptyDir.cid + }) +} + +},{"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/constants":369,"./utils/create-node":371,"./utils/to-path-components":376,"./utils/update-mfs-root":380,"./utils/update-tree":381,"./utils/with-mfs-root":382,"debug":355,"err-code":357,"ipfs-unixfs-exporter":400}],363:[function(require,module,exports){ +'use strict' + +const applyDefaultOptions = require('./utils/apply-default-options') +const toSources = require('./utils/to-sources') +const cp = require('./cp') +const rm = require('./rm') + +const defaultOptions = { + parents: false, + recursive: false, + flush: true, + format: 'dag-pb', + hashAlg: 'sha2-256', + shardSplitThreshold: 1000 +} + +module.exports = (context) => { + return async function mfsMv (...args) { + if (Array.isArray(args[0])) { + args = args[0].concat(args.slice(1)) + } + + const { + sources + } = await toSources(context, args) + const options = applyDefaultOptions(args, defaultOptions) + + const cpArgs = sources + .map(source => source.path).concat(options) + + // remove the last source as it'll be the destination + const rmArgs = sources + .slice(0, -1) + .map(source => source.path) + .concat(Object.assign(options, { + recursive: true + })) + + await cp(context).apply(null, cpArgs) + await rm(context).apply(null, rmArgs) + } +} + +},{"./cp":358,"./rm":365,"./utils/apply-default-options":368,"./utils/to-sources":378}],364:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const applyDefaultOptions = require('./utils/apply-default-options') +const toMfsPath = require('./utils/to-mfs-path') +const errCode = require('err-code') + +const defaultOptions = { + offset: 0, + length: Infinity +} + +module.exports = (context) => { + return function mfsRead (path, options = {}) { + options = applyDefaultOptions(options, defaultOptions) + + return { + [Symbol.asyncIterator]: async function * read () { + const mfsPath = await toMfsPath(context, path) + const result = await exporter(mfsPath.mfsPath, context.ipld) + + if (result.unixfs.type !== 'file') { + throw errCode(new Error(`${path} was not a file`), 'ERR_NOT_FILE') + } + + if (!result.content) { + throw errCode(new Error(`Could not load content stream from ${path}`), 'ERR_NO_CONTENT') + } + + for await (const buf of result.content({ + offset: options.offset, + length: options.length + })) { + yield buf + } + } + } + } +} + +},{"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"err-code":357,"ipfs-unixfs-exporter":400}],365:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const updateTree = require('./utils/update-tree') +const updateMfsRoot = require('./utils/update-mfs-root') +const toSources = require('./utils/to-sources') +const removeLink = require('./utils/remove-link') +const toMfsPath = require('./utils/to-mfs-path') +const toTrail = require('./utils/to-trail') +const applyDefaultOptions = require('./utils/apply-default-options') +const { + FILE_SEPARATOR +} = require('./utils/constants') + +const defaultOptions = { + recursive: false, + cidVersion: 0, + hashAlg: 'sha2-256', + format: 'dag-pb', + flush: true +} + +module.exports = (context) => { + return async function mfsRm () { + const args = Array.from(arguments) + + const { + sources + } = await toSources(context, args, defaultOptions) + const options = applyDefaultOptions(args, defaultOptions) + + if (!sources.length) { + throw errCode(new Error('Please supply at least one path to remove'), 'ERR_INVALID_PARAMS') + } + + sources.forEach(source => { + if (source.path === FILE_SEPARATOR) { + throw errCode(new Error('Cannot delete root'), 'ERR_INVALID_PARAMS') + } + }) + + for (const source of sources) { + await removePath(context, source.path, options) + } + } +} + +const removePath = async (context, path, options) => { + const mfsPath = await toMfsPath(context, path) + const trail = await toTrail(context, mfsPath.mfsPath, options) + const child = trail.pop() + const parent = trail[trail.length - 1] + + if (!parent) { + throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND') + } + + if (child.type === 'directory' && !options.recursive) { + throw errCode(new Error(`${path} is a directory, use -r to remove directories`), 'ERR_WAS_DIR') + } + + const { + cid + } = await removeLink(context, { + parentCid: parent.cid, + name: child.name, + format: options.format, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion, + flush: options.flush + }) + + parent.cid = cid + + // update the tree with the new child + const newRootCid = await updateTree(context, trail, options) + + // Update the MFS record with the new CID for the root of the tree + await updateMfsRoot(context, newRootCid) +} + +},{"./utils/apply-default-options":368,"./utils/constants":369,"./utils/remove-link":373,"./utils/to-mfs-path":375,"./utils/to-sources":378,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"err-code":357}],366:[function(require,module,exports){ +'use strict' + +const applyDefaultOptions = require('./utils/apply-default-options') +const toMfsPath = require('./utils/to-mfs-path') +const exporter = require('ipfs-unixfs-exporter') +const log = require('debug')('ipfs:mfs:stat') +const errCode = require('err-code') + +const defaultOptions = { + withLocal: false +} + +module.exports = (context) => { + return async function mfsStat (path, options) { + options = applyDefaultOptions(options, defaultOptions) + + log(`Fetching stats for ${path}`) + + const { + type, + cid, + mfsPath + } = await toMfsPath(context, path) + + let exportPath = type === 'ipfs' && cid ? cid : mfsPath + let file + + try { + file = await exporter(exportPath, context.ipld) + } catch (err) { + if (err.code === 'ERR_NOT_FOUND') { + throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND') + } + + throw err + } + + if (!statters[file.cid.codec]) { + throw new Error(`Cannot stat codec ${file.cid.codec}`) + } + + return statters[file.cid.codec](file, options) + } +} + +const statters = { + raw: (file) => { + return { + cid: file.cid, + size: file.node.length, + cumulativeSize: file.node.length, + blocks: 0, + type: 'file', // for go compatibility + local: undefined, + sizeLocal: undefined, + withLocality: false + } + }, + 'dag-pb': (file) => { + let blocks = file.node.Links.length + let size = file.node.size + let cumulativeSize = file.node.size + let nodeType = null + + if (file.unixfs) { + size = file.unixfs.fileSize() + nodeType = file.unixfs.type + + if (nodeType.includes('directory')) { + size = 0 + cumulativeSize = file.node.size + } + + if (nodeType === 'file') { + blocks = file.unixfs.blockSizes.length + } + } + + return { + cid: file.cid, + size: size, + cumulativeSize: cumulativeSize, + blocks: blocks, + type: nodeType, + local: undefined, + sizeLocal: undefined, + withLocality: false + } + }, + 'dag-cbor': (file) => { + return { + cid: file.cid, + local: undefined, + sizeLocal: undefined, + withLocality: false + } + } +} + +},{"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"debug":355,"err-code":357,"ipfs-unixfs-exporter":400}],367:[function(require,module,exports){ +'use strict' + +const { + DAGNode, + DAGLink +} = require('ipld-dag-pb') +const CID = require('cids') +const log = require('debug')('ipfs:mfs:core:utils:add-link') +const UnixFS = require('ipfs-unixfs') +const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') +const { + updateHamtDirectory, + recreateHamtLevel, + createShard, + toPrefix, + addLinksToHamtBucket +} = require('./hamt-utils') +const errCode = require('err-code') +const mc = require('multicodec') +const mh = require('multihashes') +const last = require('async-iterator-last') + +const addLink = async (context, options) => { + if (!options.parentCid && !options.parent) { + throw errCode(new Error('No parent node or CID passed to addLink'), 'EINVALIDPARENT') + } + + if (options.parentCid && !CID.isCID(options.parentCid)) { + throw errCode(new Error('Invalid CID passed to addLink'), 'EINVALIDPARENTCID') + } + + if (!options.parent) { + log(`Loading parent node ${options.parentCid}`) + + options.parent = await context.ipld.get(options.parentCid) + } + + if (!options.cid) { + throw errCode(new Error('No child cid passed to addLink'), 'EINVALIDCHILDCID') + } + + if (!options.name) { + throw errCode(new Error('No child name passed to addLink'), 'EINVALIDCHILDNAME') + } + + if (!CID.isCID(options.cid)) { + options.cid = new CID(options.cid) + } + + if (!options.size && options.size !== 0) { + throw errCode(new Error('No child size passed to addLink'), 'EINVALIDCHILDSIZE') + } + + const meta = UnixFS.unmarshal(options.parent.Data) + + if (meta.type === 'hamt-sharded-directory') { + log('Adding link to sharded directory') + + return addToShardedDirectory(context, options) + } + + if (options.parent.Links.length >= options.shardSplitThreshold) { + log('Converting directory to sharded directory') + + return convertToShardedDirectory(context, options) + } + + log(`Adding ${options.name} (${options.cid}) to regular directory`) + + return addToDirectory(context, options) +} + +const convertToShardedDirectory = async (context, options) => { + const result = await createShard(context, options.parent.Links.map(link => ({ + name: link.Name, + size: link.Tsize, + cid: link.Hash + })).concat({ + name: options.name, + size: options.size, + cid: options.cid + }), options) + + log(`Converted directory to sharded directory ${result.cid}`) + + return result +} + +const addToDirectory = async (context, options) => { + let parent = await DAGNode.rmLink(options.parent, options.name) + parent = await DAGNode.addLink(parent, new DAGLink(options.name, options.size, options.cid)) + + const format = mc[options.format.toUpperCase().replace(/-/g, '_')] + const hashAlg = mh.names[options.hashAlg] + + // Persist the new parent DAGNode + const cid = await context.ipld.put(parent, format, { + cidVersion: options.cidVersion, + hashAlg, + hashOnly: !options.flush + }) + + return { + node: parent, + cid + } +} + +const addToShardedDirectory = async (context, options) => { + const { + shard, path + } = await addFileToShardedDirectory(context, options) + + const result = await last(shard.flush('', context.ipld)) + + // we have written out the shard, but only one sub-shard will have been written so replace it in the original shard + const oldLink = options.parent.Links + .find(link => link.Name.substring(0, 2) === path[0].prefix) + + const newLink = result.node.Links + .find(link => link.Name.substring(0, 2) === path[0].prefix) + + let parent = options.parent + + if (oldLink) { + parent = await DAGNode.rmLink(options.parent, oldLink.Name) + } + + parent = await DAGNode.addLink(parent, newLink) + + return updateHamtDirectory(context, parent.Links, path[0].bucket, options) +} + +const addFileToShardedDirectory = async (context, options) => { + const file = { + name: options.name, + cid: options.cid, + size: options.size + } + + // start at the root bucket and descend, loading nodes as we go + const rootBucket = await recreateHamtLevel(options.parent.Links) + + const shard = new DirSharded({ + root: true, + dir: true, + parent: null, + parentKey: null, + path: '', + dirty: true, + flat: false + }, options) + shard._bucket = rootBucket + + // load subshards until the bucket & position no longer changes + const position = await rootBucket._findNewBucketAndPos(file.name) + const path = toBucketPath(position) + path[0].node = options.parent + let index = 0 + + while (index < path.length) { + let segment = path[index] + index++ + let node = segment.node + + let link = node.Links + .find(link => link.Name.substring(0, 2) === segment.prefix) + + if (!link) { + // prefix is new, file will be added to the current bucket + log(`Link ${segment.prefix}${file.name} will be added`) + index = path.length + + break + } + + if (link.Name === `${segment.prefix}${file.name}`) { + // file already existed, file will be added to the current bucket + log(`Link ${segment.prefix}${file.name} will be replaced`) + index = path.length + + break + } + + if (link.Name.length > 2) { + // another file had the same prefix, will be replaced with a subshard + log(`Link ${link.Name} will be replaced with a subshard`) + index = path.length + + break + } + + // load sub-shard + log(`Found subshard ${segment.prefix}`) + const subShard = await context.ipld.get(link.Hash) + + // subshard hasn't been loaded, descend to the next level of the HAMT + if (!path[index]) { + log(`Loaded new subshard ${segment.prefix}`) + await recreateHamtLevel(subShard.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16)) + + const position = await rootBucket._findNewBucketAndPos(file.name) + + path.push({ + bucket: position.bucket, + prefix: toPrefix(position.pos), + node: subShard + }) + + break + } + + const nextSegment = path[index] + + // add next level's worth of links to bucket + await addLinksToHamtBucket(subShard.Links, nextSegment.bucket, rootBucket) + + nextSegment.node = subShard + } + + // finally add the new file into the shard + await shard._bucket.put(file.name, { + size: file.size, + cid: file.cid + }) + + return { + shard, path + } +} + +const toBucketPath = (position) => { + let bucket = position.bucket + let positionInBucket = position.pos + let path = [{ + bucket, + prefix: toPrefix(positionInBucket) + }] + + bucket = position.bucket._parent + positionInBucket = position.bucket._posAtParent + + while (bucket) { + path.push({ + bucket, + prefix: toPrefix(positionInBucket) + }) + + positionInBucket = bucket._posAtParent + bucket = bucket._parent + } + + path.reverse() + + return path +} + +module.exports = addLink + +},{"./hamt-utils":372,"async-iterator-last":33,"cids":185,"debug":355,"err-code":357,"ipfs-unixfs":435,"ipfs-unixfs-importer/src/dir-sharded":428,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],368:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') + +module.exports = (options = {}, defaults) => { + if (Array.isArray(options)) { + options = options.filter(arg => typeof arg === 'object').pop() || {} + } + + const output = {} + + for (let key in defaults) { + if (options[key] !== null && options[key] !== undefined) { + output[key] = options[key] + } else { + output[key] = defaults[key] + } + } + + const format = output.format || output.codec + + if (format && isNaN(format)) { + output.format = format + delete output.codec + } + + // support legacy go arguments + if (options.count !== undefined) { + output.length = options.count + } + + if (options.p !== undefined) { + output.parents = options.p + } + + if (options.l !== undefined) { + output.long = options.l + } + + if (!output.length && output.length !== 0) { + output.length = Infinity + } + + if (output.offset < 0) { + throw errCode(new Error('cannot have negative write offset'), 'ERR_INVALID_PARAMS') + } + + if (output.length < 0) { + throw errCode(new Error('cannot have negative byte count'), 'ERR_INVALID_PARAMS') + } + + return output +} + +},{"err-code":357}],369:[function(require,module,exports){ +'use strict' + +const Key = require('interface-datastore').Key + +const FILE_TYPES = { + file: 0, + directory: 1, + 'hamt-sharded-directory': 1 +} + +module.exports = { + FILE_SEPARATOR: '/', + MFS_ROOT_KEY: new Key('/local/filesroot'), + MAX_CHUNK_SIZE: 262144, + MAX_LINKS: 174, + FILE_TYPES +} + +},{"interface-datastore":322}],370:[function(require,module,exports){ +'use strict' + +const mortice = require('mortice') + +let lock + +module.exports = (repoOwner) => { + if (lock) { + return lock + } + + const mutex = mortice({ + // ordinarily the main thread would store the read/write lock but + // if we are the thread that owns the repo, we can store the lock + // on this process even if we are a worker thread + singleProcess: repoOwner + }) + + lock = { + readLock: (func) => { + return async (...args) => { + const releaseLock = await mutex.readLock() + + try { + return await func.apply(null, args) + } finally { + releaseLock() + } + } + }, + + writeLock: (func) => { + return async (...args) => { + const releaseLock = await mutex.writeLock() + + try { + return await func.apply(null, args) + } finally { + releaseLock() + } + } + } + } + + return lock +} + +},{"mortice":1133}],371:[function(require,module,exports){ +'use strict' + +const UnixFS = require('ipfs-unixfs') +const { + DAGNode +} = require('ipld-dag-pb') +const mc = require('multicodec') +const mh = require('multihashes') + +const createNode = async (context, type, options) => { + const format = mc[options.format.toUpperCase().replace(/-/g, '_')] + const hashAlg = mh.names[options.hashAlg] + + const node = DAGNode.create(new UnixFS(type).marshal()) + const cid = await context.ipld.put(node, format, { + cidVersion: options.cidVersion, + hashAlg + }) + + return { + cid, + node + } +} + +module.exports = createNode + +},{"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],372:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const { + DAGNode +} = require('ipld-dag-pb') +const Bucket = require('hamt-sharding/src/bucket') +const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') +const log = require('debug')('ipfs:mfs:core:utils:hamt-utils') +const UnixFS = require('ipfs-unixfs') +const mc = require('multicodec') +const mh = require('multihashes') +const last = require('async-iterator-last') + +const updateHamtDirectory = async (context, links, bucket, options) => { + // update parent with new bit field + const data = Buffer.from(bucket._children.bitField().reverse()) + const dir = new UnixFS('hamt-sharded-directory', data) + dir.fanout = bucket.tableSize() + dir.hashType = DirSharded.hashFn.code + + const format = mc[options.format.toUpperCase().replace(/-/g, '_')] + const hashAlg = mh.names[options.hashAlg] + + const parent = DAGNode.create(dir.marshal(), links) + const cid = await context.ipld.put(parent, format, { + cidVersion: options.cidVersion, + hashAlg, + hashOnly: !options.flush + }) + + return { + node: parent, + cid + } +} + +const recreateHamtLevel = async (links, rootBucket, parentBucket, positionAtParent) => { + // recreate this level of the HAMT + const bucket = new Bucket({ + hashFn: DirSharded.hashFn, + hash: parentBucket ? parentBucket._options.hash : undefined + }, parentBucket, positionAtParent) + + if (parentBucket) { + parentBucket._putObjectAt(positionAtParent, bucket) + } + + await addLinksToHamtBucket(links, bucket, rootBucket) + + return bucket +} + +const addLinksToHamtBucket = async (links, bucket, rootBucket) => { + await Promise.all( + links.map(link => { + if (link.Name.length === 2) { + const pos = parseInt(link.Name, 16) + + bucket._putObjectAt(pos, new Bucket({ + hashFn: DirSharded.hashFn + }, bucket, pos)) + + return Promise.resolve() + } + + return (rootBucket || bucket).put(link.Name.substring(2), { + size: link.TSize, + cid: link.Hash + }) + }) + ) +} + +const toPrefix = (position) => { + return position + .toString('16') + .toUpperCase() + .padStart(2, '0') + .substring(0, 2) +} + +const generatePath = async (context, fileName, rootNode) => { + // start at the root bucket and descend, loading nodes as we go + const rootBucket = await recreateHamtLevel(rootNode.Links, null, null, null) + const position = await rootBucket._findNewBucketAndPos(fileName) + + // the path to the root bucket + let path = [{ + bucket: position.bucket, + prefix: toPrefix(position.pos) + }] + let currentBucket = position.bucket + + while (currentBucket !== rootBucket) { + path.push({ + bucket: currentBucket, + prefix: toPrefix(currentBucket._posAtParent) + }) + + currentBucket = currentBucket._parent + } + + path.reverse() + path[0].node = rootNode + + // load DAGNode for each path segment + for (let i = 0; i < path.length; i++) { + const segment = path[i] + + // find prefix in links + const link = segment.node.Links + .filter(link => link.Name.substring(0, 2) === segment.prefix) + .pop() + + // entry was not in shard + if (!link) { + // reached bottom of tree, file will be added to the current bucket + log(`Link ${segment.prefix}${fileName} will be added`) + // return path + continue + } + + // found entry + if (link.Name === `${segment.prefix}${fileName}`) { + log(`Link ${segment.prefix}${fileName} will be replaced`) + // file already existed, file will be added to the current bucket + // return path + continue + } + + // found subshard + log(`Found subshard ${segment.prefix}`) + const node = await context.ipld.get(link.Hash) + + // subshard hasn't been loaded, descend to the next level of the HAMT + if (!path[i + 1]) { + log(`Loaded new subshard ${segment.prefix}`) + + await recreateHamtLevel(node.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16)) + const position = await rootBucket._findNewBucketAndPos(fileName) + + // i-- + path.push({ + bucket: position.bucket, + prefix: toPrefix(position.pos), + node: node + }) + + continue + } + + const nextSegment = path[i + 1] + + // add intermediate links to bucket + await addLinksToHamtBucket(node.Links, nextSegment.bucket, rootBucket) + + nextSegment.node = node + } + + await rootBucket.put(fileName, true) + + path.reverse() + + return { + rootBucket, + path + } +} + +const createShard = async (context, contents, options) => { + const shard = new DirSharded({ + root: true, + dir: true, + parent: null, + parentKey: null, + path: '', + dirty: true, + flat: false + }, options) + + for (let i = 0; i < contents.length; i++) { + await shard._bucket.put(contents[i].name, { + size: contents[i].size, + cid: contents[i].cid + }) + } + + return last(shard.flush('', context.ipld, null)) +} + +module.exports = { + generatePath, + updateHamtDirectory, + recreateHamtLevel, + addLinksToHamtBucket, + toPrefix, + createShard +} + +}).call(this,require("buffer").Buffer) +},{"async-iterator-last":33,"buffer":181,"debug":355,"hamt-sharding/src/bucket":286,"ipfs-unixfs":435,"ipfs-unixfs-importer/src/dir-sharded":428,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],373:[function(require,module,exports){ +'use strict' + +const { + DAGNode, + DAGLink +} = require('ipld-dag-pb') +const CID = require('cids') +const log = require('debug')('ipfs:mfs:core:utils:remove-link') +const UnixFS = require('ipfs-unixfs') +const { + generatePath, + updateHamtDirectory +} = require('./hamt-utils') +const errCode = require('err-code') +const mc = require('multicodec') +const mh = require('multihashes') + +const removeLink = async (context, options) => { + if (!options.parentCid && !options.parent) { + throw errCode(new Error('No parent node or CID passed to removeLink'), 'EINVALIDPARENT') + } + + if (options.parentCid && !CID.isCID(options.parentCid)) { + throw errCode(new Error('Invalid CID passed to removeLink'), 'EINVALIDPARENTCID') + } + + if (!options.parent) { + log(`Loading parent node ${options.parentCid}`) + + options.parent = await context.ipld.get(options.parentCid) + } + + if (!options.name) { + throw errCode(new Error('No child name passed to removeLink'), 'EINVALIDCHILDNAME') + } + + const meta = UnixFS.unmarshal(options.parent.Data) + + if (meta.type === 'hamt-sharded-directory') { + log(`Removing ${options.name} from sharded directory`) + + return removeFromShardedDirectory(context, options) + } + + log(`Removing link ${options.name} regular directory`) + + return removeFromDirectory(context, options) +} + +const removeFromDirectory = async (context, options) => { + const format = mc[options.format.toUpperCase().replace(/-/g, '_')] + const hashAlg = mh.names[options.hashAlg] + + const newParentNode = await DAGNode.rmLink(options.parent, options.name) + const cid = await context.ipld.put(newParentNode, format, { + cidVersion: options.cidVersion, + hashAlg + }) + + log(`Updated regular directory ${cid}`) + + return { + node: newParentNode, + cid + } +} + +const removeFromShardedDirectory = async (context, options) => { + const { + rootBucket, path + } = await generatePath(context, options.name, options.parent) + + await rootBucket.del(options.name) + + const { + node + } = await updateShard(context, path, { + name: options.name, + cid: options.cid, + size: options.size, + hashAlg: options.hashAlg, + format: options.format, + cidVersion: options.cidVersion, + flush: options.flush + }, options) + + return updateHamtDirectory(context, node.Links, rootBucket, options) +} + +const updateShard = async (context, positions, child, options) => { + const { + bucket, + prefix, + node + } = positions.pop() + + const link = node.Links + .find(link => link.Name.substring(0, 2) === prefix) + + if (!link) { + throw errCode(new Error(`No link found with prefix ${prefix} for file ${child.name}`), 'ERR_NOT_FOUND') + } + + if (link.Name === `${prefix}${child.name}`) { + log(`Removing existing link ${link.Name}`) + + const newNode = await DAGNode.rmLink(node, link.Name) + + await bucket.del(child.name) + + return updateHamtDirectory(context, newNode.Links, bucket, options) + } + + log(`Descending into sub-shard ${link.Name} for ${prefix}${child.name}`) + + const result = await updateShard(context, positions, child, options) + + let newName = prefix + + if (result.node.Links.length === 1) { + log(`Removing subshard for ${prefix}`) + + // convert shard back to normal dir + result.cid = result.node.Links[0].Hash + result.node = result.node.Links[0] + + newName = `${prefix}${result.node.Name.substring(2)}` + } + + log(`Updating shard ${prefix} with name ${newName}`) + + const size = DAGNode.isDAGNode(result.node) ? result.node.size : result.node.Tsize + + return updateShardParent(context, bucket, node, prefix, newName, size, result.cid, options) +} + +const updateShardParent = async (context, bucket, parent, oldName, newName, size, cid, options) => { + parent = await DAGNode.rmLink(parent, oldName) + parent = await DAGNode.addLink(parent, new DAGLink(newName, size, cid)) + + return updateHamtDirectory(context, parent.Links, bucket, options) +} + +module.exports = removeLink + +},{"./hamt-utils":372,"cids":185,"debug":355,"err-code":357,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],374:[function(require,module,exports){ +(function (global,Buffer){ +'use strict' + +const errCode = require('err-code') +const fs = require('fs') +const log = require('debug')('ipfs:mfs:utils:to-async-iterator') +const { + MAX_CHUNK_SIZE +} = require('./constants') + +const toAsyncIterator = async (content) => { + if (!content) { + throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH') + } + + if (typeof content === 'string' || content instanceof String) { + // Paths, node only + log('Content was a path') + + return fs.createReadStream(content) + } + + if (content.length) { + log('Content was array-like') + + return { + [Symbol.asyncIterator]: async function * bufferContent () { + yield content + } + } + } + + if (content[Symbol.asyncIterator]) { + log('Content was an async iterator') + return content + } + + if (content[Symbol.iterator]) { + log('Content was an iterator') + return content + } + + if (global.Blob && content instanceof global.Blob) { + // HTML5 Blob objects (including Files) + log('Content was an HTML5 Blob') + + let index = 0 + + const iterator = { + next: async () => { + if (index > content.size) { + return { + done: true + } + } + + return new Promise((resolve, reject) => { + const chunk = content.slice(index, MAX_CHUNK_SIZE) + index += MAX_CHUNK_SIZE + + const reader = new global.FileReader() + + const handleLoad = (ev) => { + reader.removeEventListener('loadend', handleLoad, false) + + if (ev.error) { + return reject(ev.error) + } + + resolve({ + done: false, + value: Buffer.from(reader.result) + }) + } + + reader.addEventListener('loadend', handleLoad) + reader.readAsArrayBuffer(chunk) + }) + } + } + + return { + [Symbol.asyncIterator]: () => { + return iterator + } + } + } + + throw errCode(new Error(`Don't know how to convert ${content} into an async iterator`), 'ERR_INVALID_PARAMS') +} + +module.exports = toAsyncIterator + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"./constants":369,"buffer":181,"debug":355,"err-code":357,"fs":146}],375:[function(require,module,exports){ +'use strict' + +const { + FILE_SEPARATOR +} = require('./constants') +const loadMfsRoot = require('./with-mfs-root') +const toPathComponents = require('./to-path-components') +const exporter = require('ipfs-unixfs-exporter') +const errCode = require('err-code') + +const IPFS_PREFIX = 'ipfs' + +const toMfsPath = async (context, path) => { + let outputArray = Array.isArray(path) + let paths = Array.isArray(path) ? path : [path] + const root = await loadMfsRoot(context) + + paths = paths.map(path => { + path = (path || '').trim() + path = path.replace(/(\/\/+)/g, '/') + + if (path.endsWith('/') && path.length > 1) { + path = path.substring(0, path.length - 1) + } + + if (!path) { + throw errCode(new Error('paths must not be empty'), 'ERR_NO_PATH') + } + + if (path.substring(0, 1) !== FILE_SEPARATOR) { + throw errCode(new Error(`paths must start with a leading ${FILE_SEPARATOR}`), 'ERR_INVALID_PATH') + } + + if (path.substring(path.length - FILE_SEPARATOR.length) === FILE_SEPARATOR) { + path = path.substring(0, path.length - FILE_SEPARATOR.length) + } + + const pathComponents = toPathComponents(path) + + if (pathComponents[0] === IPFS_PREFIX) { + // e.g. /ipfs/QMfoo or /ipfs/Qmfoo/sub/path + let mfsDirectory + + if (pathComponents.length === 2) { + mfsDirectory = `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}` + } else { + mfsDirectory = `${FILE_SEPARATOR}${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}` + } + + return { + type: 'ipfs', + depth: pathComponents.length - 2, + + mfsPath: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, + mfsDirectory, + parts: pathComponents, + path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, + name: pathComponents[pathComponents.length - 1] + } + } + + const mfsPath = `/${IPFS_PREFIX}/${root}${pathComponents.length ? '/' + pathComponents.join(FILE_SEPARATOR) : ''}` + const mfsDirectory = `/${IPFS_PREFIX}/${root}/${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}` + + return { + type: 'mfs', + depth: pathComponents.length, + + mfsDirectory, + mfsPath, + parts: pathComponents, + path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, + name: pathComponents[pathComponents.length - 1] + } + }) + + await Promise.all( + paths.map(async (path) => { + const cidPath = path.type === 'mfs' ? path.mfsPath : path.path + + try { + const res = await exporter(cidPath, context.ipld) + + path.cid = res.cid + path.mfsPath = `/ipfs/${res.path}` + path.unixfs = res.unixfs + path.content = res.content + } catch (err) { + if (err.code !== 'ERR_NOT_FOUND') { + throw err + } + } + + path.exists = Boolean(path.cid) + }) + ) + + if (outputArray) { + return paths + } + + return paths[0] +} + +module.exports = toMfsPath + +},{"./constants":369,"./to-path-components":376,"./with-mfs-root":382,"err-code":357,"ipfs-unixfs-exporter":400}],376:[function(require,module,exports){ +'use strict' + +const toPathComponents = (path = '') => { + // split on / unless escaped with \ + return (path + .trim() + .match(/([^\\^/]|\\\/)+/g) || []) + .filter(Boolean) +} + +module.exports = toPathComponents + +},{}],377:[function(require,module,exports){ +'use strict' + +const toSources = require('./to-sources') + +async function toSourcesAndDestination (context, args) { + const { + sources, + options + } = await toSources(context, args) + + const destination = sources.pop() + + return { + destination, + sources, + options + } +} + +module.exports = toSourcesAndDestination + +},{"./to-sources":378}],378:[function(require,module,exports){ +'use strict' + +const toMfsPath = require('./to-mfs-path') + +async function toSources (context, args) { + // Support weird mfs.mv([source, dest], options, callback) signature + if (Array.isArray(args[0])) { + args = args[0] + } + + const sources = args + .filter(arg => typeof arg === 'string') + .map(source => source.trim()) + + return { + sources: await toMfsPath(context, sources) + } +} + +module.exports = toSources + +},{"./to-mfs-path":375}],379:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const log = require('debug')('ipfs:mfs:utils:to-trail') + +const toTrail = async (context, path) => { + log(`Creating trail for path ${path}`) + + const output = [] + + for await (const fsEntry of exporter.path(path, context.ipld)) { + output.push({ + name: fsEntry.name, + cid: fsEntry.cid, + size: fsEntry.node.size, + type: fsEntry.unixfs ? fsEntry.unixfs.type : undefined + }) + } + + return output +} + +module.exports = toTrail + +},{"debug":355,"ipfs-unixfs-exporter":400}],380:[function(require,module,exports){ +'use strict' + +const log = require('debug')('ipfs:mfs:utils:update-mfs-root') +const { + MFS_ROOT_KEY +} = require('./constants') + +const updateMfsRoot = async (context, cid) => { + log(`New MFS root will be ${cid}`) + + await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer) + + return cid +} + +module.exports = updateMfsRoot + +},{"./constants":369,"debug":355}],381:[function(require,module,exports){ +'use strict' + +const log = require('debug')('ipfs:mfs:utils:update-tree') +const addLink = require('./add-link') + +const defaultOptions = { + shardSplitThreshold: 1000 +} + +// loop backwards through the trail, replacing links of all components to update CIDs +const updateTree = async (context, trail, options) => { + options = Object.assign({}, defaultOptions, options) + + log('Trail', trail) + trail = trail.slice().reverse() + + let index = 0 + let child + + for await (const node of context.ipld.getMany(trail.map(node => node.cid))) { + const cid = trail[index].cid + const name = trail[index].name + index++ + + if (!child) { + child = { + cid, + name, + size: node.size + } + + continue + } + + const result = await addLink(context, { + parent: node, + name: child.name, + cid: child.cid, + size: child.size, + flush: options.flush, + shardSplitThreshold: options.shardSplitThreshold, + format: options.format, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion + }) + + // new child for next loop + child = { + cid: result.cid, + name, + size: result.node.size + } + } + + log(`Final CID ${child.cid}`) + + return child.cid +} + +module.exports = updateTree + +},{"./add-link":367,"debug":355}],382:[function(require,module,exports){ +'use strict' + +const CID = require('cids') +const UnixFs = require('ipfs-unixfs') +const { + DAGNode +} = require('ipld-dag-pb') +const log = require('debug')('ipfs:mfs:utils:with-mfs-root') +const mc = require('multicodec') +const mh = require('multihashes') + +const { + MFS_ROOT_KEY +} = require('./constants') + +const loadMfsRoot = async (context) => { + // Open the repo if it's been closed + await context.repo.datastore.open() + + // Load the MFS root CID + let cid + + try { + const buf = await context.repo.datastore.get(MFS_ROOT_KEY) + + cid = new CID(buf) + } catch (err) { + if (err.code !== 'ERR_NOT_FOUND') { + throw err + } + + log('Creating new MFS root') + const node = DAGNode.create(new UnixFs('directory').marshal()) + cid = await context.ipld.put(node, mc.DAG_PB, { + cidVersion: 0, + hashAlg: mh.names['sha2-256'] // why can't ipld look this up? + }) + + await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer) + } + + log(`Loaded MFS root /ipfs/${cid}`) + + return cid +} + +module.exports = loadMfsRoot + +},{"./constants":369,"cids":185,"debug":355,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],383:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const log = require('debug')('ipfs:mfs:write') +const importer = require('ipfs-unixfs-importer') +const stat = require('./stat') +const mkdir = require('./mkdir') +const addLink = require('./utils/add-link') +const applyDefaultOptions = require('./utils/apply-default-options') +const createLock = require('./utils/create-lock') +const toAsyncIterator = require('./utils/to-async-iterator') +const toMfsPath = require('./utils/to-mfs-path') +const toPathComponents = require('./utils/to-path-components') +const toTrail = require('./utils/to-trail') +const updateTree = require('./utils/update-tree') +const updateMfsRoot = require('./utils/update-mfs-root') +const errCode = require('err-code') +const { + MAX_CHUNK_SIZE +} = require('./utils/constants') +const last = require('async-iterator-last') + +const defaultOptions = { + offset: 0, // the offset in the file to begin writing + length: undefined, // how many bytes from the incoming buffer to write + create: false, // whether to create the file if it does not exist + truncate: false, // whether to truncate the file first + rawLeaves: false, + reduceSingleLeafToSelf: false, + cidVersion: 0, + hashAlg: 'sha2-256', + format: 'dag-pb', + parents: false, // whether to create intermediate directories if they do not exist + progress: () => {}, + strategy: 'trickle', + flush: true, + leafType: 'raw', + shardSplitThreshold: 1000 +} + +module.exports = (context) => { + return async function mfsWrite (path, content, options) { + log('Hello world, writing', path, content, options) + options = applyDefaultOptions(options, defaultOptions) + + let source, destination, parent + log('Reading source, destination and parent') + await createLock().readLock(async () => { + source = await toAsyncIterator(content, options) + destination = await toMfsPath(context, path) + parent = await toMfsPath(context, destination.mfsDirectory) + })() + log('Read source, destination and parent') + if (!options.parents && !parent.exists) { + throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST') + } + + if (!options.create && !destination.exists) { + throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST') + } + + return updateOrImport(context, path, source, destination, options) + } +} + +const updateOrImport = async (context, path, source, destination, options) => { + const child = await write(context, source, destination, options) + + // The slow bit is done, now add or replace the DAGLink in the containing directory + // re-reading the path to the containing folder in case it has changed in the interim + await createLock().writeLock(async () => { + const pathComponents = toPathComponents(path) + const fileName = pathComponents.pop() + let parentExists = false + + try { + await stat(context)(`/${pathComponents.join('/')}`, options) + parentExists = true + } catch (err) { + if (err.code !== 'ERR_NOT_FOUND') { + throw err + } + } + + if (!parentExists) { + await mkdir(context)(`/${pathComponents.join('/')}`, options) + } + + // get an updated mfs path in case the root changed while we were writing + const updatedPath = await toMfsPath(context, path) + const trail = await toTrail(context, updatedPath.mfsDirectory, options) + const parent = trail[trail.length - 1] + + if (!parent.type.includes('directory')) { + throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY') + } + + const parentNode = await context.ipld.get(parent.cid) + + const result = await addLink(context, { + parent: parentNode, + name: fileName, + cid: child.cid, + size: child.size, + flush: options.flush, + shardSplitThreshold: options.shardSplitThreshold, + format: options.format, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion + }) + + parent.cid = result.cid + + // update the tree with the new child + const newRootCid = await updateTree(context, trail, options) + + // Update the MFS record with the new CID for the root of the tree + await updateMfsRoot(context, newRootCid) + })() +} + +const write = async (context, source, destination, options) => { + if (destination.exists) { + log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`) + } else { + log(`Writing file offset ${options.offset} length ${options.length}`) + } + + const sources = [] + + // pad start of file if necessary + if (options.offset > 0) { + if (destination.unixfs && destination.unixfs.fileSize() > options.offset) { + log(`Writing first ${options.offset} bytes of original file`) + + sources.push( + () => { + return destination.content({ + offset: 0, + length: options.offset + }) + } + ) + } else { + log(`Writing zeros for first ${options.offset} bytes`) + sources.push( + asyncZeroes(options.offset) + ) + } + } + + sources.push( + limitAsyncStreamBytes(source, options.length) + ) + + const content = countBytesStreamed(catAsyncInterators(sources), (bytesWritten) => { + if (destination.unixfs && !options.truncate) { + // if we've done reading from the new source and we are not going + // to truncate the file, add the end of the existing file to the output + const fileSize = destination.unixfs.fileSize() + + if (fileSize > bytesWritten) { + log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`) + + return destination.content({ + offset: bytesWritten + }) + } else { + log(`Not writing last bytes from original file`) + } + } + + return { + [Symbol.asyncIterator]: async function * () {} + } + }) + + let result = await last(importer([{ + content: content + }], context.ipld, { + progress: options.progress, + hashAlg: options.hashAlg, + cidVersion: options.cidVersion, + strategy: options.strategy, + rawLeaves: options.rawLeaves, + reduceSingleLeafToSelf: options.reduceSingleLeafToSelf, + leafType: options.leafType + })) + + log(`Wrote ${result.cid}`) + + return { + cid: result.cid, + size: result.size + } +} + +const limitAsyncStreamBytes = (stream, limit) => { + return async function * _limitAsyncStreamBytes () { + let emitted = 0 + + for await (const buf of stream) { + emitted += buf.length + + if (emitted > limit) { + yield buf.slice(0, limit - emitted) + + return + } + + yield buf + } + } +} + +const asyncZeroes = (count, chunkSize = MAX_CHUNK_SIZE) => { + const buf = Buffer.alloc(chunkSize, 0) + + const stream = { + [Symbol.asyncIterator]: async function * _asyncZeroes () { + while (true) { + yield buf.slice() + } + } + } + + return limitAsyncStreamBytes(stream, count) +} + +const catAsyncInterators = async function * (sources) { + for (let i = 0; i < sources.length; i++) { + for await (const buf of sources[i]()) { + yield buf + } + } +} + +const countBytesStreamed = async function * (source, notify) { + let wrote = 0 + + for await (const buf of source) { + wrote += buf.length + + yield buf + } + + for await (const buf of notify(wrote)) { + wrote += buf.length + + yield buf + } +} + +}).call(this,require("buffer").Buffer) +},{"./mkdir":362,"./stat":366,"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/constants":369,"./utils/create-lock":370,"./utils/to-async-iterator":374,"./utils/to-mfs-path":375,"./utils/to-path-components":376,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"async-iterator-last":33,"buffer":181,"debug":355,"err-code":357,"ipfs-unixfs-importer":431}],384:[function(require,module,exports){ +arguments[4][328][0].apply(exports,arguments) +},{"dup":328}],385:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":386,"_process":1258,"dup":208}],386:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],387:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const Key = require('interface-datastore').Key + +const apiFile = new Key('api') + +module.exports = (store) => { + return { + /** + * Get the current configuration from the repo. + * + * @param {function(Error, Object)} callback + * @returns {void} + */ + get (callback) { + store.get(apiFile, (err, value) => callback(err, value && value.toString())) + }, + /** + * Set the current configuration for this repo. + * + * @param {Object} value - the api address to be written + * @param {function(Error)} callback + * @returns {void} + */ + set (value, callback) { + store.put(apiFile, Buffer.from(value.toString()), callback) + }, + /** + * Deletes api file + * + * @param {function(Error, bool)} callback + * @returns {void} + */ + delete (callback) { + store.delete(apiFile, callback) + } + } +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"interface-datastore":322}],388:[function(require,module,exports){ +'use strict' + +exports.create = function createBackend (name, path, options) { + const Ctor = options.storageBackends[name] + const backendOptions = Object.assign({}, options.storageBackendOptions[name] || {}) + return new Ctor(path, backendOptions) +} + +},{}],389:[function(require,module,exports){ +'use strict' + +const core = require('datastore-core') +const ShardingStore = core.ShardingDatastore +const Key = require('interface-datastore').Key +const base32 = require('base32.js') +const Block = require('ipfs-block') +const setImmediate = require('async/setImmediate') +const reject = require('async/reject') +const CID = require('cids') +const pull = require('pull-stream/pull') +const collect = require('pull-stream/sinks/collect') + +/** + * Transform a raw buffer to a base32 encoded key. + * + * @param {Buffer} rawKey + * @returns {Key} + */ +const keyFromBuffer = (rawKey) => { + const enc = new base32.Encoder() + return new Key('/' + enc.write(rawKey).finalize(), false) +} + +/** + * Transform a cid to the appropriate datastore key. + * + * @param {CID} cid + * @returns {Key} + */ +const cidToDsKey = (cid) => { + return keyFromBuffer(cid.buffer) +} + +module.exports = (filestore, options, callback) => { + maybeWithSharding(filestore, options, (err, store) => { + if (err) { return callback(err) } + + callback(null, createBaseStore(store)) + }) +} + +function maybeWithSharding (filestore, options, callback) { + if (options.sharding) { + const shard = new core.shard.NextToLast(2) + ShardingStore.createOrOpen(filestore, shard, callback) + } else { + setImmediate(() => callback(null, filestore)) + } +} + +function createBaseStore (store) { + return { + /** + * Query the store. + * + * @param {object} query + * @param {function(Error, Array)} callback + * @return {void} + */ + query (query, callback) { + pull( + store.query(query), + collect(callback) + ) + }, + /** + * Get a single block by CID. + * + * @param {CID} cid + * @param {function(Error, Block)} callback + * @returns {void} + */ + get (cid, callback) { + if (!CID.isCID(cid)) { + return setImmediate(() => { + callback(new Error('Not a valid cid')) + }) + } + + const key = cidToDsKey(cid) + store.get(key, (err, blockData) => { + if (err) { + // If not found, we try with the other CID version. + // If exists, then store that block under the CID that was requested. + // Some duplication occurs. + if (err.code === 'ERR_NOT_FOUND') { + const otherCid = cidToOtherVersion(cid) + if (!otherCid) return callback(err) + + const otherKey = cidToDsKey(otherCid) + return store.get(otherKey, (err, blockData) => { + if (err) return callback(err) + + store.put(key, blockData, (err) => { + if (err) return callback(err) + callback(null, new Block(blockData, cid)) + }) + }) + } + + return callback(err) + } + + callback(null, new Block(blockData, cid)) + }) + }, + put (block, callback) { + if (!Block.isBlock(block)) { + return setImmediate(() => { + callback(new Error('invalid block')) + }) + } + + const k = cidToDsKey(block.cid) + + store.has(k, (err, exists) => { + if (err) { return callback(err) } + if (exists) { return callback() } + + store.put(k, block.data, callback) + }) + }, + /** + * Like put, but for more. + * + * @param {Array} blocks + * @param {function(Error)} callback + * @returns {void} + */ + putMany (blocks, callback) { + const keys = blocks.map((b) => ({ + key: cidToDsKey(b.cid), + block: b + })) + + const batch = store.batch() + reject(keys, (k, cb) => store.has(k.key, cb), (err, newKeys) => { + if (err) { + return callback(err) + } + + newKeys.forEach((k) => { + batch.put(k.key, k.block.data) + }) + + batch.commit(callback) + }) + }, + /** + * Does the store contain block with this cid? + * + * @param {CID} cid + * @param {function(Error, bool)} callback + * @returns {void} + */ + has (cid, callback) { + if (!CID.isCID(cid)) { + return setImmediate(() => { + callback(new Error('Not a valid cid')) + }) + } + + store.has(cidToDsKey(cid), (err, exists) => { + if (err) return callback(err) + if (exists) return callback(null, true) + + // If not found, we try with the other CID version. + const otherCid = cidToOtherVersion(cid) + if (!otherCid) return callback(null, false) + + store.has(cidToDsKey(otherCid), callback) + }) + }, + /** + * Delete a block from the store + * + * @param {CID} cid + * @param {function(Error)} callback + * @returns {void} + */ + delete (cid, callback) { + if (!CID.isCID(cid)) { + return setImmediate(() => { + callback(new Error('Not a valid cid')) + }) + } + + store.delete(cidToDsKey(cid), callback) + }, + + close (callback) { + store.close(callback) + } + } +} + +function cidToOtherVersion (cid) { + try { + return cid.version === 0 ? cid.toV1() : cid.toV0() + } catch (err) { + return null + } +} + +},{"async/reject":93,"async/setImmediate":96,"base32.js":107,"cids":185,"datastore-core":199,"interface-datastore":322,"ipfs-block":353,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313}],390:[function(require,module,exports){ +'use strict' + +const Key = require('interface-datastore').Key +const queue = require('async/queue') +const waterfall = require('async/waterfall') +const _get = require('dlv') +const _set = require('just-safe-set') +const Buffer = require('buffer').Buffer + +const configKey = new Key('config') + +module.exports = (store) => { + const setQueue = queue(_doSet, 1) + + const configStore = { + /** + * Get the current configuration from the repo. + * + * @param {String} key - the config key to get + * @param {function(Error, Object)} callback + * @returns {void} + */ + get (key, callback) { + if (typeof key === 'function') { + callback = key + key = undefined + } + if (!key) { + key = undefined + } + store.get(configKey, (err, encodedValue) => { + if (err) { return callback(err) } + + let config + try { + config = JSON.parse(encodedValue.toString()) + } catch (err) { + return callback(err) + } + + if (typeof key === 'undefined') { + return callback(null, config) + } + + if (typeof key !== 'string') { + return callback(new Error('Key ' + key + ' must be a string.')) + } + + const value = _get(config, key, null) + + if (value === null) { + return callback(new Error('Key ' + key + ' does not exist in config.')) + } + + callback(null, value) + }) + }, + /** + * Set the current configuration for this repo. + * + * @param {String} key - the config key to be written + * @param {Object} value - the config value to be written + * @param {function(Error)} callback + * @returns {void} + */ + set (key, value, callback) { + if (typeof value === 'function') { + callback = value + value = key + key = undefined + } else if (!key || typeof key !== 'string') { + return callback(new Error('Invalid key type')) + } + + if (value === undefined || Buffer.isBuffer(value)) { + return callback(new Error('Invalid value type')) + } + + setQueue.push({ + key: key, + value: value + }, callback) + }, + + /** + * Check if a config file exists. + * + * @param {function(Error, bool)} callback + * @returns {void} + */ + exists (callback) { + store.has(configKey, callback) + } + } + + return configStore + + function _doSet (m, callback) { + const key = m.key + const value = m.value + if (key) { + waterfall( + [ + (cb) => configStore.get(cb), + (config, cb) => { + _set(config, key, value) + cb(null, config) + }, + _saveAll + ], + callback) + } else { + _saveAll(value, callback) + } + } + + function _saveAll (config, callback) { + const buf = Buffer.from(JSON.stringify(config, null, 2)) + store.put(configKey, buf, callback) + } +} + +},{"async/queue":92,"async/waterfall":102,"buffer":181,"dlv":233,"interface-datastore":322,"just-safe-set":669}],391:[function(require,module,exports){ +'use strict' + +module.exports = { + repoVersion: 7 +} + +},{}],392:[function(require,module,exports){ +'use strict' + +// Default configuration for the datastore spec in node.js +module.exports = { + Spec: { + type: 'mount', + mounts: [ + { + mountpoint: '/blocks', + type: 'measure', + prefix: 'flatfs.datastore', + child: { + type: 'flatfs', + path: 'blocks', + sync: true, + shardFunc: '/repo/flatfs/shard/v1/next-to-last/2' + } + }, + { + mountpoint: '/', + type: 'measure', + prefix: 'leveldb.datastore', + child: { + type: 'levelds', + path: 'datastore', + compression: 'none' + } + } + ] + } +} + +},{}],393:[function(require,module,exports){ +'use strict' + +// Default configuration for a repo in the browser +module.exports = { + lock: 'memory', + storageBackends: { + root: require('datastore-level'), + blocks: require('datastore-level'), + keys: require('datastore-level'), + datastore: require('datastore-level') + }, + storageBackendOptions: { + root: { + extension: '' + }, + blocks: { + sharding: false + }, + keys: { + sharding: false + } + } +} + +},{"datastore-level":207}],394:[function(require,module,exports){ +'use strict' + +exports.ERR_REPO_NOT_INITIALIZED = 'ERR_REPO_NOT_INITIALIZED' + +},{}],395:[function(require,module,exports){ +(function (setImmediate){ +'use strict' + +const waterfall = require('async/waterfall') +const series = require('async/series') +const parallel = require('async/parallel') +const each = require('async/each') +const _get = require('dlv') +const assert = require('assert') +const path = require('path') +const debug = require('debug') +const Big = require('bignumber.js') +const pull = require('pull-stream/pull') +const reduce = require('pull-stream/sinks/reduce') + +const backends = require('./backends') +const version = require('./version') +const config = require('./config') +const spec = require('./spec') +const apiAddr = require('./api-addr') +const blockstore = require('./blockstore') +const defaultOptions = require('./default-options') +const defaultDatastore = require('./default-datastore') +const ERRORS = require('./errors') + +const log = debug('repo') + +const noLimit = Number.MAX_SAFE_INTEGER + +const lockers = { + memory: require('./lock-memory'), + fs: require('./lock') +} + +const repoVersion = require('./constants').repoVersion + +/** + * IpfsRepo implements all required functionality to read and write to an ipfs repo. + * + */ +class IpfsRepo { + /** + * @param {string} repoPath - path where the repo is stored + * @param {object} options - Configuration + */ + constructor (repoPath, options) { + assert.strictEqual(typeof repoPath, 'string', 'missing repoPath') + + this.options = buildOptions(options) + this.closed = true + this.path = repoPath + + this._locker = this._getLocker() + + this.root = backends.create('root', this.path, this.options) + this.version = version(this.root) + this.config = config(this.root) + this.spec = spec(this.root) + this.apiAddr = apiAddr(this.root) + } + + /** + * Initialize a new repo. + * + * @param {Object} config - config to write into `config`. + * @param {function(Error)} callback + * @returns {void} + */ + init (config, callback) { + log('initializing at: %s', this.path) + + series([ + (cb) => this.root.open(ignoringAlreadyOpened(cb)), + (cb) => this.config.set(buildConfig(config), cb), + (cb) => this.spec.set(buildDatastoreSpec(config), cb), + (cb) => this.version.set(repoVersion, cb) + ], callback) + } + + /** + * Open the repo. If the repo is already open no action will be taken. + * If the repo is not initialized it will return an error. + * + * @param {function(Error)} callback + * @returns {void} + */ + open (callback) { + if (!this.closed) { + setImmediate(() => callback(new Error('repo is already open'))) + return // early + } + log('opening at: %s', this.path) + + // check if the repo is already initialized + waterfall([ + (cb) => this.root.open(ignoringAlreadyOpened(cb)), + (cb) => this._isInitialized(cb), + (cb) => this._openLock(this.path, cb), + (lck, cb) => { + log('aquired repo.lock') + this.lockfile = lck + cb() + }, + (cb) => { + log('creating datastore') + this.datastore = backends.create('datastore', path.join(this.path, 'datastore'), this.options) + log('creating blocks') + const blocksBaseStore = backends.create('blocks', path.join(this.path, 'blocks'), this.options) + blockstore( + blocksBaseStore, + this.options.storageBackendOptions.blocks, + cb) + }, + (blocks, cb) => { + this.blocks = blocks + cb() + }, + (cb) => { + log('creating keystore') + this.keys = backends.create('keys', path.join(this.path, 'keys'), this.options) + cb() + }, + + (cb) => { + this.closed = false + log('all opened') + cb() + } + ], (err) => { + if (err && this.lockfile) { + this._closeLock((err2) => { + if (!err2) { + this.lockfile = null + } else { + log('error removing lock', err2) + } + callback(err) + }) + } else { + callback(err) + } + }) + } + + /** + * Returns the repo locker to be used. Null will be returned if no locker is requested + * + * @private + * @returns {Locker} + */ + _getLocker () { + if (typeof this.options.lock === 'string') { + assert(lockers[this.options.lock], 'Unknown lock type: ' + this.options.lock) + return lockers[this.options.lock] + } + + assert(this.options.lock, 'No lock provided') + return this.options.lock + } + + /** + * Creates a lock on the repo if a locker is specified. The lockfile object will + * be returned in the callback if one has been created. + * + * @param {string} path + * @param {function(Error, lockfile)} callback + * @returns {void} + */ + _openLock (path, callback) { + this._locker.lock(path, (err, lockfile) => { + if (err) { + return callback(err, null) + } + + assert.strictEqual(typeof lockfile.close, 'function', 'Locks must have a close method') + callback(null, lockfile) + }) + } + + /** + * Closes the lock on the repo + * + * @param {function(Error)} callback + * @returns {void} + */ + _closeLock (callback) { + if (this.lockfile) { + return this.lockfile.close(callback) + } + callback() + } + + /** + * Check if the repo is already initialized. + * + * @private + * @param {function(Error)} callback + * @returns {void} + */ + _isInitialized (callback) { + log('init check') + parallel( + { + config: (cb) => this.config.exists(cb), + spec: (cb) => this.spec.exists(cb), + version: (cb) => this.version.check(repoVersion, cb) + }, + (err, res) => { + log('init', err, res) + if (err && !res.config) { + return callback(Object.assign(new Error('repo is not initialized yet'), + { + code: ERRORS.ERR_REPO_NOT_INITIALIZED, + path: this.path + })) + } + callback(err) + } + ) + } + + /** + * Close the repo and cleanup. + * + * @param {function(Error)} callback + * @returns {void} + */ + close (callback) { + if (this.closed) { + return callback(new Error('repo is already closed')) + } + + log('closing at: %s', this.path) + series([ + (cb) => this.apiAddr.delete(ignoringNotFound(cb)), + (cb) => { + each( + [this.blocks, this.keys, this.datastore], + (store, callback) => store.close(callback), + cb) + }, + (cb) => { + log('unlocking') + this.closed = true + this._closeLock(cb) + }, + (cb) => { + this.lockfile = null + cb() + } + ], (err) => callback(err)) + } + + /** + * Check if a repo exists. + * + * @param {function(Error, bool)} callback + * @returns {void} + */ + exists (callback) { + this.version.exists(callback) + } + + /** + * Get repo status. + * + * @param {Object} options + * @param {Boolean} options.human + * @param {function(Error, Object)} callback + * @return {void} + */ + stat (options, callback) { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = Object.assign({}, { human: false }, options) + + parallel({ + storageMax: (cb) => this.config.get('Datastore.StorageMax', (err, max) => { + if (err) { + cb(null, new Big(noLimit)) + } else { + cb(null, new Big(max)) + } + }), + version: (cb) => this.version.get(cb), + blocks: (cb) => this.blocks.query({}, (err, list) => { + list = list || [] + + const count = new Big(list.length) + let size = new Big(0) + + list.forEach(block => { + size = size + .plus(block.value.byteLength) + .plus(block.key._buf.byteLength) + }) + + cb(err, { + count: count, + size: size + }) + }), + datastore: (cb) => getSize(this.datastore, cb), + keys: (cb) => getSize(this.keys, cb) + }, (err, results) => { + if (err) return callback(err) + + let size = results.blocks.size + .plus(results.datastore) + .plus(results.keys) + + if (options.human) { + size = size.div(1048576) + } + + callback(null, { + repoPath: this.path, + storageMax: results.storageMax, + version: results.version, + numObjects: results.blocks.count, + repoSize: size + }) + }) + } +} + +function getSize (queryFn, callback) { + pull( + queryFn.query({}), + reduce((sum, block) => { + return sum + .plus(block.value.byteLength) + .plus(block.key._buf.byteLength) + }, new Big(0), callback)) +} + +module.exports = IpfsRepo +module.exports.repoVersion = repoVersion +module.exports.errors = ERRORS + +function ignoringIf (cond, cb) { + return (err) => { + cb(err && !cond(err) ? err : null) + } +} +function ignoringAlreadyOpened (cb) { + return ignoringIf((err) => err.message === 'Already open', cb) +} + +function ignoringNotFound (cb) { + return ignoringIf((err) => { + return err && (err.code === ERRORS.ERR_REPO_NOT_INITIALIZED || err.message.startsWith('ENOENT')) + }, cb) +} + +function buildOptions (_options) { + const options = Object.assign({}, defaultOptions, _options) + + options.storageBackends = Object.assign( + {}, + defaultOptions.storageBackends, + options.storageBackends) + + options.storageBackendOptions = Object.assign( + {}, + defaultOptions.storageBackendOptions, + options.storageBackendOptions) + + return options +} + +// TODO this should come from js-ipfs instead +function buildConfig (_config) { + _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {})) + + return _config +} + +function buildDatastoreSpec (_config) { + const spec = Object.assign({}, defaultDatastore.Spec, _get(_config, 'datastore.Spec', {})) + + return { + type: spec.type, + mounts: spec.mounts.map((mounting) => ({ + mountpoint: mounting.mountpoint, + type: mounting.child.type, + path: mounting.child.path, + shardFunc: mounting.child.shardFunc + })) + } +} + +}).call(this,require("timers").setImmediate) +},{"./api-addr":387,"./backends":388,"./blockstore":389,"./config":390,"./constants":391,"./default-datastore":392,"./default-options":393,"./errors":394,"./lock":396,"./lock-memory":396,"./spec":397,"./version":398,"assert":26,"async/each":56,"async/parallel":91,"async/series":95,"async/waterfall":102,"bignumber.js":384,"debug":385,"dlv":233,"path":1246,"pull-stream/pull":1312,"pull-stream/sinks/reduce":1320,"timers":1500}],396:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const setImmediate = require('async/setImmediate') + +const log = debug('repo:lock') + +const lockFile = 'repo.lock' + +const LOCKS = {} + +/** + * Lock the repo in the given dir. + * + * @param {string} dir + * @param {function(Error, lock)} callback + * @returns {void} + */ +exports.lock = (dir, callback) => { + const file = dir + '/' + lockFile + log('locking %s', file) + LOCKS[file] = true + const closer = { + close (cb) { + if (LOCKS[file]) { + delete LOCKS[file] + } + setImmediate(cb) + } + } + setImmediate(() => { + callback(null, closer) + }) +} + +/** + * Check if the repo in the given directory is locked. + * + * @param {string} dir + * @param {function(Error, bool)} callback + * @returns {void} + */ +exports.locked = (dir, callback) => { + const file = dir + '/' + lockFile + log('checking lock: %s') + + const locked = LOCKS[file] + setImmediate(() => { + callback(null, locked) + }) +} + +},{"async/setImmediate":96,"debug":385}],397:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const Key = require('interface-datastore').Key +const sortKeys = require('sort-keys') + +const specKey = new Key('datastore_spec') + +module.exports = (store) => { + return { + /** + * Check if a datastore spec file exists. + * + * @param {function(Error, bool)} callback + * @returns {void} + */ + exists (callback) { + store.has(specKey, callback) + }, + /** + * Get the current datastore spec. + * + * @param {function(Error, number)} callback + * @returns {void} + */ + get (callback) { + store.get(specKey, (err, buf) => { + if (err) { + return callback(err) + } + callback(null, JSON.parse(buf.toString())) + }) + }, + /** + * Set the datastore spec of the repo, writing it to the underlying store. + * + * @param {number} spec + * @param {function(Error)} callback + * @returns {void} + */ + set (spec, callback) { + store.put(specKey, Buffer.from(JSON.stringify(sortKeys(spec, { deep: true }))), callback) + } + } +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"interface-datastore":322,"sort-keys":1438}],398:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const Key = require('interface-datastore').Key +const debug = require('debug') +const log = debug('repo:version') + +const versionKey = new Key('version') + +module.exports = (store) => { + return { + /** + * Check if a version file exists. + * + * @param {function(Error, bool)} callback + * @returns {void} + */ + exists (callback) { + store.has(versionKey, callback) + }, + /** + * Get the current version. + * + * @param {function(Error, number)} callback + * @returns {void} + */ + get (callback) { + store.get(versionKey, (err, buf) => { + if (err) { + return callback(err) + } + callback(null, parseInt(buf.toString().trim(), 10)) + }) + }, + /** + * Set the version of the repo, writing it to the underlying store. + * + * @param {number} version + * @param {function(Error)} callback + * @returns {void} + */ + set (version, callback) { + store.put(versionKey, Buffer.from(String(version)), callback) + }, + /** + * Check the current version, and return an error on missmatch + * @param {number} expected + * @param {function(Error)} callback + * @returns {void} + */ + check (expected, callback) { + this.get((err, version) => { + if (err) { + return callback(err) + } + log('comparing version: %s and %s', version, expected) + + // Version 6 and 7 are the same + // TODO: Clean up the compatibility logic. Repo feature detection would be ideal, or a better version schema + const compatibleVersion = (version === 6 && expected === 7) || (expected === 6 && version === 7) + + if (version !== expected && !compatibleVersion) { + return callback(new Error(`ipfs repo needs migration: expected version v${expected}, found version v${version}`)) + } + callback() + }) + } + } +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"debug":385,"interface-datastore":322}],399:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],400:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const errCode = require('err-code') +const CID = require('cids') +const resolve = require('./resolvers') +const last = require('async-iterator-last') + +const toPathComponents = (path = '') => { + // split on / unless escaped with \ + return (path + .trim() + .match(/([^\\^/]|\\\/)+/g) || []) + .filter(Boolean) +} + +const cidAndRest = (path) => { + if (Buffer.isBuffer(path)) { + return { + cid: new CID(path), + toResolve: [] + } + } + + if (CID.isCID(path)) { + return { + cid: path, + toResolve: [] + } + } + + if (typeof path === 'string') { + if (path.indexOf('/ipfs/') === 0) { + path = path.substring(6) + } + + const output = toPathComponents(path) + + return { + cid: new CID(output[0]), + toResolve: output.slice(1) + } + } + + throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH') +} + +const walkPath = async function * (path, ipld) { + let { + cid, + toResolve + } = cidAndRest(path) + let name = cid.toBaseEncodedString() + let entryPath = name + const startingDepth = toResolve.length + + while (true) { + const result = await resolve(cid, name, entryPath, toResolve, startingDepth, ipld) + + if (!result.entry && !result.next) { + throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND') + } + + if (result.entry) { + yield result.entry + } + + if (!result.next) { + return + } + + // resolve further parts + toResolve = result.next.toResolve + cid = result.next.cid + name = result.next.name + entryPath = result.next.path + } +} + +const exporter = (path, ipld) => { + return last(walkPath(path, ipld)) +} + +const recursive = async function * (path, ipld) { + const node = await exporter(path, ipld) + + yield node + + if (node.unixfs && node.unixfs.type.includes('dir')) { + for await (const child of recurse(node)) { + yield child + } + } + + async function * recurse (node) { + for await (const file of node.content()) { + yield file + + if (file.unixfs.type.includes('dir')) { + for await (const subFile of recurse(file)) { + yield subFile + } + } + } + } +} + +module.exports = exporter +module.exports.path = walkPath +module.exports.recursive = recursive + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608,"./resolvers":402,"async-iterator-last":33,"cids":185,"err-code":399}],401:[function(require,module,exports){ +'use strict' + +const CID = require('cids') +const errCode = require('err-code') + +const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => { + let node = await ipld.get(cid) + let subObject = node + let subPath = path + + while (toResolve.length) { + const prop = toResolve[0] + + if (prop in subObject) { + // remove the bit of the path we have resolved + toResolve.shift() + subPath = `${subPath}/${prop}` + + if (CID.isCID(subObject[prop])) { + return { + entry: { + name, + path, + cid, + node, + depth + }, + next: { + cid: subObject[prop], + name: prop, + path: subPath, + toResolve + } + } + } + + subObject = subObject[prop] + } else { + // cannot resolve further + throw errCode(new Error(`No property named ${prop} found in cbor node ${cid.toBaseEncodedString()}`), 'ERR_NO_PROP') + } + } + + return { + entry: { + name, + path, + cid, + node, + depth + } + } +} + +module.exports = resolve + +},{"cids":185,"err-code":399}],402:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') + +const resolvers = { + 'dag-pb': require('./unixfs-v1'), + raw: require('./raw'), + 'dag-cbor': require('./dag-cbor') +} + +const resolve = (cid, name, path, toResolve, depth, ipld) => { + const resolver = resolvers[cid.codec] + + if (!resolver) { + throw errCode(new Error(`No resolver for codec ${cid.codec}`), 'ERR_NO_RESOLVER') + } + + return resolver(cid, name, path, toResolve, resolve, depth, ipld) +} + +module.exports = resolve + +},{"./dag-cbor":401,"./raw":403,"./unixfs-v1":407,"err-code":399}],403:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const extractDataFromBlock = require('../utils/extract-data-from-block') +const validateOffsetAndLength = require('../utils/validate-offset-and-length') + +const rawContent = (node) => { + return function * (options = {}) { + const { + offset, + length + } = validateOffsetAndLength(node.length, options.offset, options.length) + + yield extractDataFromBlock(node, 0, offset, offset + length) + } +} + +const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => { + if (toResolve.length) { + throw errCode(new Error(`No link named ${path} found in raw node ${cid.toBaseEncodedString()}`), 'ERR_NOT_FOUND') + } + + const buf = await ipld.get(cid) + + return { + entry: { + name, + path, + cid, + node: buf, + content: rawContent(buf), + depth + } + } +} + +module.exports = resolve + +},{"../utils/extract-data-from-block":408,"../utils/validate-offset-and-length":410,"err-code":399}],404:[function(require,module,exports){ +'use strict' + +const directoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => { + return async function * (options = {}) { + const offset = options.offset || 0 + const length = options.length || node.Links.length + const links = node.Links.slice(offset, length) + + for (const link of links) { + const result = await resolve(link.Hash, link.Name, `${path}/${link.Name}`, [], depth + 1, ipld) + + yield result.entry + } + } +} + +module.exports = directoryContent + +},{}],405:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const extractDataFromBlock = require('../../../utils/extract-data-from-block') +const validateOffsetAndLength = require('../../../utils/validate-offset-and-length') +const UnixFS = require('ipfs-unixfs') +const errCode = require('err-code') + +async function * emitBytes (ipld, node, start, end, streamPosition = 0) { + // a `raw` node + if (Buffer.isBuffer(node)) { + const buf = extractDataFromBlock(node, streamPosition, start, end) + + if (buf.length) { + yield buf + } + + streamPosition += buf.length + + return streamPosition + } + + let file + + try { + file = UnixFS.unmarshal(node.Data) + } catch (err) { + throw errCode(err, 'ERR_NOT_UNIXFS') + } + + // might be a unixfs `raw` node or have data on intermediate nodes + const nodeHasData = Boolean(file.data && file.data.length) + + if (nodeHasData) { + const buf = extractDataFromBlock(file.data, streamPosition, start, end) + + if (buf.length) { + yield buf + } + + streamPosition += file.data.length + } + + let childStart = streamPosition + + // work out which child nodes contain the requested data + for (let i = 0; i < node.Links.length; i++) { + const childLink = node.Links[i] + const childEnd = streamPosition + file.blockSizes[i] + + if ((start >= childStart && start < childEnd) || // child has offset byte + (end > childStart && end <= childEnd) || // child has end byte + (start < childStart && end > childEnd)) { // child is between offset and end bytes + const child = await ipld.get(childLink.Hash) + + for await (const buf of emitBytes(ipld, child, start, end, streamPosition)) { + streamPosition += buf.length + + yield buf + } + } + + streamPosition = childEnd + childStart = childEnd + 1 + } +} + +const fileContent = (cid, node, unixfs, path, resolve, depth, ipld) => { + return (options = {}) => { + const fileSize = unixfs.fileSize() + + const { + offset, + length + } = validateOffsetAndLength(fileSize, options.offset, options.length) + + const start = offset + const end = offset + length + + return emitBytes(ipld, node, start, end) + } +} + +module.exports = fileContent + +}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) +},{"../../../../../is-buffer/index.js":608,"../../../utils/extract-data-from-block":408,"../../../utils/validate-offset-and-length":410,"err-code":399,"ipfs-unixfs":435}],406:[function(require,module,exports){ +'use strict' + +const hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => { + return (options = {}) => { + return listDirectory(node, path, resolve, depth, ipld, options) + } +} + +async function * listDirectory (node, path, resolve, depth, ipld, options) { + const links = node.Links + + for (const link of links) { + const name = link.Name.substring(2) + + if (name) { + const result = await resolve(link.Hash, name, `${path}/${name}`, [], depth + 1, ipld) + + yield result.entry + } else { + // descend into subshard + node = await ipld.get(link.Hash) + + for await (const file of listDirectory(node, path, resolve, depth, ipld, options)) { + yield file + } + } + } +} + +module.exports = hamtShardedDirectoryContent + +},{}],407:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const UnixFS = require('ipfs-unixfs') +const findShardCid = require('../../utils/find-cid-in-shard') + +const findLinkCid = (node, name) => { + const link = node.Links.find(link => link.Name === name) + + return link && link.Hash +} + +const contentExporters = { + raw: require('./content/file'), + file: require('./content/file'), + directory: require('./content/directory'), + 'hamt-sharded-directory': require('./content/hamt-sharded-directory'), + metadata: (cid, node, unixfs, path, resolve, depth, ipld) => {}, + symlink: (cid, node, unixfs, path, resolve, depth, ipld) => {} +} + +const unixFsResolver = async (cid, name, path, toResolve, resolve, depth, ipld) => { + const node = await ipld.get(cid) + let unixfs + let next + + if (!name) { + name = cid.toBaseEncodedString() + } + + try { + unixfs = UnixFS.unmarshal(node.Data) + } catch (err) { + // non-UnixFS dag-pb node? It could happen. + throw errCode(err, 'ERR_NOT_UNIXFS') + } + + if (!path) { + path = name + } + + if (toResolve.length) { + let linkCid + + if (unixfs && unixfs.type === 'hamt-sharded-directory') { + // special case - unixfs v1 hamt shards + linkCid = await findShardCid(node, toResolve[0], ipld) + } else { + linkCid = findLinkCid(node, toResolve[0]) + } + + if (!linkCid) { + throw errCode(new Error(`file does not exist`), 'ERR_NOT_FOUND') + } + + // remove the path component we have resolved + const nextName = toResolve.shift() + const nextPath = `${path}/${nextName}` + + next = { + cid: linkCid, + toResolve, + name: nextName, + path: nextPath + } + } + + return { + entry: { + name, + path, + cid, + node, + content: contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, ipld), + unixfs, + depth + }, + next + } +} + +module.exports = unixFsResolver + +},{"../../utils/find-cid-in-shard":409,"./content/directory":404,"./content/file":405,"./content/hamt-sharded-directory":406,"err-code":399,"ipfs-unixfs":435}],408:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +module.exports = function extractDataFromBlock (block, blockStart, requestedStart, requestedEnd) { + const blockLength = block.length + const blockEnd = blockStart + blockLength + + if (requestedStart >= blockEnd || requestedEnd < blockStart) { + // If we are looking for a byte range that is starts after the start of the block, + // return an empty block. This can happen when internal nodes contain data + return Buffer.alloc(0) + } + + if (requestedEnd >= blockStart && requestedEnd < blockEnd) { + // If the end byte is in the current block, truncate the block to the end byte + block = block.slice(0, requestedEnd - blockStart) + } + + if (requestedStart >= blockStart && requestedStart < blockEnd) { + // If the start byte is in the current block, skip to the start byte + block = block.slice(requestedStart - blockStart) + } + + return block +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181}],409:[function(require,module,exports){ +'use strict' + +const Bucket = require('hamt-sharding/src/bucket') +const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') + +const addLinksToHamtBucket = (links, bucket, rootBucket) => { + return Promise.all( + links.map(link => { + if (link.Name.length === 2) { + const pos = parseInt(link.Name, 16) + + return bucket._putObjectAt(pos, new Bucket({ + hashFn: DirSharded.hashFn + }, bucket, pos)) + } + + return rootBucket.put(link.Name.substring(2), true) + }) + ) +} + +const toPrefix = (position) => { + return position + .toString('16') + .toUpperCase() + .padStart(2, '0') + .substring(0, 2) +} + +const toBucketPath = (position) => { + let bucket = position.bucket + const path = [] + + while (bucket._parent) { + path.push(bucket) + + bucket = bucket._parent + } + + path.push(bucket) + + return path.reverse() +} + +const findShardCid = async (node, name, ipld, context) => { + if (!context) { + context = { + rootBucket: new Bucket({ + hashFn: DirSharded.hashFn + }), + hamtDepth: 1 + } + + context.lastBucket = context.rootBucket + } + + await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket) + + const position = await context.rootBucket._findNewBucketAndPos(name) + let prefix = toPrefix(position.pos) + const bucketPath = toBucketPath(position) + + if (bucketPath.length > (context.hamtDepth)) { + context.lastBucket = bucketPath[context.hamtDepth] + + prefix = toPrefix(context.lastBucket._posAtParent) + } + + const link = node.Links.find(link => { + const entryPrefix = link.Name.substring(0, 2) + const entryName = link.Name.substring(2) + + if (entryPrefix !== prefix) { + // not the entry or subshard we're looking for + return + } + + if (entryName && entryName !== name) { + // not the entry we're looking for + return + } + + return true + }) + + if (!link) { + return null + } + + if (link.Name.substring(2) === name) { + return link.Hash + } + + context.hamtDepth++ + + node = await ipld.get(link.Hash) + + return findShardCid(node, name, ipld, context) +} + +module.exports = findShardCid + +},{"hamt-sharding/src/bucket":286,"ipfs-unixfs-importer/src/dir-sharded":428}],410:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') + +const validateOffsetAndLength = (size, offset, length) => { + if (!offset) { + offset = 0 + } + + if (offset < 0) { + throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') + } + + if (offset > size) { + throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS') + } + + if (!length && length !== 0) { + length = size - offset + } + + if (length < 0) { + throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') + } + + if (offset + length > size) { + length = size - offset + } + + return { + offset, + length + } +} + +module.exports = validateOffsetAndLength + +},{"err-code":399}],411:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],412:[function(require,module,exports){ +'use strict' + +const { Buffer } = require('buffer') +const blake = require('blakejs') + +const minB = 0xb201 +const minS = 0xb241 + +const blake2b = { + init: blake.blake2bInit, + update: blake.blake2bUpdate, + digest: blake.blake2bFinal +} + +const blake2s = { + init: blake.blake2sInit, + update: blake.blake2sUpdate, + digest: blake.blake2sFinal +} + +// Note that although this function doesn't do any asynchronous work, we mark +// the function as async because it must return a Promise to match the API +// for other functions that do perform asynchronous work (see sha.browser.js) +const makeB2Hash = (size, hf) => async (data) => { + const ctx = hf.init(size, null) + hf.update(ctx, data) + return Buffer.from(hf.digest(ctx)) +} + +module.exports = (table) => { + for (let i = 0; i < 64; i++) { + table[minB + i] = makeB2Hash(i + 1, blake2b) + } + for (let i = 0; i < 32; i++) { + table[minS + i] = makeB2Hash(i + 1, blake2s) + } +} + +},{"blakejs":132,"buffer":181}],413:[function(require,module,exports){ +'use strict' + +const { Buffer } = require('buffer') +const sha3 = require('js-sha3') +const mur = require('murmurhash3js-revisited') +const sha = require('./sha') +const { fromNumberTo32BitBuf } = require('./utils') + +// Note that although this function doesn't do any asynchronous work, we mark +// the function as async because it must return a Promise to match the API +// for other functions that do perform asynchronous work (see sha.browser.js) +const hash = (algorithm) => async (data) => { + switch (algorithm) { + case 'sha3-224': + return Buffer.from(sha3.sha3_224.arrayBuffer(data)) + case 'sha3-256': + return Buffer.from(sha3.sha3_256.arrayBuffer(data)) + case 'sha3-384': + return Buffer.from(sha3.sha3_384.arrayBuffer(data)) + case 'sha3-512': + return Buffer.from(sha3.sha3_512.arrayBuffer(data)) + case 'shake-128': + return Buffer.from(sha3.shake128.create(128).update(data).arrayBuffer()) + case 'shake-256': + return Buffer.from(sha3.shake256.create(256).update(data).arrayBuffer()) + case 'keccak-224': + return Buffer.from(sha3.keccak224.arrayBuffer(data)) + case 'keccak-256': + return Buffer.from(sha3.keccak256.arrayBuffer(data)) + case 'keccak-384': + return Buffer.from(sha3.keccak384.arrayBuffer(data)) + case 'keccak-512': + return Buffer.from(sha3.keccak512.arrayBuffer(data)) + case 'murmur3-128': + return Buffer.from(mur.x64.hash128(data), 'hex') + case 'murmur3-32': + return fromNumberTo32BitBuf(mur.x86.hash32(data)) + + default: + throw new TypeError(`${algorithm} is not a supported algorithm`) + } +} + +module.exports = { + sha1: sha('sha1'), + sha2256: sha('sha2-256'), + sha2512: sha('sha2-512'), + dblSha2256: sha('dbl-sha2-256'), + sha3224: hash('sha3-224'), + sha3256: hash('sha3-256'), + sha3384: hash('sha3-384'), + sha3512: hash('sha3-512'), + shake128: hash('shake-128'), + shake256: hash('shake-256'), + keccak224: hash('keccak-224'), + keccak256: hash('keccak-256'), + keccak384: hash('keccak-384'), + keccak512: hash('keccak-512'), + murmur3128: hash('murmur3-128'), + murmur332: hash('murmur3-32'), + addBlake: require('./blake') +} + +},{"./blake":412,"./sha":415,"./utils":416,"buffer":181,"js-sha3":666,"murmurhash3js-revisited":1177}],414:[function(require,module,exports){ +'use strict' + +const { Buffer } = require('buffer') +const errcode = require('err-code') +const multihash = require('multihashes') +const crypto = require('./crypto') + +/** + * Hash the given `buf` using the algorithm specified by `alg`. + * @param {Buffer} buf - The value to hash. + * @param {number|string} alg - The algorithm to use eg 'sha1' + * @param {number} [length] - Optionally trim the result to this length. + * @returns {Promise} + */ +async function Multihashing (buf, alg, length) { + const digest = await Multihashing.digest(buf, alg, length) + return multihash.encode(digest, alg, length) +} + +/** + * The `buffer` module for easy use in the browser. + * + * @type {Buffer} + */ +Multihashing.Buffer = Buffer // for browser things + +/** + * Expose multihash itself, to avoid silly double requires. + */ +Multihashing.multihash = multihash + +/** + * @param {Buffer} buf - The value to hash. + * @param {number|string} alg - The algorithm to use eg 'sha1' + * @param {number} [length] - Optionally trim the result to this length. + * @returns {Promise} + */ +Multihashing.digest = async (buf, alg, length) => { + const hash = Multihashing.createHash(alg) + const digest = await hash(buf) + return length ? digest.slice(0, length) : digest +} + +/** + * Creates a function that hashes with the given algorithm + * + * @param {string|number} alg - The algorithm to use eg 'sha1' + * + * @returns {function} - The hash function corresponding to `alg` + */ +Multihashing.createHash = function (alg) { + if (!alg) { + throw errcode('hash algorithm must be specified', 'ERR_HASH_ALGORITHM_NOT_SPECIFIED') + } + + alg = multihash.coerceCode(alg) + if (!Multihashing.functions[alg]) { + throw errcode(`multihash function '${alg}' not yet supported`, 'ERR_HASH_ALGORITHM_NOT_SUPPORTED') + } + + return Multihashing.functions[alg] +} + +/** + * Mapping of multihash codes to their hashing functions. + * @type {Object} + */ +Multihashing.functions = { + // sha1 + 0x11: crypto.sha1, + // sha2-256 + 0x12: crypto.sha2256, + // sha2-512 + 0x13: crypto.sha2512, + // sha3-512 + 0x14: crypto.sha3512, + // sha3-384 + 0x15: crypto.sha3384, + // sha3-256 + 0x16: crypto.sha3256, + // sha3-224 + 0x17: crypto.sha3224, + // shake-128 + 0x18: crypto.shake128, + // shake-256 + 0x19: crypto.shake256, + // keccak-224 + 0x1A: crypto.keccak224, + // keccak-256 + 0x1B: crypto.keccak256, + // keccak-384 + 0x1C: crypto.keccak384, + // keccak-512 + 0x1D: crypto.keccak512, + // murmur3-128 + 0x22: crypto.murmur3128, + // murmur3-32 + 0x23: crypto.murmur332, + // dbl-sha2-256 + 0x56: crypto.dblSha2256 +} + +// add blake functions +crypto.addBlake(Multihashing.functions) + +Multihashing.validate = async (buf, hash) => { + const newHash = await Multihashing(buf, multihash.decode(hash).name) + + return Buffer.compare(hash, newHash) === 0 +} + +module.exports = Multihashing + +},{"./crypto":413,"buffer":181,"err-code":411,"multihashes":1157}],415:[function(require,module,exports){ +'use strict' + +const { Buffer } = require('buffer') + +const crypto = self.crypto || self.msCrypto + +module.exports = (algorithm) => { + if (typeof self === 'undefined' || (!self.crypto && !self.msCrypto)) { + throw new Error( + 'Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context' + ) + } + + return async (data) => { + switch (algorithm) { + case 'sha1': + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-1' }, data)) + case 'sha2-256': + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, data)) + case 'sha2-512': + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-512' }, data)) + case 'dbl-sha2-256': { + const d = await crypto.subtle.digest({ name: 'SHA-256' }, data) + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, d)) + } + default: + throw new Error(`${algorithm} is not a supported algorithm`) + } + } +} + +},{"buffer":181}],416:[function(require,module,exports){ +'use strict' + +const { Buffer } = require('buffer') + +const fromNumberTo32BitBuf = (number) => { + const bytes = new Array(4) + + for (let i = 0; i < 4; i++) { + bytes[i] = number & 0xff + number = number >> 8 + } + + return Buffer.from(bytes) +} + +module.exports = { + fromNumberTo32BitBuf +} + +},{"buffer":181}],417:[function(require,module,exports){ +'use strict' + +const BufferList = require('bl') + +module.exports = async function * fixedSizeChunker (source, options) { + let bl = new BufferList() + let currentLength = 0 + let emitted = false + const maxChunkSize = options.maxChunkSize + + for await (const buffer of source) { + bl.append(buffer) + + currentLength += buffer.length + + while (currentLength >= maxChunkSize) { + yield bl.slice(0, maxChunkSize) + emitted = true + + // throw away consumed bytes + if (maxChunkSize === bl.length) { + bl = new BufferList() + currentLength = 0 + } else { + const newBl = new BufferList() + newBl.append(bl.shallowSlice(maxChunkSize)) + bl = newBl + + // update our offset + currentLength -= maxChunkSize + } + } + } + + if (!emitted || currentLength) { + // return any remaining bytes or an empty buffer + yield bl.slice(0, currentLength) + } +} + +},{"bl":112}],418:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') + +const chunkers = { + fixed: require('../chunker/fixed-size'), + rabin: require('../chunker/rabin') +} + +module.exports = (type, source, options) => { + const chunker = chunkers[type] + + if (!chunker) { + throw errCode(new Error(`Unknkown chunker named ${type}`), 'ERR_UNKNOWN_CHUNKER') + } + + return chunker(source, options) +} + +},{"../chunker/fixed-size":417,"../chunker/rabin":419,"err-code":411}],419:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const BufferList = require('bl') +const { create } = require('rabin-wasm') +const errcode = require('err-code') + +module.exports = async function * rabinChunker (source, options) { + const rabin = jsRabin() + + let min, max, avg + + if (options.minChunkSize && options.maxChunkSize && options.avgChunkSize) { + avg = options.avgChunkSize + min = options.minChunkSize + max = options.maxChunkSize + } else if (!options.avgChunkSize) { + throw errcode(new Error('please specify an average chunk size'), 'ERR_INVALID_AVG_CHUNK_SIZE') + } else { + avg = options.avgChunkSize + min = avg / 3 + max = avg + (avg / 2) + } + + // validate min/max/avg in the same way as go + if (min < 16) { + throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE') + } + + if (max < min) { + max = min + } + + if (avg < min) { + avg = min + } + + const sizepow = Math.floor(Math.log2(avg)) + + for await (const chunk of rabin(source, { + min: min, + max: max, + bits: sizepow, + window: options.window, + polynomial: options.polynomial + })) { + yield chunk + } +} + +const jsRabin = () => { + return async function * (source, options) { + const r = await create(options.bits, options.min, options.max, options.window) + const buffers = new BufferList() + let pending = [] + + for await (const chunk of source) { + buffers.append(chunk) + pending.push(chunk) + + const sizes = r.fingerprint(Buffer.concat(pending)) + pending = [] + + for (let i = 0; i < sizes.length; i++) { + var size = sizes[i] + var buf = buffers.slice(0, size) + buffers.consume(size) + + yield buf + } + } + + if (buffers.length) { + yield buffers.slice(0) + } + } +} + +}).call(this,require("buffer").Buffer) +},{"bl":112,"buffer":181,"err-code":411,"rabin-wasm":1364}],420:[function(require,module,exports){ +'use strict' + +const UnixFS = require('ipfs-unixfs') +const persist = require('../utils/persist') +const { + DAGNode +} = require('ipld-dag-pb') + +const dirBuilder = async (item, ipld, options) => { + const unixfs = new UnixFS('directory') + const node = DAGNode.create(unixfs.marshal(), []) + const cid = await persist(node, ipld, options) + let path = item.path + + return { + cid, + path, + unixfs, + node + } +} + +module.exports = dirBuilder + +},{"../utils/persist":433,"ipfs-unixfs":435,"ipld-dag-pb":589}],421:[function(require,module,exports){ +'use strict' + +const batch = require('async-iterator-batch') + +async function * balanced (source, reduce, options) { + yield await reduceToParents(source, reduce, options) +} + +async function reduceToParents (source, reduce, options) { + const roots = [] + + for await (const chunked of batch(source, options.maxChildrenPerNode)) { + roots.push(await reduce(chunked)) + } + + if (roots.length > 1) { + return reduceToParents(roots, reduce, options) + } + + return roots[0] +} + +module.exports = balanced + +},{"async-iterator-batch":31}],422:[function(require,module,exports){ +'use strict' + +const batch = require('async-iterator-batch') + +module.exports = async function * (source, reduce) { + const roots = [] + + for await (const chunk of batch(source, Infinity)) { + roots.push(await reduce(chunk)) + } + + yield roots[0] +} + +},{"async-iterator-batch":31}],423:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const UnixFS = require('ipfs-unixfs') +const persist = require('../../utils/persist') +const { + DAGNode, + DAGLink +} = require('ipld-dag-pb') +const all = require('async-iterator-all') + +const dagBuilders = { + flat: require('./flat'), + balanced: require('./balanced'), + trickle: require('./trickle') +} + +async function * buildFile (source, ipld, options) { + let count = -1 + let previous + + for await (const buffer of source) { + count++ + options.progress(buffer.length) + let node + let unixfs + + let opts = { + ...options + } + + if (options.rawLeaves) { + node = buffer + + opts.codec = 'raw' + opts.cidVersion = 1 + } else { + unixfs = new UnixFS(options.leafType, buffer) + node = DAGNode.create(unixfs.marshal(), []) + } + + const cid = await persist(node, ipld, opts) + + const entry = { + cid: cid, + unixfs, + node + } + + if (count === 0) { + previous = entry + continue + } else if (count === 1) { + yield previous + previous = null + } + + yield entry + } + + if (previous) { + previous.single = true + yield previous + } +} + +const reduce = (file, ipld, options) => { + return async function (leaves) { + if (leaves.length === 1 && leaves[0].single && options.reduceSingleLeafToSelf) { + const leaf = leaves[0] + + return { + cid: leaf.cid, + path: file.path, + name: (file.path || '').split('/').pop(), + unixfs: leaf.unixfs, + node: leaf.node + } + } + + // create a parent node and add all the leaves + const f = new UnixFS('file') + + const links = leaves + .filter(leaf => { + if (leaf.cid.codec === 'raw' && leaf.node.length) { + return true + } + + if (!leaf.unixfs.data && leaf.unixfs.fileSize()) { + return true + } + + return Boolean(leaf.unixfs.data.length) + }) + .map((leaf) => { + if (leaf.cid.codec === 'raw') { + // node is a leaf buffer + f.addBlockSize(leaf.node.length) + + return new DAGLink(leaf.name, leaf.node.length, leaf.cid) + } + + if (!leaf.unixfs.data) { + // node is an intermediate node + f.addBlockSize(leaf.unixfs.fileSize()) + } else { + // node is a unixfs 'file' leaf node + f.addBlockSize(leaf.unixfs.data.length) + } + + return new DAGLink(leaf.name, leaf.node.size, leaf.cid) + }) + + const node = DAGNode.create(f.marshal(), links) + const cid = await persist(node, ipld, options) + + return { + cid, + path: file.path, + unixfs: f, + node, + size: node.size + } + } +} + +const fileBuilder = async (file, source, ipld, options) => { + const dagBuilder = dagBuilders[options.strategy] + + if (!dagBuilder) { + throw errCode(new Error(`Unknown importer build strategy name: ${options.strategy}`), 'ERR_BAD_STRATEGY') + } + + const roots = await all(dagBuilder(buildFile(source, ipld, options), reduce(file, ipld, options), options.builderOptions)) + + if (roots.length > 1) { + throw errCode(new Error('expected a maximum of 1 roots and got ' + roots.length), 'ETOOMANYROOTS') + } + + return roots[0] +} + +module.exports = fileBuilder + +},{"../../utils/persist":433,"./balanced":421,"./flat":422,"./trickle":424,"async-iterator-all":30,"err-code":411,"ipfs-unixfs":435,"ipld-dag-pb":589}],424:[function(require,module,exports){ +'use strict' + +const batch = require('async-iterator-batch') + +module.exports = function * trickleReduceToRoot (source, reduce, options) { + yield trickleStream(source, reduce, options) +} + +async function trickleStream (source, reduce, options) { + let root + let iteration = 0 + let maxDepth = 1 + let subTree = root = new Root(options.layerRepeat) + + for await (const layer of batch(source, options.maxChildrenPerNode)) { + if (subTree.isFull()) { + if (subTree !== root) { + root.addChild(await subTree.reduce(reduce)) + } + + if (iteration && iteration % options.layerRepeat === 0) { + maxDepth++ + } + + subTree = new SubTree(maxDepth, options.layerRepeat, iteration) + + iteration++ + } + + subTree.append(layer) + } + + if (subTree && subTree !== root) { + root.addChild(await subTree.reduce(reduce)) + } + + return root.reduce(reduce) +} + +class SubTree { + constructor (maxDepth, layerRepeat, iteration) { + this.maxDepth = maxDepth + this.layerRepeat = layerRepeat + this.currentDepth = 1 + this.iteration = iteration + + this.root = this.node = this.parent = { + children: [], + depth: this.currentDepth, + maxDepth, + maxChildren: (this.maxDepth - this.currentDepth) * this.layerRepeat + } + } + + isFull () { + if (!this.root.data) { + return false + } + + if (this.currentDepth < this.maxDepth && this.node.maxChildren) { + // can descend + this._addNextNodeToParent(this.node) + + return false + } + + // try to find new node from node.parent + const distantRelative = this._findParent(this.node, this.currentDepth) + + if (distantRelative) { + this._addNextNodeToParent(distantRelative) + + return false + } + + return true + } + + _addNextNodeToParent (parent) { + this.parent = parent + + // find site for new node + const nextNode = { + children: [], + depth: parent.depth + 1, + parent, + maxDepth: this.maxDepth, + maxChildren: Math.floor(parent.children.length / this.layerRepeat) * this.layerRepeat + } + + parent.children.push(nextNode) + + this.currentDepth = nextNode.depth + this.node = nextNode + } + + append (layer) { + this.node.data = layer + } + + reduce (reduce) { + return this._reduce(this.root, reduce) + } + + async _reduce (node, reduce) { + let children = [] + + if (node.children.length) { + children = await Promise.all( + node.children + .filter(child => child.data) + .map(child => this._reduce(child, reduce)) + ) + } + + return reduce(node.data.concat(children)) + } + + _findParent (node, depth) { + const parent = node.parent + + if (!parent || parent.depth === 0) { + return + } + + if (parent.children.length === parent.maxChildren || !parent.maxChildren) { + // this layer is full, may be able to traverse to a different branch + return this._findParent(parent, depth) + } + + return parent + } +} + +class Root extends SubTree { + constructor (layerRepeat) { + super(0, layerRepeat) + + this.root.depth = 0 + this.currentDepth = 1 + } + + addChild (child) { + this.root.children.push(child) + } + + reduce (reduce) { + return reduce(this.root.data.concat(this.root.children)) + } +} + +},{"async-iterator-batch":31}],425:[function(require,module,exports){ +'use strict' + +const dirBuilder = require('./dir') +const fileBuilder = require('./file') +const createChunker = require('../chunker') +const validateChunks = require('./validate-chunks') + +async function * dagBuilder (source, ipld, options) { + for await (const entry of source) { + if (entry.path) { + if (entry.path.substring(0, 2) === './') { + options.wrapWithDirectory = true + } + + entry.path = entry.path + .split('/') + .filter(path => path && path !== '.') + .join('/') + } + + if (entry.content) { + let source = entry.content + + // wrap in iterator if it is array-like or not an iterator + if ((!source[Symbol.asyncIterator] && !source[Symbol.iterator]) || source.length !== undefined) { + source = { + [Symbol.iterator]: function * () { + yield entry.content + } + } + } + + const chunker = createChunker(options.chunker, validateChunks(source), options.chunkerOptions) + + // item is a file + yield fileBuilder(entry, chunker, ipld, options) + } else { + // item is a directory + yield dirBuilder(entry, ipld, options) + } + } +} + +module.exports = dagBuilder + +},{"../chunker":418,"./dir":420,"./file":423,"./validate-chunks":426}],426:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const errCode = require('err-code') + +// make sure the content only emits buffer-a-likes +async function * validateChunks (source) { + for await (const content of source) { + if (content.length === undefined) { + throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') + } + + if (typeof content === 'string' || content instanceof String) { + yield Buffer.from(content, 'utf8') + } else if (Array.isArray(content)) { + yield Buffer.from(content) + } else { + yield content + } + } +} + +module.exports = validateChunks + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"err-code":411}],427:[function(require,module,exports){ +'use strict' + +const { + DAGLink, + DAGNode +} = require('ipld-dag-pb') +const UnixFS = require('ipfs-unixfs') +const Dir = require('./dir') +const persist = require('./utils/persist') + +class DirFlat extends Dir { + constructor (props, options) { + super(props, options) + this._children = {} + } + + put (name, value) { + this.cid = undefined + this.size = undefined + this._children[name] = value + } + + get (name) { + return this._children[name] + } + + childCount () { + return Object.keys(this._children).length + } + + directChildrenCount () { + return this.childCount() + } + + onlyChild () { + return this._children[Object.keys(this._children)[0]] + } + + * eachChildSeries () { + const keys = Object.keys(this._children) + + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + + yield { + key: key, + child: this._children[key] + } + } + } + + async * flush (path, ipld) { + const children = Object.keys(this._children) + const links = [] + + for (let i = 0; i < children.length; i++) { + let child = this._children[children[i]] + + if (typeof child.flush === 'function') { + for await (const entry of child.flush(child.path, ipld)) { + child = entry + + yield child + } + } + + links.push(new DAGLink(children[i], child.node.length || child.node.size, child.cid)) + } + + const unixfs = new UnixFS('directory') + let node = DAGNode.create(unixfs.marshal(), links) + const cid = await persist(node, ipld, this.options) + + this.cid = cid + this.size = node.size + + yield { + cid, + unixfs, + path, + node + } + } +} + +module.exports = DirFlat + +},{"./dir":429,"./utils/persist":433,"ipfs-unixfs":435,"ipld-dag-pb":589}],428:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const { + DAGLink, + DAGNode +} = require('ipld-dag-pb') +const UnixFS = require('ipfs-unixfs') +const multihashing = require('multihashing-async') +const Dir = require('./dir') +const persist = require('./utils/persist') +const Bucket = require('hamt-sharding') +const extend = require('deep-extend') + +const hashFn = async function (value) { + const hash = await multihashing(Buffer.from(value, 'utf8'), 'murmur3-128') + + // Multihashing inserts preamble of 2 bytes. Remove it. + // Also, murmur3 outputs 128 bit but, accidently, IPFS Go's + // implementation only uses the first 64, so we must do the same + // for parity.. + const justHash = hash.slice(2, 10) + const length = justHash.length + const result = Buffer.alloc(length) + // TODO: invert buffer because that's how Go impl does it + for (let i = 0; i < length; i++) { + result[length - i - 1] = justHash[i] + } + + return result +} +hashFn.code = 0x22 // TODO: get this from multihashing-async? + +const defaultOptions = { + hashFn: hashFn +} + +class DirSharded extends Dir { + constructor (props, options) { + options = extend({}, defaultOptions, options) + + super(props, options) + + this._bucket = Bucket(options) + } + + async put (name, value) { + await this._bucket.put(name, value) + } + + get (name) { + return this._bucket.get(name) + } + + childCount () { + return this._bucket.leafCount() + } + + directChildrenCount () { + return this._bucket.childrenCount() + } + + onlyChild () { + return this._bucket.onlyChild() + } + + async * eachChildSeries () { + for await (const { key, value } of this._bucket.eachLeafSeries()) { + yield { + key, + child: value + } + } + } + + async * flush (path, ipld) { + for await (const entry of flush(path, this._bucket, ipld, this.options)) { + yield entry + } + } +} + +module.exports = DirSharded + +module.exports.hashFn = hashFn + +async function * flush (path, bucket, ipld, options) { + const children = bucket._children + const links = [] + + for (let i = 0; i < children.length; i++) { + const child = children.get(i) + + if (!child) { + continue + } + + const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0') + + if (Bucket.isBucket(child)) { + let shard + + for await (const subShard of await flush('', child, ipld, options)) { + shard = subShard + } + + links.push(await new DAGLink(labelPrefix, shard.node.size, shard.cid)) + } else if (typeof child.value.flush === 'function') { + const dir = child.value + let flushedDir + + for await (const entry of dir.flush(dir.path, ipld)) { + flushedDir = entry + + yield flushedDir + } + + const label = labelPrefix + child.key + links.push(new DAGLink(label, flushedDir.node.size, flushedDir.cid)) + } else { + const value = child.value + + if (!value.node) { + if (value.cid) { + value.node = await ipld.get(value.cid) + } else { + continue + } + } + + const label = labelPrefix + child.key + const size = value.node.length || value.node.size || value.node.Size + + links.push(await new DAGLink(label, size, value.cid)) + } + } + + // go-ipfs uses little endian, that's why we have to + // reverse the bit field before storing it + const data = Buffer.from(children.bitField().reverse()) + const dir = new UnixFS('hamt-sharded-directory', data) + dir.fanout = bucket.tableSize() + dir.hashType = options.hashFn.code + + const node = DAGNode.create(dir.marshal(), links) + const cid = await persist(node, ipld, options) + + yield { + cid, + node, + unixfs: dir, + path + } +} + +}).call(this,require("buffer").Buffer) +},{"./dir":429,"./utils/persist":433,"buffer":181,"deep-extend":215,"hamt-sharding":289,"ipfs-unixfs":435,"ipld-dag-pb":589,"multihashing-async":414}],429:[function(require,module,exports){ +'use strict' + +module.exports = class Dir { + constructor (props, options) { + this.options = options || {} + Object.assign(this, props) + } +} + +},{}],430:[function(require,module,exports){ +'use strict' + +const DirSharded = require('./dir-sharded') + +module.exports = async function flatToShard (child, dir, threshold, options) { + let newDir = dir + + if (dir.flat && dir.directChildrenCount() >= threshold) { + newDir = await convertToShard(dir, options) + } + + const parent = newDir.parent + + if (parent) { + if (newDir !== dir) { + if (child) { + child.parent = newDir + } + + await parent.put(newDir.parentKey, newDir) + } + + if (parent) { + return flatToShard(newDir, parent, threshold, options) + } + } + + return newDir +} + +async function convertToShard (oldDir, options) { + const newDir = new DirSharded({ + root: oldDir.root, + dir: true, + parent: oldDir.parent, + parentKey: oldDir.parentKey, + path: oldDir.path, + dirty: oldDir.dirty, + flat: false + }, options) + + for await (const { key, child } of oldDir.eachChildSeries()) { + await newDir.put(key, child) + } + + return newDir +} + +},{"./dir-sharded":428}],431:[function(require,module,exports){ +'use strict' + +const { superstruct } = require('superstruct') +const dagBuilder = require('./dag-builder') +const treeBuilder = require('./tree-builder') +const mh = require('multihashes') + +const struct = superstruct({ + types: { + codec: v => ['dag-pb', 'dag-cbor', 'raw'].includes(v), + hashAlg: v => Object.keys(mh.names).includes(v), + leafType: v => ['file', 'raw'].includes(v) + } +}) + +const ChunkerOptions = struct({ + minChunkSize: 'number?', + maxChunkSize: 'number?', + avgChunkSize: 'number?', + window: 'number?', + polynomial: 'number?' +}, { + maxChunkSize: 262144, + avgChunkSize: 262144, + window: 16, + polynomial: 17437180132763653 // https://github.com/ipfs/go-ipfs-chunker/blob/d0125832512163708c0804a3cda060e21acddae4/rabin.go#L11 +}) + +const BuilderOptions = struct({ + maxChildrenPerNode: 'number?', + layerRepeat: 'number?' +}, { + maxChildrenPerNode: 174, + layerRepeat: 4 +}) + +const Options = struct({ + chunker: struct.enum(['fixed', 'rabin']), + rawLeaves: 'boolean?', + hashOnly: 'boolean?', + strategy: struct.enum(['balanced', 'flat', 'trickle']), + reduceSingleLeafToSelf: 'boolean?', + codec: 'codec?', + format: 'codec?', + hashAlg: 'hashAlg?', + leafType: 'leafType?', + cidVersion: 'number?', + progress: 'function?', + wrapWithDirectory: 'boolean?', + shardSplitThreshold: 'number?', + onlyHash: 'boolean?', + chunkerOptions: ChunkerOptions, + builderOptions: BuilderOptions, + + wrap: 'boolean?', + pin: 'boolean?', + recursive: 'boolean?', + ignore: 'array?', + hidden: 'boolean?', + preload: 'boolean?' +}, { + chunker: 'fixed', + strategy: 'balanced', + rawLeaves: false, + reduceSingleLeafToSelf: true, + codec: 'dag-pb', + hashAlg: 'sha2-256', + leafType: 'file', + cidVersion: 0, + progress: () => () => {}, + shardSplitThreshold: 1000 +}) + +module.exports = async function * (source, ipld, options = {}) { + const opts = Options(options) + + if (options.cidVersion > 0 && options.rawLeaves === undefined) { + // if the cid version is 1 or above, use raw leaves as this is + // what go does. + opts.rawLeaves = true + } + + if (options.hashAlg !== undefined && options.rawLeaves === undefined) { + // if a non-default hash alg has been specified, use raw leaves as this is + // what go does. + opts.rawLeaves = true + } + + // go-ifps trickle dag defaults to unixfs raw leaves, balanced dag defaults to file leaves + if (options.strategy === 'trickle') { + opts.leafType = 'raw' + opts.reduceSingleLeafToSelf = false + } + + if (options.format) { + options.codec = options.format + } + + for await (const entry of treeBuilder(dagBuilder(source, ipld, opts), ipld, opts)) { + yield { + cid: entry.cid, + path: entry.path, + unixfs: entry.unixfs, + size: entry.size + } + } +} + +},{"./dag-builder":425,"./tree-builder":432,"multihashes":1157,"superstruct":1498}],432:[function(require,module,exports){ +'use strict' + +const DirFlat = require('./dir-flat') +const flatToShard = require('./flat-to-shard') +const Dir = require('./dir') +const toPathComponents = require('./utils/to-path-components') +const errCode = require('err-code') +const first = require('async-iterator-first') + +async function addToTree (elem, tree, options) { + const pathElems = toPathComponents(elem.path || '') + const lastIndex = pathElems.length - 1 + let parent = tree + let currentPath = '' + + for (let i = 0; i < pathElems.length; i++) { + const pathElem = pathElems[i] + + currentPath += `${currentPath ? '/' : ''}${pathElem}` + + const last = (i === lastIndex) + parent.dirty = true + parent.cid = null + parent.size = null + + if (last) { + await parent.put(pathElem, elem) + tree = await flatToShard(null, parent, options.shardSplitThreshold, options) + } else { + let dir = await parent.get(pathElem) + + if (!dir || !(dir instanceof Dir)) { + dir = new DirFlat({ + dir: true, + parent: parent, + parentKey: pathElem, + path: currentPath, + dirty: true, + flat: true + }, options) + } + + await parent.put(pathElem, dir) + + parent = dir + } + } + + return tree +} + +async function * treeBuilder (source, ipld, options) { + let tree = new DirFlat({ + root: true, + dir: true, + path: '', + dirty: true, + flat: true + }, options) + + for await (const entry of source) { + tree = await addToTree(entry, tree, options) + + yield entry + } + + if (tree) { + if (!options.wrapWithDirectory) { + if (tree.childCount() > 1) { + throw errCode(new Error('detected more than one root'), 'ERR_MORE_THAN_ONE_ROOT') + } + + const unwrapped = await first(tree.eachChildSeries()) + + if (!unwrapped) { + return + } + + tree = unwrapped.child + } + + if (!tree.dir) { + return + } + + for await (const entry of tree.flush(tree.path, ipld)) { + yield entry + } + } +} + +module.exports = treeBuilder + +},{"./dir":429,"./dir-flat":427,"./flat-to-shard":430,"./utils/to-path-components":434,"async-iterator-first":32,"err-code":411}],433:[function(require,module,exports){ +'use strict' + +const mh = require('multihashes') +const mc = require('multicodec') + +const persist = (node, ipld, options) => { + if (!options.codec && node.length) { + options.cidVersion = 1 + options.codec = 'raw' + } + + if (isNaN(options.hashAlg)) { + options.hashAlg = mh.names[options.hashAlg] + } + + if (options.hashAlg !== mh.names['sha2-256']) { + options.cidVersion = 1 + } + + if (options.format) { + options.codec = options.format + } + + const format = mc[options.codec.toUpperCase().replace(/-/g, '_')] + + return ipld.put(node, format, options) +} + +module.exports = persist + +},{"multicodec":1151,"multihashes":1157}],434:[function(require,module,exports){ +arguments[4][376][0].apply(exports,arguments) +},{"dup":376}],435:[function(require,module,exports){ +'use strict' + +const protons = require('protons') +const pb = protons(require('./unixfs.proto')) +// encode/decode +const unixfsData = pb.Data +// const unixfsMetadata = pb.MetaData // encode/decode + +const types = [ + 'raw', + 'directory', + 'file', + 'metadata', + 'symlink', + 'hamt-sharded-directory' +] + +const dirTypes = [ + 'directory', + 'hamt-sharded-directory' +] + +function Data (type, data) { + if (!(this instanceof Data)) { + return new Data(type, data) + } + if (types.indexOf(type) === -1) { + throw new Error('Type: ' + type + ' is not valid') + } + + this.type = type + this.data = data + this.blockSizes = [] + + this.addBlockSize = (size) => { + this.blockSizes.push(size) + } + + this.removeBlockSize = (index) => { + this.blockSizes.splice(index, 1) + } + + // data.length + blockSizes + this.fileSize = () => { + if (dirTypes.indexOf(this.type) >= 0) { + // dirs don't have file size + return undefined + } + + let sum = 0 + this.blockSizes.forEach((size) => { + sum += size + }) + if (data) { + sum += data.length + } + return sum + } + + // encode to protobuf + this.marshal = () => { + let type + + switch (this.type) { + case 'raw': type = unixfsData.DataType.Raw; break + case 'directory': type = unixfsData.DataType.Directory; break + case 'file': type = unixfsData.DataType.File; break + case 'metadata': type = unixfsData.DataType.Metadata; break + case 'symlink': type = unixfsData.DataType.Symlink; break + case 'hamt-sharded-directory': type = unixfsData.DataType.HAMTShard; break + default: + throw new Error(`Unkown type: "${this.type}"`) + } + let fileSize = this.fileSize() + + let data = this.data + + if (!this.data || !this.data.length) { + data = undefined + } + + let blockSizes = this.blockSizes + + if (!this.blockSizes || !this.blockSizes.length) { + blockSizes = undefined + } + + return unixfsData.encode({ + Type: type, + Data: data, + filesize: fileSize, + blocksizes: blockSizes, + hashType: this.hashType, + fanout: this.fanout + }) + } +} + +// decode from protobuf https://github.com/ipfs/go-ipfs/blob/master/unixfs/format.go#L24 +Data.unmarshal = (marsheled) => { + const decoded = unixfsData.decode(marsheled) + if (!decoded.Data) { + decoded.Data = undefined + } + const obj = new Data(types[decoded.Type], decoded.Data) + obj.blockSizes = decoded.blocksizes + return obj +} + +exports = module.exports = Data + +},{"./unixfs.proto":436,"protons":1274}],436:[function(require,module,exports){ +'use strict' + +module.exports = `message Data { + enum DataType { + Raw = 0; + Directory = 1; + File = 2; + Metadata = 3; + Symlink = 4; + HAMTShard = 5; + } + + required DataType Type = 1; + optional bytes Data = 2; + optional uint64 filesize = 3; + repeated uint64 blocksizes = 4; + + optional uint64 hashType = 5; + optional uint64 fanout = 6; +} + +message Metadata { + optional string MimeType = 1; +}` + +},{}],437:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],438:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],439:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":441,"./_stream_writable":443,"_process":1258,"dup":38,"inherits":317}],440:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":442,"dup":39,"inherits":317}],441:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":437,"../experimentalWarning":438,"./_stream_duplex":439,"./internal/streams/async_iterator":444,"./internal/streams/buffer_list":445,"./internal/streams/destroy":446,"./internal/streams/state":449,"./internal/streams/stream":450,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":453,"util":146}],442:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":437,"./_stream_duplex":439,"dup":41,"inherits":317}],443:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":437,"./_stream_duplex":439,"./internal/streams/destroy":446,"./internal/streams/state":449,"./internal/streams/stream":450,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],444:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":447,"_process":1258,"dup":43}],445:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],446:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],447:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":437,"dup":46}],448:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":437,"./end-of-stream":447,"dup":47}],449:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":437,"dup":48}],450:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],451:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":439,"./lib/_stream_passthrough.js":440,"./lib/_stream_readable.js":441,"./lib/_stream_transform.js":442,"./lib/_stream_writable.js":443,"./lib/internal/streams/end-of-stream.js":447,"./lib/internal/streams/pipeline.js":448,"dup":50}],452:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],453:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":452}],454:[function(require,module,exports){ +'use strict' + +const errCode = require('err-code') +const { Buffer } = require('buffer') +const pullStreamToIterable = require('pull-stream-to-async-iterator') +const { isSource } = require('is-pull-stream') +const globalThis = require('../globalthis') +const { Readable } = require('stream') +const Readable3 = require('readable-stream') + +/* + * Transform one of: + * + * ``` + * Bytes (Buffer|ArrayBuffer|TypedArray) [single file] + * Bloby (Blob|File) [single file] + * String [single file] + * { path, content: Bytes } [single file] + * { path, content: Bloby } [single file] + * { path, content: String } [single file] + * { path, content: Iterable } [single file] + * { path, content: Iterable } [single file] + * { path, content: AsyncIterable } [single file] + * { path, content: PullStream } [single file] + * { path, content: Readable } [single file] + * Iterable [single file] + * Iterable [single file] + * Iterable [multiple files] + * Iterable [multiple files] + * Iterable<{ path, content: Bytes }> [multiple files] + * Iterable<{ path, content: Bloby }> [multiple files] + * Iterable<{ path, content: String }> [multiple files] + * Iterable<{ path, content: Iterable }> [multiple files] + * Iterable<{ path, content: Iterable }> [multiple files] + * Iterable<{ path, content: AsyncIterable }> [multiple files] + * Iterable<{ path, content: PullStream }> [multiple files] + * Iterable<{ path, content: Readable }> [multiple files] + * AsyncIterable [single file] + * AsyncIterable [multiple files] + * AsyncIterable [multiple files] + * AsyncIterable<{ path, content: Bytes }> [multiple files] + * AsyncIterable<{ path, content: Bloby }> [multiple files] + * AsyncIterable<{ path, content: String }> [multiple files] + * AsyncIterable<{ path, content: Iterable }> [multiple files] + * AsyncIterable<{ path, content: Iterable }> [multiple files] + * AsyncIterable<{ path, content: AsyncIterable }> [multiple files] + * AsyncIterable<{ path, content: PullStream }> [multiple files] + * AsyncIterable<{ path, content: Readable }> [multiple files] + * PullStream [single file] + * PullStream [multiple files] + * PullStream [multiple files] + * PullStream<{ path, content: Bytes }> [multiple files] + * PullStream<{ path, content: Bloby }> [multiple files] + * PullStream<{ path, content: String }> [multiple files] + * PullStream<{ path, content: Iterable }> [multiple files] + * PullStream<{ path, content: Iterable }> [multiple files] + * PullStream<{ path, content: AsyncIterable }> [multiple files] + * PullStream<{ path, content: PullStream }> [multiple files] + * PullStream<{ path, content: Readable }> [multiple files] + * Readable [single file] + * Readable [multiple files] + * Readable [multiple files] + * Readable<{ path, content: Bytes }> [multiple files] + * Readable<{ path, content: Bloby }> [multiple files] + * Readable<{ path, content: String }> [multiple files] + * Readable<{ path, content: Iterable }> [multiple files] + * Readable<{ path, content: Iterable }> [multiple files] + * Readable<{ path, content: AsyncIterable }> [multiple files] + * Readable<{ path, content: PullStream }> [multiple files] + * Readable<{ path, content: Readable }> [multiple files] + * ``` + * Into: + * + * ``` + * AsyncIterable<{ path, content: AsyncIterable }> + * ``` + * + * @param input Object + * @return AsyncInterable<{ path, content: AsyncIterable }> + */ +module.exports = function normaliseInput (input) { + // must give us something + if (input === null || input === undefined) { + throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT')) + } + + // String + if (typeof input === 'string' || input instanceof String) { + return (async function * () { // eslint-disable-line require-await + yield toFileObject(input) + })() + } + + // Buffer|ArrayBuffer|TypedArray + // Blob|File + if (isBytes(input) || isBloby(input)) { + return (async function * () { // eslint-disable-line require-await + yield toFileObject(input) + })() + } + + // Readable + if (isOldReadable(input)) { + input = upgradeOldStream(input) + } + + // Iterable + if (input[Symbol.iterator]) { + return (async function * () { // eslint-disable-line require-await + const iterator = input[Symbol.iterator]() + const first = iterator.next() + if (first.done) return iterator + + // Iterable + // Iterable + if (Number.isInteger(first.value) || isBytes(first.value)) { + yield toFileObject((function * () { + yield first.value + yield * iterator + })()) + return + } + + // Iterable + // Iterable + // Iterable<{ path, content }> + if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { + yield toFileObject(first.value) + for (const obj of iterator) { + yield toFileObject(obj) + } + return + } + + throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') + })() + } + + // AsyncIterable + if (input[Symbol.asyncIterator]) { + return (async function * () { + const iterator = input[Symbol.asyncIterator]() + const first = await iterator.next() + if (first.done) return iterator + + // AsyncIterable + if (isBytes(first.value)) { + yield toFileObject((async function * () { // eslint-disable-line require-await + yield first.value + yield * iterator + })()) + return + } + + // AsyncIterable + // AsyncIterable + // AsyncIterable<{ path, content }> + if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { + yield toFileObject(first.value) + for await (const obj of iterator) { + yield toFileObject(obj) + } + return + } + + throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') + })() + } + + // { path, content: ? } + // Note: Detected _after_ AsyncIterable because Node.js streams have a + // `path` property that passes this check. + if (isFileObject(input)) { + return (async function * () { // eslint-disable-line require-await + yield toFileObject(input) + })() + } + + // PullStream + if (isSource(input)) { + return (async function * () { + const iterator = pullStreamToIterable(input)[Symbol.asyncIterator]() + const first = await iterator.next() + if (first.done) return iterator + + // PullStream + if (isBytes(first.value)) { + yield toFileObject((async function * () { // eslint-disable-line require-await + yield first.value + yield * iterator + })()) + return + } + + // PullStream + // PullStream + // PullStream<{ path, content }> + if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { + yield toFileObject(first.value) + for await (const obj of iterator) { + yield toFileObject(obj) + } + return + } + + throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') + })() + } + + throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') +} + +function toFileObject (input) { + const obj = { path: input.path || '' } + + if (input.content) { + obj.content = toAsyncIterable(input.content) + } else if (!input.path) { // Not already a file object with path or content prop + obj.content = toAsyncIterable(input) + } + + return obj +} + +function toAsyncIterable (input) { + // Bytes | String + if (isBytes(input) || typeof input === 'string') { + return (async function * () { // eslint-disable-line require-await + yield toBuffer(input) + })() + } + + // Bloby + if (isBloby(input)) { + return blobToAsyncGenerator(input) + } + + // Readable + if (isOldReadable(input)) { + input = upgradeOldStream(input) + } + + // Iterator + if (input[Symbol.iterator]) { + return (async function * () { // eslint-disable-line require-await + const iterator = input[Symbol.iterator]() + const first = iterator.next() + if (first.done) return iterator + + // Iterable + if (Number.isInteger(first.value)) { + yield toBuffer(Array.from((function * () { + yield first.value + yield * iterator + })())) + return + } + + // Iterable + if (isBytes(first.value)) { + yield toBuffer(first.value) + for (const chunk of iterator) { + yield toBuffer(chunk) + } + return + } + + throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') + })() + } + + // AsyncIterable + if (input[Symbol.asyncIterator]) { + return (async function * () { + for await (const chunk of input) { + yield toBuffer(chunk) + } + })() + } + + // PullStream + if (isSource(input)) { + return pullStreamToIterable(input) + } + + throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT')) +} + +function isOldReadable (obj) { + if (obj[Symbol.iterator] || obj[Symbol.asyncIterator]) { + return false + } + + return Boolean(obj.readable) +} + +function toBuffer (chunk) { + return isBytes(chunk) ? chunk : Buffer.from(chunk) +} + +function isBytes (obj) { + return Buffer.isBuffer(obj) || ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer +} + +function isBloby (obj) { + return typeof globalThis.Blob !== 'undefined' && obj instanceof globalThis.Blob +} + +// An object with a path or content property +function isFileObject (obj) { + return typeof obj === 'object' && (obj.path || obj.content) +} + +function upgradeOldStream (stream) { + if (stream[Symbol.asyncIterator] || stream[Symbol.iterator]) { + return stream + } + + // in the browser the stream.Readable is not an async iterator but readble-stream@3 is... + stream[Symbol.asyncIterator] = Readable.prototype[Symbol.asyncIterator] || Readable3.prototype[Symbol.asyncIterator] + + return stream +} + +function blobToAsyncGenerator (blob) { + if (typeof blob.stream === 'function') { + // firefox < 69 does not support blob.stream() + return streamBlob(blob) + } + + return readBlob(blob) +} + +async function * streamBlob (blob) { + const reader = blob.stream().getReader() + + while (true) { + const result = await reader.read() + + if (result.done) { + return + } + + yield result.value + } +} + +async function * readBlob (blob, options) { + options = options || {} + + const reader = new globalThis.FileReader() + const chunkSize = options.chunkSize || 1024 * 1024 + let offset = options.offset || 0 + + const getNextChunk = () => new Promise((resolve, reject) => { + reader.onloadend = e => { + const data = e.target.result + resolve(data.byteLength === 0 ? null : data) + } + reader.onerror = reject + + const end = offset + chunkSize + const slice = blob.slice(offset, end) + reader.readAsArrayBuffer(slice) + offset = end + }) + + while (true) { + const data = await getNextChunk() + + if (data == null) { + return + } + + yield Buffer.from(data) + } +} + +},{"../globalthis":455,"buffer":181,"err-code":268,"is-pull-stream":617,"pull-stream-to-async-iterator":1309,"readable-stream":451,"stream":1459}],455:[function(require,module,exports){ +/* eslint-disable no-undef */ +/* eslint-disable no-extend-native */ +/* eslint-disable strict */ + +// polyfill for globalThis +// https://v8.dev/features/globalthis +// https://mathiasbynens.be/notes/globalthis +(function () { + if (typeof globalThis === 'object') return + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this + }, + configurable: true + }) + __magic__.globalThis = __magic__ + delete Object.prototype.__magic__ +}()) + +module.exports = globalThis + +},{}],456:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":457,"_process":1258,"dup":208}],457:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],458:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],459:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],460:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":462,"./_stream_writable":464,"_process":1258,"dup":38,"inherits":317}],461:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":463,"dup":39,"inherits":317}],462:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":458,"../experimentalWarning":459,"./_stream_duplex":460,"./internal/streams/async_iterator":465,"./internal/streams/buffer_list":466,"./internal/streams/destroy":467,"./internal/streams/state":470,"./internal/streams/stream":471,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":474,"util":146}],463:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":458,"./_stream_duplex":460,"dup":41,"inherits":317}],464:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":458,"./_stream_duplex":460,"./internal/streams/destroy":467,"./internal/streams/state":470,"./internal/streams/stream":471,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],465:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":468,"_process":1258,"dup":43}],466:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],467:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],468:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":458,"dup":46}],469:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":458,"./end-of-stream":468,"dup":47}],470:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":458,"dup":48}],471:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],472:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":460,"./lib/_stream_passthrough.js":461,"./lib/_stream_readable.js":462,"./lib/_stream_transform.js":463,"./lib/_stream_writable.js":464,"./lib/internal/streams/end-of-stream.js":468,"./lib/internal/streams/pipeline.js":469,"dup":50}],473:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],474:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":473}],475:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + "ipfs@0.38.0", + "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet" + ] + ], + "_from": "ipfs@0.38.0", + "_id": "ipfs@0.38.0", + "_inBundle": false, + "_integrity": "sha512-Yt4bTEqJ32zml6FbTIaEUZS4Wo8MI97Q/fqU3TgbflKln5YEY7nXcr4Y/fzC/2n6jZG7j7XZsP0LFM557WJ+Fw==", + "_location": "/ipfs", + "_phantomChildren": { + "@sindresorhus/is": "0.14.0", + "@szmarczak/http-timer": "1.1.2", + "ansi-styles": "3.2.1", + "cacheable-request": "6.1.0", + "chalk": "2.4.2", + "decamelize": "1.2.0", + "decompress-response": "3.3.0", + "dot-prop": "4.2.0", + "duplexer3": "0.1.4", + "emoji-regex": "7.0.3", + "find-up": "3.0.0", + "graceful-fs": "4.1.15", + "has-yarn": "2.1.0", + "import-lazy": "2.1.0", + "inherits": "2.0.3", + "is-ci": "2.0.0", + "is-installed-globally": "0.1.0", + "is-yarn-global": "0.3.0", + "lowercase-keys": "1.0.1", + "make-dir": "1.3.0", + "mimic-response": "1.0.1", + "ms": "2.1.1", + "p-cancelable": "1.1.0", + "pump": "3.0.0", + "rc": "1.2.8", + "require-directory": "2.1.1", + "semver-diff": "2.1.0", + "set-blocking": "2.0.0", + "term-size": "1.2.0", + "to-readable-stream": "1.0.0", + "type-fest": "0.3.1", + "unique-string": "1.0.0", + "util-deprecate": "1.0.2", + "which-module": "2.0.0", + "widest-line": "2.0.1", + "write-file-atomic": "2.4.2", + "xdg-basedir": "3.0.0", + "y18n": "4.0.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "ipfs@0.38.0", + "name": "ipfs", + "escapedName": "ipfs", + "rawSpec": "0.38.0", + "saveSpec": null, + "fetchSpec": "0.38.0" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/ipfs/-/ipfs-0.38.0.tgz", + "_spec": "0.38.0", + "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet", + "bin": { + "jsipfs": "src/cli/bin.js" + }, + "browser": { + "./src/core/components/init-assets.js": false, + "./src/core/runtime/add-from-fs-nodejs.js": "./src/core/runtime/add-from-fs-browser.js", + "./src/core/runtime/config-nodejs.js": "./src/core/runtime/config-browser.js", + "./src/core/runtime/dns-nodejs.js": "./src/core/runtime/dns-browser.js", + "./src/core/runtime/fetch-nodejs.js": "./src/core/runtime/fetch-browser.js", + "./src/core/runtime/libp2p-nodejs.js": "./src/core/runtime/libp2p-browser.js", + "./src/core/runtime/libp2p-pubsub-routers-nodejs.js": "./src/core/runtime/libp2p-pubsub-routers-browser.js", + "./src/core/runtime/preload-nodejs.js": "./src/core/runtime/preload-browser.js", + "./src/core/runtime/repo-nodejs.js": "./src/core/runtime/repo-browser.js", + "./src/core/runtime/ipld-nodejs.js": "./src/core/runtime/ipld-browser.js", + "./test/utils/create-repo-nodejs.js": "./test/utils/create-repo-browser.js", + "stream": "readable-stream" + }, + "browser-all-ipld-formats": { + "./src/core/runtime/ipld-browser.js": "./src/core/runtime/ipld-browser-all.js" + }, + "bugs": { + "url": "https://github.com/ipfs/js-ipfs/issues" + }, + "contributors": [ + { + "name": "0xflotus", + "email": "0xflotus@gmail.com" + }, + { + "name": "A_A", + "email": "21040751+Otto-AA@users.noreply.github.com" + }, + { + "name": "Alan Shaw", + "email": "alan.shaw@protocol.ai" + }, + { + "name": "Alan Shaw", + "email": "alan@tableflip.io" + }, + { + "name": "Alex North", + "email": "alex@alexnorth.me" + }, + { + "name": "Andrew Nesbitt", + "email": "andrewnez@gmail.com" + }, + { + "name": "Andrew de Andrade", + "email": "andrew@deandrade.com.br" + }, + { + "name": "André Cruz", + "email": "andremiguelcruz@msn.com" + }, + { + "name": "Arkadiy Kukarkin", + "email": "parkan@users.noreply.github.com" + }, + { + "name": "Arpit Agarwal", + "email": "93arpit@gmail.com" + }, + { + "name": "Arpit Agarwal", + "email": "atvanguard@users.noreply.github.com" + }, + { + "name": "Bernard Mordan", + "email": "bernard@tableflip.io" + }, + { + "name": "Brian Vander Schaaf", + "email": "bvs330@gmail.com" + }, + { + "name": "Bruno Zell", + "email": "bruno.zzell@gmail.com" + }, + { + "name": "CHEVALAY JOSSELIN", + "email": "josselin54.chevalay@gmail.com" + }, + { + "name": "Caio Gondim", + "email": "me@caiogondim.com" + }, + { + "name": "Chance Hudson", + "email": "jchancehud@gmail.com" + }, + { + "name": "Chirag Shinde", + "email": "chirag-shinde@users.noreply.github.com" + }, + { + "name": "Christian Couder", + "email": "chriscool@tuxfamily.org" + }, + { + "name": "Dafeng", + "email": "dfguo.joe@gmail.com" + }, + { + "name": "Dan Ordille", + "email": "dordille@gmail.com" + }, + { + "name": "Dan Shields", + "email": "35669742+NukeManDan@users.noreply.github.com" + }, + { + "name": "Daniel J. O'Quinn", + "email": "danieljoquinn@gmail.com" + }, + { + "name": "Daniela Borges Matos de Carvalho", + "email": "alunassertiva@gmail.com" + }, + { + "name": "David Dias", + "email": "daviddias.p@gmail.com" + }, + { + "name": "David Gilbertson", + "email": "gilbertson.david@gmail.com" + }, + { + "name": "David da Silva", + "email": "dasilvacontin@gmail.com" + }, + { + "name": "Diogo Silva", + "email": "fsdiogo@gmail.com" + }, + { + "name": "Dmitriy Ryajov", + "email": "dryajov@gmail.com" + }, + { + "name": "Dominic Della Valle", + "email": "ddvpublic@Gmail.com" + }, + { + "name": "Dzmitry Bachko", + "email": "dbachko@gmail.com" + }, + { + "name": "Enrico Marino", + "email": "enrico.marino@email.com" + }, + { + "name": "Faheel Ahmad", + "email": "faheel@live.in" + }, + { + "name": "Felix Yan", + "email": "felixonmars@archlinux.org" + }, + { + "name": "Francisco Baio Dias", + "email": "xicombd@gmail.com" + }, + { + "name": "Francisco Baio Dias", + "email": "francisco@typeform.com" + }, + { + "name": "Friedel Ziegelmayer", + "email": "dignifiedquire@gmail.com" + }, + { + "name": "Gar", + "email": "gar+gh@danger.computer" + }, + { + "name": "Georgios Rassias", + "email": "georassias@gmail.com" + }, + { + "name": "Gorka Ludlow", + "email": "gorka@aquigorka.com" + }, + { + "name": "Grant Herman", + "email": "grantlouisherman041@gmail.com" + }, + { + "name": "Greenkeeper", + "email": "support@greenkeeper.io" + }, + { + "name": "Haad", + "email": "haadcode@users.noreply.github.com" + }, + { + "name": "Haoliang Yu", + "email": "haoliangyu@users.noreply.github.com" + }, + { + "name": "Harsh Vakharia", + "email": "harshjv@users.noreply.github.com" + }, + { + "name": "Henrique Dias", + "email": "hacdias@gmail.com" + }, + { + "name": "Henry Rodrick", + "email": "moshisushi@gmail.com" + }, + { + "name": "Heo Sangmin", + "email": "heo@mapiacompany.com" + }, + { + "name": "Hugo Dias", + "email": "hugomrdias@gmail.com" + }, + { + "name": "Hugo Dias", + "email": "mail@hugodias.me" + }, + { + "name": "Irakli Gozalishvili", + "email": "contact@gozala.io" + }, + { + "name": "Jacob Heun", + "email": "jacobheun@gmail.com" + }, + { + "name": "Jacob Heun", + "email": "jake@andyet.net" + }, + { + "name": "Jade Meskill", + "email": "jade.meskill@gmail.com" + }, + { + "name": "Johannes Wikner", + "email": "johannes.wikner@gmail.com" + }, + { + "name": "Jon Schlinkert", + "email": "dev@sellside.com" + }, + { + "name": "Jonathan", + "email": "jkrone@vt.edu" + }, + { + "name": "Jonybang", + "email": "Jonybange@gmail.com" + }, + { + "name": "João Antunes", + "email": "j.goncalo.antunes@gmail.com" + }, + { + "name": "João Santos", + "email": "joaosantos15@users.noreply.github.com" + }, + { + "name": "Kevin Wang", + "email": "kevin@fossa.io" + }, + { + "name": "Lars Gierth", + "email": "larsg@systemli.org" + }, + { + "name": "Lukas Drgon", + "email": "lukas.drgon@gmail.com" + }, + { + "name": "Maciej Krüger", + "email": "mkg20001@gmail.com" + }, + { + "name": "Marcin Rataj", + "email": "lidel@lidel.org" + }, + { + "name": "Marius Darila", + "email": "marius.darila@gmail.com" + }, + { + "name": "Mat Kelly", + "email": "machawk1@gmail.com" + }, + { + "name": "Michelle Lee", + "email": "michelle@protocol.ai" + }, + { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "Mithgol", + "email": "getgit@mithgol.ru" + }, + { + "name": "Molly", + "email": "momack2@users.noreply.github.com" + }, + { + "name": "Mounish Sai", + "email": "pvsmounish@gmail.com" + }, + { + "name": "My9Bot", + "email": "34904312+My9Bot@users.noreply.github.com" + }, + { + "name": "Nick Poulden", + "email": "nick@poulden.com" + }, + { + "name": "Nitin Patel", + "email": "31539366+niinpatel@users.noreply.github.com" + }, + { + "name": "Nuno Nogueira", + "email": "nunofmn@gmail.com" + }, + { + "name": "Oli Evans", + "email": "oli@tableflip.io" + }, + { + "name": "Oskar Nyberg", + "email": "oskar@oskarnyberg.com" + }, + { + "name": "Pascal Precht", + "email": "pascal.precht@googlemail.com" + }, + { + "name": "Pau Ramon Revilla", + "email": "masylum@gmail.com" + }, + { + "name": "Paulo Rodrigues", + "email": "me@paulogr.com" + }, + { + "name": "Pedro Teixeira", + "email": "i@pgte.me" + }, + { + "name": "Portia Burton", + "email": "plburton@gmail.com" + }, + { + "name": "Prabhakar Poudel", + "email": "yuvrajzohan@gmail.com" + }, + { + "name": "Qmstream", + "email": "51881352+Qmstream@users.noreply.github.com" + }, + { + "name": "Raoul Millais", + "email": "raoul@raoulmillais.com" + }, + { + "name": "RasmusErik Voel Jensen", + "email": "github@solsort.com" + }, + { + "name": "Richard Littauer", + "email": "richard.littauer@gmail.com" + }, + { + "name": "Richard Schneider", + "email": "makaretu@gmail.com" + }, + { + "name": "Rob Brackett", + "email": "rob@robbrackett.com" + }, + { + "name": "Rod Keys", + "email": "rod@zokos.com" + }, + { + "name": "Sangwon Hong", + "email": "qpakzk@gmail.com" + }, + { + "name": "Sid Harder", + "email": "sideharder@gmail.com" + }, + { + "name": "SidHarder", + "email": "softwarenavigator@gmail.com" + }, + { + "name": "Stephen Whitmore", + "email": "stephen.whitmore@gmail.com" + }, + { + "name": "Stephen Whitmore", + "email": "noffle@users.noreply.github.com" + }, + { + "name": "Steven Allen", + "email": "steven@stebalien.com" + }, + { + "name": "Terence Pae", + "email": "terencepae@gmail.com" + }, + { + "name": "Teri Chadbourne", + "email": "terichadbourne@users.noreply.github.com" + }, + { + "name": "Uroš Jurglič", + "email": "jurglic@gmail.com" + }, + { + "name": "Vasco Santos", + "email": "vasco.santos@moxy.studio" + }, + { + "name": "Vasco Santos", + "email": "vasco.santos@ua.pt" + }, + { + "name": "Volker Mische", + "email": "volker.mische@gmail.com" + }, + { + "name": "Xiao Liang", + "email": "yxliang01@users.noreply.github.com" + }, + { + "name": "Yahya", + "email": "ya7yaz@gmail.com" + }, + { + "name": "Yole", + "email": "yole@ultiledger.io" + }, + { + "name": "achingbrain", + "email": "alex@achingbrain.net" + }, + { + "name": "bitspill", + "email": "bitspill+github@bitspill.net" + }, + { + "name": "datafatmunger", + "email": "jbg@peerparty.org" + }, + { + "name": "dirkmc", + "email": "dirkmdev@gmail.com" + }, + { + "name": "dirkmc", + "email": "dirk@mccormick.cx" + }, + { + "name": "greenkeeper[bot]", + "email": "23040076+greenkeeper[bot]@users.noreply.github.com" + }, + { + "name": "greenkeeper[bot]", + "email": "greenkeeper[bot]@users.noreply.github.com" + }, + { + "name": "haad", + "email": "haad@headbanggames.com" + }, + { + "name": "hapsody", + "email": "hapsody@gmail.com" + }, + { + "name": "jbenet", + "email": "juan@benet.ai" + }, + { + "name": "jonahweissman", + "email": "19804455+jonahweissman@users.noreply.github.com" + }, + { + "name": "kevingzhang", + "email": "kevin.zhang.canada@gmail.com" + }, + { + "name": "kumavis", + "email": "kumavis@users.noreply.github.com" + }, + { + "name": "nginnever", + "email": "ginneversource@gmail.com" + }, + { + "name": "npmcdn-to-unpkg-bot", + "email": "npmcdn-to-unpkg-bot@users.noreply.github.com" + }, + { + "name": "robbsolter", + "email": "35879806+robbsolter@users.noreply.github.com" + }, + { + "name": "seungwon-kang", + "email": "ksw3894@gmail.com" + }, + { + "name": "tcme", + "email": "hi@this-connect.me" + }, + { + "name": "victorbjelkholm", + "email": "victorbjelkholm@gmail.com" + }, + { + "name": "Łukasz Magiera", + "email": "magik6k@users.noreply.github.com" + }, + { + "name": "Максим Ильин", + "email": "negamaxi@gmail.com" + } + ], + "dependencies": { + "@hapi/ammo": "^3.1.1", + "@hapi/boom": "^7.4.3", + "@hapi/hapi": "^18.3.2", + "@hapi/joi": "^15.0.1", + "array-shuffle": "^1.0.1", + "async": "^2.6.1", + "async-iterator-all": "^1.0.0", + "async-iterator-to-pull-stream": "^1.3.0", + "async-iterator-to-stream": "^1.1.0", + "base32.js": "~0.1.0", + "bignumber.js": "^9.0.0", + "binary-querystring": "~0.1.2", + "bl": "^3.0.0", + "bs58": "^4.0.1", + "buffer-peek-stream": "^1.0.1", + "byteman": "^1.3.5", + "cid-tool": "~0.3.0", + "cids": "~0.7.1", + "class-is": "^1.1.0", + "datastore-core": "~0.6.0", + "datastore-pubsub": "~0.1.1", + "debug": "^4.1.0", + "dlv": "^1.1.3", + "err-code": "^2.0.0", + "explain-error": "^1.0.4", + "file-type": "^12.0.1", + "fnv1a": "^1.0.1", + "fsm-event": "^2.1.0", + "get-folder-size": "^2.0.0", + "glob": "^7.1.3", + "hapi-pino": "^6.1.0", + "hashlru": "^2.3.0", + "human-to-milliseconds": "^2.0.0", + "interface-datastore": "~0.6.0", + "ipfs-bitswap": "~0.25.1", + "ipfs-block": "~0.8.1", + "ipfs-block-service": "~0.15.2", + "ipfs-http-client": "^37.0.1", + "ipfs-http-response": "~0.3.1", + "ipfs-mfs": "^0.12.2", + "ipfs-multipart": "^0.2.0", + "ipfs-repo": "~0.26.6", + "ipfs-unixfs": "~0.1.16", + "ipfs-unixfs-exporter": "~0.37.7", + "ipfs-unixfs-importer": "~0.39.11", + "ipfs-utils": "^0.3.0", + "ipld": "~0.24.1", + "ipld-bitcoin": "~0.3.0", + "ipld-dag-cbor": "~0.15.0", + "ipld-dag-pb": "~0.17.4", + "ipld-ethereum": "^4.0.0", + "ipld-git": "~0.5.0", + "ipld-raw": "^4.0.0", + "ipld-zcash": "~0.3.0", + "ipns": "~0.5.2", + "is-domain-name": "^1.0.1", + "is-ipfs": "~0.6.1", + "is-pull-stream": "~0.0.0", + "is-stream": "^2.0.0", + "iso-url": "~0.4.6", + "it-pipe": "^1.0.1", + "it-to-stream": "^0.1.1", + "just-safe-set": "^2.1.0", + "kind-of": "^6.0.2", + "libp2p": "~0.26.1", + "libp2p-bootstrap": "~0.9.3", + "libp2p-crypto": "~0.16.0", + "libp2p-delegated-content-routing": "^0.2.4", + "libp2p-delegated-peer-routing": "^0.2.4", + "libp2p-floodsub": "^0.18.0", + "libp2p-gossipsub": "~0.0.5", + "libp2p-kad-dht": "~0.15.3", + "libp2p-keychain": "~0.4.2", + "libp2p-mdns": "~0.12.0", + "libp2p-record": "~0.6.3", + "libp2p-secio": "~0.11.0", + "libp2p-tcp": "~0.13.1", + "libp2p-webrtc-star": "~0.16.0", + "libp2p-websocket-star-multi": "~0.4.3", + "libp2p-websockets": "~0.12.3", + "lodash": "^4.17.15", + "mafmt": "^6.0.10", + "merge-options": "^1.0.1", + "mime-types": "^2.1.21", + "mkdirp": "~0.5.1", + "mortice": "^2.0.0", + "multiaddr": "^6.1.0", + "multiaddr-to-uri": "^5.0.0", + "multibase": "~0.6.0", + "multicodec": "~0.5.5", + "multihashes": "~0.4.14", + "multihashing-async": "~0.6.0", + "node-fetch": "^2.3.0", + "peer-book": "~0.9.0", + "peer-id": "~0.12.3", + "peer-info": "~0.15.0", + "progress": "^2.0.1", + "prom-client": "^11.5.3", + "prometheus-gc-stats": "~0.6.0", + "promise-nodeify": "^3.0.1", + "promisify-es6": "^1.0.3", + "protons": "^1.0.1", + "pull-abortable": "^4.1.1", + "pull-cat": "^1.1.11", + "pull-defer": "~0.2.3", + "pull-file": "^1.1.0", + "pull-mplex": "~0.1.1", + "pull-ndjson": "~0.1.1", + "pull-pushable": "^2.2.0", + "pull-sort": "^1.0.1", + "pull-stream": "^3.6.14", + "pull-stream-to-async-iterator": "^1.0.2", + "pull-stream-to-stream": "^1.3.4", + "pull-traverse": "^1.0.3", + "readable-stream": "^3.4.0", + "receptacle": "^1.3.2", + "semver": "^6.3.0", + "stream-to-pull-stream": "^1.7.3", + "superstruct": "~0.6.2", + "tar-stream": "^2.0.0", + "temp": "~0.9.0", + "update-notifier": "^3.0.1", + "uri-to-multiaddr": "^3.0.1", + "varint": "^5.0.0", + "yargs": "^14.0.0", + "yargs-promise": "^1.1.0" + }, + "description": "JavaScript implementation of the IPFS specification", + "devDependencies": { + "aegir": "^20.1.0", + "base64url": "^3.0.1", + "chai": "^4.2.0", + "clear-module": "^4.0.0", + "delay": "^4.1.0", + "detect-node": "^2.0.4", + "dir-compare": "^1.7.3", + "dirty-chai": "^2.0.1", + "execa": "^2.0.4", + "form-data": "^2.5.1", + "hat": "0.0.3", + "interface-ipfs-core": "^0.113.0", + "ipfs-interop": "~0.1.0", + "ipfsd-ctl": "0.46.0", + "libp2p-websocket-star": "~0.10.2", + "ncp": "^2.0.0", + "p-event": "^4.1.0", + "qs": "^6.5.2", + "rimraf": "^3.0.0", + "sinon": "^7.4.2", + "stream-to-promise": "^2.2.0" + }, + "engines": { + "node": ">=10.0.0", + "npm": ">=6.0.0" + }, + "files": [ + "src", + "dist" + ], + "homepage": "https://js.ipfs.io", + "keywords": [ + "IPFS" + ], + "leadMaintainer": "Alan Shaw ", + "license": "MIT", + "main": "src/core/index.js", + "name": "ipfs", + "optionalDependencies": { + "prom-client": "^11.5.3", + "prometheus-gc-stats": "~0.6.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ipfs/js-ipfs.git" + }, + "scripts": { + "benchmark": "echo \"Error: no benchmarks yet\" && exit 1", + "benchmark:browser": "echo \"Error: no benchmarks yet\" && exit 1", + "benchmark:node": "echo \"Error: no benchmarks yet\" && exit 1", + "benchmark:node:core": "echo \"Error: no benchmarks yet\" && exit 1", + "benchmark:node:http": "echo \"Error: no benchmarks yet\" && exit 1", + "build": "aegir build", + "coverage": "nyc --reporter=text --reporter=lcov npm run test:node", + "lint": "aegir lint", + "release": "aegir release -t node -t browser", + "release-major": "aegir release --type major -t node -t browser", + "release-minor": "aegir release --type minor -t node -t browser", + "test": "aegir test", + "test:bootstrapers": "IPFS_TEST=bootstrapers aegir test -t browser -f test/bootstrapers.js", + "test:browser": "aegir test -t browser", + "test:external": "aegir test-external", + "test:interop": "IPFS_JS_EXEC=$PWD/src/cli/bin.js ipfs-interop", + "test:node": "aegir test -t node", + "test:node:cli": "aegir test -t node -f test/cli/index.js", + "test:node:core": "aegir test -t node -f test/core/**/*.js", + "test:node:gateway": "aegir test -t node -f test/gateway/index.js", + "test:node:http": "aegir test -t node -f test/http-api/index.js", + "test:node:interface": "aegir test -t node -f test/core/interface.spec.js", + "test:webworker": "aegir test -t webworker" + }, + "version": "0.38.0" +} + +},{}],476:[function(require,module,exports){ +'use strict' + +const waterfall = require('async/waterfall') +const RepoErrors = require('ipfs-repo').errors + +// Boot an IPFS node depending on the options set +module.exports = (self) => { + self.log('booting') + const options = self._options + const doInit = options.init + const doStart = options.start + + // Do the actual boot sequence + waterfall([ + // Checks if a repo exists, and if so opens it + // Will return callback with a bool indicating the existence + // of the repo + (cb) => { + // nothing to do + if (!self._repo.closed) { + return cb(null, true) + } + + self._repo.open((err, res) => { + if (isRepoUninitializedError(err)) return cb(null, false) + if (err) return cb(err) + cb(null, true) + }) + }, + (repoOpened, cb) => { + // Init with existing initialized, opened, repo + if (repoOpened) { + return self.init({ repo: self._repo }, (err) => { + if (err) return cb(Object.assign(err, { emitted: true })) + cb() + }) + } + + if (doInit) { + const initOptions = Object.assign( + { bits: 2048, pass: self._options.pass }, + typeof options.init === 'object' ? options.init : {} + ) + return self.init(initOptions, (err) => { + if (err) return cb(Object.assign(err, { emitted: true })) + cb() + }) + } + + cb() + }, + (cb) => { + // No problem, we don't have to start the node + if (!doStart) { + return cb() + } + + self.start((err) => { + if (err) return cb(Object.assign(err, { emitted: true })) + cb() + }) + } + ], (err) => { + if (err) { + if (!err.emitted) { + self.emit('error', err) + } + return + } + self.log('booted') + self.emit('ready') + }) +} + +function isRepoUninitializedError (err) { + if (!err) { + return false + } + + // If the error is that no repo exists, + // which happens when the version file is not found + // we just want to signal that no repo exist, not + // fail the whole process. + + // Use standardized errors as much as possible + if (err.code === RepoErrors.ERR_REPO_NOT_INITIALIZED) { + return true + } + + // TODO: As error codes continue to be standardized, this logic can be phase out; + // it is here to maintain compatibility + if (err.message.match(/not found/) || // indexeddb + err.message.match(/ENOENT/) || // fs + err.message.match(/No value/) // memory + ) { + return true + } + + return false +} + +},{"async/waterfall":102,"ipfs-repo":395}],477:[function(require,module,exports){ +'use strict' + +const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR +const promisify = require('promisify-es6') +const setImmediate = require('async/setImmediate') +const Big = require('bignumber.js') +const CID = require('cids') +const PeerId = require('peer-id') +const errCode = require('err-code') + +function formatWantlist (list, cidBase) { + return Array.from(list).map((e) => ({ '/': e[1].cid.toBaseEncodedString(cidBase) })) +} + +module.exports = function bitswap (self) { + return { + wantlist: promisify((peerId, callback) => { + if (typeof peerId === 'function') { + callback = peerId + peerId = null + } + + if (!self.isOnline()) { + return setImmediate(() => callback(new Error(OFFLINE_ERROR))) + } + + let list + if (peerId) { + try { + peerId = PeerId.createFromB58String(peerId) + } catch (e) { + peerId = null + } + if (!peerId) { + return setImmediate(() => callback(new Error('Invalid peerId'))) + } + list = self._bitswap.wantlistForPeer(peerId) + } else { + list = self._bitswap.getWantlist() + } + + setImmediate(() => callback(null, { Keys: formatWantlist(list) })) + }), + + stat: promisify((callback) => { + if (!self.isOnline()) { + return setImmediate(() => callback(new Error(OFFLINE_ERROR))) + } + + const snapshot = self._bitswap.stat().snapshot + + setImmediate(() => { + callback(null, { + provideBufLen: parseInt(snapshot.providesBufferLength.toString()), + blocksReceived: new Big(snapshot.blocksReceived), + wantlist: formatWantlist(self._bitswap.getWantlist()), + peers: self._bitswap.peers().map((id) => id.toB58String()), + dupBlksReceived: new Big(snapshot.dupBlksReceived), + dupDataReceived: new Big(snapshot.dupDataReceived), + dataReceived: new Big(snapshot.dataReceived), + blocksSent: new Big(snapshot.blocksSent), + dataSent: new Big(snapshot.dataSent) + }) + }) + }), + + unwant: promisify((keys, callback) => { + if (!self.isOnline()) { + return setImmediate(() => callback(new Error(OFFLINE_ERROR))) + } + + if (!Array.isArray(keys)) { + keys = [keys] + } + + try { + keys = keys.map((key) => { + if (CID.isCID(key)) { + return key + } + return new CID(key) + }) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + setImmediate(() => callback(null, self._bitswap.unwant(keys))) + }) + } +} + +},{"../utils":560,"async/setImmediate":96,"bignumber.js":110,"cids":185,"err-code":268,"peer-id":1253,"promisify-es6":1263}],478:[function(require,module,exports){ +'use strict' + +const Block = require('ipfs-block') +const multihashing = require('multihashing-async') +const CID = require('cids') +const waterfall = require('async/waterfall') +const setImmediate = require('async/setImmediate') +const promisify = require('promisify-es6') +const errCode = require('err-code') + +module.exports = function block (self) { + return { + get: promisify((cid, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + try { + cid = cleanCid(cid) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + if (options.preload !== false) { + self._preload(cid) + } + + self._blockService.get(cid, callback) + }), + put: promisify((block, options, callback) => { + callback = callback || function noop () {} + + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + if (Array.isArray(block)) { + return callback(new Error('Array is not supported')) + } + + waterfall([ + (cb) => { + if (Block.isBlock(block)) { + return cb(null, block) + } + + if (options.cid && CID.isCID(options.cid)) { + return cb(null, new Block(block, options.cid)) + } + + const mhtype = options.mhtype || 'sha2-256' + const format = options.format || 'dag-pb' + let cidVersion + // const mhlen = options.mhlen || 0 + + if (options.version == null) { + // Pick appropriate CID version + cidVersion = mhtype === 'sha2-256' && format === 'dag-pb' ? 0 : 1 + } else { + cidVersion = options.version + } + + multihashing(block, mhtype, (err, multihash) => { + if (err) { + return cb(err) + } + + let cid + try { + cid = new CID(cidVersion, format, multihash) + } catch (err) { + return cb(err) + } + + cb(null, new Block(block, cid)) + }) + }, + (block, cb) => self._gcLock.readLock((_cb) => { + self._blockService.put(block, (err) => { + if (err) { + return _cb(err) + } + + if (options.preload !== false) { + self._preload(block.cid) + } + + _cb(null, block) + }) + }, cb) + ], callback) + }), + rm: promisify((cid, callback) => { + try { + cid = cleanCid(cid) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + // We need to take a write lock here to ensure that adding and removing + // blocks are exclusive operations + self._gcLock.writeLock((cb) => self._blockService.delete(cid, cb), callback) + }), + stat: promisify((cid, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + try { + cid = cleanCid(cid) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + if (options.preload !== false) { + self._preload(cid) + } + + self._blockService.get(cid, (err, block) => { + if (err) { + return callback(err) + } + callback(null, { + key: cid.toString(), + size: block.data.length + }) + }) + }) + } +} + +function cleanCid (cid) { + if (CID.isCID(cid)) { + return cid + } + + // CID constructor knows how to do the cleaning :) + return new CID(cid) +} + +},{"async/setImmediate":96,"async/waterfall":102,"cids":185,"err-code":268,"ipfs-block":353,"multihashing-async":1161,"promisify-es6":1263}],479:[function(require,module,exports){ +(function (setImmediate){ +'use strict' + +const defaultConfig = require('../runtime/config-nodejs.js') +const isMultiaddr = require('mafmt').IPFS.matches +const promisify = require('promisify-es6') + +function isValidMultiaddr (ma) { + try { + return isMultiaddr(ma) + } catch (err) { + return false + } +} + +function invalidMultiaddrError (ma) { + return new Error(`${ma} is not a valid Multiaddr`) +} + +module.exports = function bootstrap (self) { + return { + list: promisify((callback) => { + self._repo.config.get((err, config) => { + if (err) { + return callback(err) + } + callback(null, { Peers: config.Bootstrap }) + }) + }), + add: promisify((multiaddr, args, callback) => { + if (typeof args === 'function') { + callback = args + args = { default: false } + } + + if (multiaddr && !isValidMultiaddr(multiaddr)) { + return setImmediate(() => callback(invalidMultiaddrError(multiaddr))) + } + + self._repo.config.get((err, config) => { + if (err) { + return callback(err) + } + if (args.default) { + config.Bootstrap = defaultConfig().Bootstrap + } else if (multiaddr && config.Bootstrap.indexOf(multiaddr) === -1) { + config.Bootstrap.push(multiaddr) + } + self._repo.config.set(config, (err) => { + if (err) { + return callback(err) + } + + callback(null, { + Peers: args.default ? defaultConfig().Bootstrap : [multiaddr] + }) + }) + }) + }), + rm: promisify((multiaddr, args, callback) => { + if (typeof args === 'function') { + callback = args + args = { all: false } + } + if (multiaddr && !isValidMultiaddr(multiaddr)) { + return setImmediate(() => callback(invalidMultiaddrError(multiaddr))) + } + + self._repo.config.get((err, config) => { + if (err) { + return callback(err) + } + if (args.all) { + config.Bootstrap = [] + } else { + config.Bootstrap = config.Bootstrap.filter((mh) => mh !== multiaddr) + } + + self._repo.config.set(config, (err) => { + if (err) { + return callback(err) + } + + const res = [] + if (!args.all && multiaddr) { + res.push(multiaddr) + } + + callback(null, { Peers: res }) + }) + }) + }) + } +} + +}).call(this,require("timers").setImmediate) +},{"../runtime/config-nodejs.js":551,"mafmt":1125,"promisify-es6":1263,"timers":1500}],480:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') + +module.exports = function config (self) { + return { + get: promisify((key, callback) => { + if (typeof key === 'function') { + callback = key + key = undefined + } + + return self._repo.config.get(key, callback) + }), + set: promisify((key, value, callback) => { + self._repo.config.set(key, value, callback) + }), + replace: promisify((config, callback) => { + self._repo.config.set(config, callback) + }) + } +} + +},{"promisify-es6":1263}],481:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const promisify = require('promisify-es6') +const CID = require('cids') +const pull = require('pull-stream') +const iterToPull = require('async-iterator-to-pull-stream') +const setImmediate = require('async/setImmediate') +const errCode = require('err-code') +const multicodec = require('multicodec') + +module.exports = function dag (self) { + return { + put: promisify((dagNode, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + if (options.cid && (options.format || options.hashAlg)) { + return callback(new Error('Can\'t put dag node. Please provide either `cid` OR `format` and `hashAlg` options.')) + } else if (((options.format && !options.hashAlg) || (!options.format && options.hashAlg))) { + return callback(new Error('Can\'t put dag node. Please provide `format` AND `hashAlg` options.')) + } + + const optionDefaults = { + format: multicodec.DAG_CBOR, + hashAlg: multicodec.SHA2_256 + } + + // The IPLD expects the format and hashAlg as constants + if (options.format && typeof options.format === 'string') { + const constantName = options.format.toUpperCase().replace(/-/g, '_') + options.format = multicodec[constantName] + } + if (options.hashAlg && typeof options.hashAlg === 'string') { + const constantName = options.hashAlg.toUpperCase().replace(/-/g, '_') + options.hashAlg = multicodec[constantName] + } + + options = options.cid ? options : Object.assign({}, optionDefaults, options) + + // js-ipld defaults to verion 1 CIDs. Hence set version 0 explicitly for + // dag-pb nodes + if (options.version === undefined) { + if (options.format === multicodec.DAG_PB && options.hashAlg === multicodec.SHA2_256) { + options.version = 0 + } else { + options.version = 1 + } + } + + self._ipld.put(dagNode, options.format, { + hashAlg: options.hashAlg, + cidVersion: options.version + }).then( + (cid) => { + if (options.preload !== false) { + self._preload(cid) + } + return callback(null, cid) + }, + (error) => callback(error) + ) + }), + + get: promisify((cid, path, options, callback) => { + if (typeof path === 'function') { + callback = path + path = undefined + } + + if (typeof options === 'function') { + callback = options + + // Allow options in path position + if (typeof path !== 'string') { + options = path + path = undefined + } else { + options = {} + } + } + + options = options || {} + + if (typeof cid === 'string') { + const split = cid.split('/') + + try { + cid = new CID(split[0]) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + split.shift() + + if (split.length > 0) { + path = split.join('/') + } else { + path = path || '/' + } + } else if (Buffer.isBuffer(cid)) { + try { + cid = new CID(cid) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + } + + if (options.preload !== false) { + self._preload(cid) + } + + if (path == null || path === '/') { + self._ipld.get(cid).then( + (value) => { + callback(null, { + value, + remainderPath: '' + }) + }, + (error) => callback(error) + ) + } else { + const result = self._ipld.resolve(cid, path) + const promisedValue = options.localResolve ? result.first() : result.last() + promisedValue.then( + (value) => callback(null, value), + (error) => callback(error) + ) + } + }), + + tree: promisify((cid, path, options, callback) => { + if (typeof path === 'object') { + callback = options + options = path + path = undefined + } + + if (typeof path === 'function') { + callback = path + path = undefined + } + + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + if (typeof cid === 'string') { + const split = cid.split('/') + + try { + cid = new CID(split[0]) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + split.shift() + + if (split.length > 0) { + path = split.join('/') + } else { + path = undefined + } + } + + if (options.preload !== false) { + self._preload(cid) + } + + pull( + iterToPull(self._ipld.tree(cid, path, options)), + pull.collect(callback) + ) + }) + } +} + +}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) +},{"../../../../is-buffer/index.js":608,"async-iterator-to-pull-stream":34,"async/setImmediate":96,"cids":185,"err-code":268,"multicodec":1151,"promisify-es6":1263,"pull-stream":1311}],482:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const promisify = require('promisify-es6') +const every = require('async/every') +const PeerId = require('peer-id') +const PeerInfo = require('peer-info') +const CID = require('cids') +const each = require('async/each') +const nextTick = require('async/nextTick') + +const errcode = require('err-code') + +const debug = require('debug') +const log = debug('ipfs:dht') +log.error = debug('ipfs:dht:error') + +module.exports = (self) => { + return { + /** + * Given a key, query the DHT for its best value. + * + * @param {Buffer} key + * @param {Object} options - get options + * @param {number} options.timeout - optional timeout + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + get: promisify((key, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + if (!Buffer.isBuffer(key)) { + try { + key = (new CID(key)).buffer + } catch (err) { + log.error(err) + + return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) + } + } + + self.libp2p.dht.get(key, options, callback) + }), + + /** + * Write a key/value pair to the DHT. + * + * Given a key of the form /foo/bar and a value of any + * form, this will write that value to the DHT with + * that key. + * + * @param {Buffer} key + * @param {Buffer} value + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + put: promisify((key, value, callback) => { + if (!Buffer.isBuffer(key)) { + try { + key = (new CID(key)).buffer + } catch (err) { + log.error(err) + + return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) + } + } + + self.libp2p.dht.put(key, value, callback) + }), + + /** + * Find peers in the DHT that can provide a specific value, given a key. + * + * @param {CID} key - They key to find providers for. + * @param {Object} options - findProviders options + * @param {number} options.timeout - how long the query should maximally run, in milliseconds (default: 60000) + * @param {number} options.maxNumProviders - maximum number of providers to find + * @param {function(Error, Array)} [callback] + * @returns {Promise|void} + */ + findProvs: promisify((key, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + if (typeof key === 'string') { + try { + key = new CID(key) + } catch (err) { + log.error(err) + + return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) + } + } + + self.libp2p.contentRouting.findProviders(key, options, callback) + }), + + /** + * Query the DHT for all multiaddresses associated with a `PeerId`. + * + * @param {PeerId} peer - The id of the peer to search for. + * @param {function(Error, PeerInfo)} [callback] + * @returns {Promise|void} + */ + findPeer: promisify((peer, callback) => { + if (typeof peer === 'string') { + peer = PeerId.createFromB58String(peer) + } + + self.libp2p.peerRouting.findPeer(peer, callback) + }), + + /** + * Announce to the network that we are providing given values. + * + * @param {CID|Array} keys - The keys that should be announced. + * @param {Object} options - provide options + * @param {bool} [options.recursive=false] - Provide not only the given object but also all objects linked from it. + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + provide: promisify((keys, options, callback) => { + if (!Array.isArray(keys)) { + keys = [keys] + } + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + // ensure blocks are actually local + every(keys, (key, cb) => { + self._repo.blocks.has(key, cb) + }, (err, has) => { + if (err) { + return callback(err) + } + + if (!has) { + const errMsg = 'block(s) not found locally, cannot provide' + + log.error(errMsg) + return callback(errcode(errMsg, 'ERR_BLOCK_NOT_FOUND')) + } + + if (options.recursive) { + // TODO: Implement recursive providing + return callback(errcode('not implemented yet', 'ERR_NOT_IMPLEMENTED_YET')) + } else { + each(keys, (cid, cb) => { + self.libp2p.contentRouting.provide(cid, cb) + }, callback) + } + }) + }), + + /** + * Find the closest peers to a given `PeerId`, by querying the DHT. + * + * @param {PeerId} peer - The `PeerId` to run the query agains. + * @param {function(Error, Array)} [callback] + * @returns {Promise>|void} + */ + query: promisify((peerId, callback) => { + if (typeof peerId === 'string') { + try { + peerId = PeerId.createFromB58String(peerId) + } catch (err) { + log.error(err) + return callback(err) + } + } + + // TODO expose this method in peerRouting + self.libp2p._dht.getClosestPeers(peerId.toBytes(), (err, peerIds) => { + if (err) { + log.error(err) + return callback(err) + } + + callback(null, peerIds.map((id) => new PeerInfo(id))) + }) + }) + } +} + +}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) +},{"../../../../is-buffer/index.js":608,"async/each":56,"async/every":62,"async/nextTick":90,"cids":185,"debug":456,"err-code":268,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],483:[function(require,module,exports){ +'use strict' + +// dns-nodejs gets replaced by dns-browser when webpacked/browserified +const dns = require('../runtime/dns-nodejs') +const promisify = require('promisify-es6') + +function fqdnFixups (domain) { + // Allow resolution of .eth names via .eth.link + // More context at the go-ipfs counterpart: https://github.com/ipfs/go-ipfs/pull/6448 + if (domain.endsWith('.eth')) { + domain = domain.replace(/.eth$/, '.eth.link') + } + return domain +} + +module.exports = () => { + return promisify((domain, opts, callback) => { + if (typeof domain !== 'string') { + return callback(new Error('Invalid arguments, domain must be a string')) + } + + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + opts = opts || {} + domain = fqdnFixups(domain) + + dns(domain, opts, callback) + }) +} + +},{"../runtime/dns-nodejs":552,"promisify-es6":1263}],484:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const mfs = require('ipfs-mfs/core') +const isPullStream = require('is-pull-stream') +const toPullStream = require('async-iterator-to-pull-stream') +const toReadableStream = require('async-iterator-to-stream') +const pullStreamToAsyncIterator = require('pull-stream-to-async-iterator') +const all = require('async-iterator-all') +const nodeify = require('promise-nodeify') +const PassThrough = require('stream').PassThrough +const pull = require('pull-stream/pull') +const map = require('pull-stream/throughs/map') +const isIpfs = require('is-ipfs') +const { cidToString } = require('../../utils/cid') + +/** + * @typedef { import("readable-stream").Readable } ReadableStream + * @typedef { import("pull-stream") } PullStream + */ + +const mapLsFile = (options = {}) => { + const long = options.long || options.l + + return (file) => { + return { + hash: long ? cidToString(file.cid, { base: options.cidBase }) : '', + name: file.name, + type: long ? file.type : 0, + size: long ? file.size || 0 : 0 + } + } +} + +module.exports = (/** @type { import("../index") } */ ipfs) => { + const methodsOriginal = mfs({ + ipld: ipfs._ipld, + blocks: ipfs._blockService, + datastore: ipfs._repo.root, + repoOwner: ipfs._options.repoOwner + }) + + const withPreload = fn => (...args) => { + const paths = args.filter(arg => isIpfs.ipfsPath(arg) || isIpfs.cid(arg)) + + if (paths.length) { + const options = args[args.length - 1] + if (options.preload !== false) { + paths.forEach(path => ipfs._preload(path)) + } + } + + return fn(...args) + } + + const methods = { + ...methodsOriginal, + cp: withPreload(methodsOriginal.cp), + ls: withPreload(methodsOriginal.ls), + mv: withPreload(methodsOriginal.mv), + read: withPreload(methodsOriginal.read), + stat: withPreload(methodsOriginal.stat) + } + + return { + /** + * Copy files + * + * @param {String | Array} from - The path(s) of the source to copy. + * @param {String} to - The path of the destination to copy to. + * @param {Object} [opts] - Options for copy. + * @param {boolean} [opts.parents=false] - Whether or not to make the parent directories if they don't exist. (default: false) + * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb) + * @param {String} [opts.hashAlg=sha2-256] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} + * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true). + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + cp: (from, to, opts, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(methods.cp(from, to, opts), cb) + }, + + /** + * Make a directory + * + * @param {String} path - The path to the directory to make. + * @param {Object} [opts] - Options for mkdir. + * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) + * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb). + * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} + * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true). + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + mkdir: (path, opts, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(methods.mkdir(path, opts), cb) + }, + + /** + * @typedef {Object} StatOutput + * @prop {String} hash - Output hash. + * @prop {number} size - File size in bytes. + * @prop {number} cumulativeSize - Integer with the size of the DAGNodes making up the file in Bytes. + * @prop {string} type - Output type either 'directory' or 'file'. + * @prop {number} blocks - If type is directory, this is the number of files in the directory. If it is file it is the number of blocks that make up the file. + * @prop {boolean} withLocality - Indicate if locality information is present. + * @prop {boolean} local - Indicate if the queried dag is fully present locally. + * @prop {number} sizeLocal - Integer indicating the cumulative size of the data present locally. + */ + + /** + * Get file or directory status. + * + * @param {String} path - Path to the file or directory to stat. + * @param {Object} [opts] - Options for stat. + * @param {boolean} [opts.hash=false] - Return only the hash. (default: false) + * @param {boolean} [opts.size=false] - Return only the size. (default: false) + * @param {boolean} [opts.withLocal=false] - Compute the amount of the dag that is local, and if possible the total size. (default: false) + * @param {String} [opts.cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc) + * @param {function(Error, StatOutput): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + stat: (path, opts, cb) => { + const stat = async (path, opts = {}) => { + const stats = await methods.stat(path, opts) + + stats.hash = stats.cid.toBaseEncodedString(opts && opts.cidBase) + delete stats.cid + + return stats + } + + if (typeof opts === 'function') { + cb = opts + opts = {} + } + + return nodeify(stat(path, opts), cb) + }, + + /** + * Remove a file or directory. + * + * @param {String | Array} paths - One or more paths to remove. + * @param {Object} [opts] - Options for remove. + * @param {boolean} [opts.recursive=false] - Whether or not to remove directories recursively. (default: false) + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + rm: (paths, opts, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(methods.rm(paths, opts), cb) + }, + + /** + * @typedef {Object} ReadOptions + * @prop {number} [opts.offset=0] - Integer with the byte offset to begin reading from (default: 0). + * @prop {number} [opts.length] - Integer with the maximum number of bytes to read (default: Read to the end of stream). + */ + + /** + * Read a file into a Buffer. + * + * @param {string} path - Path of the file to read and must point to a file (and not a directory). + * @param {ReadOptions} [opts] - Object for read. + * @param {function(Error, Buffer): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + read: (path, opts, cb) => { + const read = async (path, opts = {}) => { + return Buffer.concat(await all(methods.read(path, opts))) + } + + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(read(path, opts), cb) + }, + + /** + * Read a file into a ReadableStream. + * + * @param {string} path - Path of the file to read and must point to a file (and not a directory). + * @param {ReadOptions} [opts] - Object for read. + * @returns {ReadableStream} Returns a ReadableStream with the contents of path. + */ + readReadableStream: (path, opts = {}) => toReadableStream(methods.read(path, opts)), + + /** + * Read a file into a PullStrean. + * + * @param {string} path - Path of the file to read and must point to a file (and not a directory). + * @param {ReadOptions} [opts] - Object for read. + * @returns {PullStream} Returns a PullStream with the contents of path. + */ + readPullStream: (path, opts = {}) => toPullStream.source(methods.read(path, opts)), + + /** + * Write to a file. + * + * @param {string} path - Path of the file to write. + * @param {Buffer | PullStream | ReadableStream | Blob | string} content - Content to write. + * @param {Object} opts - Options for write. + * @param {number} [opts.offset=0] - Integer with the byte offset to begin writing at. (default: 0) + * @param {boolean} [opts.create=false] - Indicate to create the file if it doesn't exist. (default: false) + * @param {boolean} [opts.truncate=false] - Indicate if the file should be truncated after writing all the bytes from content. (default: false) + * @param {boolena} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) + * @param {number} [opts.length] - Maximum number of bytes to read. (default: Read all bytes from content) + * @param {boolean} [opts.rawLeaves=false] - If true, DAG leaves will contain raw file data and not be wrapped in a protobuf. (default: false) + * @param {number} [opts.cidVersion=0] - The CID version to use when storing the data (storage keys are based on the CID, including its version). (default: 0) + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + write: (path, content, opts, cb) => { + const write = async (path, content, opts = {}) => { + if (isPullStream.isSource(content)) { + content = pullStreamToAsyncIterator(content) + } + + await methods.write(path, content, opts) + } + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(write(path, content, opts), cb) + }, + + /** + * Move files. + * + * @param {string | Array} from - Path(s) of the source to move. + * @param {string} to - Path of the destination to move to. + * @param {Object} opts - Options for mv. + * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) + * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb). + * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} + * @param {boolean} [opts.flush=true] - Value to decide whether or not to immediately flush MFS changes to disk. (default: true) + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + * @description + * If from has multiple values then to must be a directory. + * + * If from has a single value and to exists and is a directory, from will be moved into to. + * + * If from has a single value and to exists and is a file, from must be a file and the contents of to will be replaced with the contents of from otherwise an error will be returned. + * + * If from is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen. + * + * All values of from will be removed after the operation is complete unless they are an IPFS path. + */ + mv: (from, to, opts, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(methods.mv(from, to, opts), cb) + }, + + /** + * Flush a given path's data to the disk. + * + * @param {string | Array} [paths] - String paths to flush. (default: /) + * @param {function(Error): void} [cb] - Callback function. + * @returns {Promise | void} When callback is provided nothing is returned. + */ + flush: (paths, cb) => { + if (typeof paths === 'function') { + cb = paths + paths = undefined + } + return nodeify(methods.flush(paths), cb) + }, + + /** + * @typedef {Object} ListOutputFile + * @prop {string} name - Which is the file's name. + * @prop {string} type - Which is the object's type (directory or file). + * @prop {number} size - The size of the file in bytes. + * @prop {string} hash - The hash of the file. + */ + + /** + * @typedef {Object} ListOptions + * @prop {boolean} [long=false] - Value to decide whether or not to populate type, size and hash. (default: false) + * @prop {string} [cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc) + * @prop {boolean} [sort=false] - If true entries will be sorted by filename. (default: false) + */ + + /** + * List directories in the local mutable namespace. + * + * @param {string} [path="/"] - String to show listing for. (default: /) + * @param {ListOptions} [opts] - Options for list. + * @param {function(Error, Array): void} [cb] - Callback function. + * @returns {Promise> | void} When callback is provided nothing is returned. + */ + ls: (path, opts, cb) => { + const ls = async (path, opts = {}) => { + const files = await all(methods.ls(path, opts)) + + return files.map(mapLsFile(opts)) + } + + if (typeof path === 'function') { + cb = path + path = '/' + opts = {} + } + + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(ls(path, opts), cb) + }, + + /** + * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as Readable Streams. + * + * @param {string} [path="/"] - String to show listing for. (default: /) + * @param {ListOptions} [opts] - Options for list. + * @returns {ReadableStream} It returns a Readable Stream in Object mode that will yield {@link ListOutputFile} + */ + lsReadableStream: (path, opts = {}) => { + const stream = toReadableStream.obj(methods.ls(path, opts)) + const through = new PassThrough({ + objectMode: true + }) + stream.on('data', (file) => { + through.write(mapLsFile(opts)(file)) + }) + stream.on('error', (err) => { + through.destroy(err) + }) + stream.on('end', (file, enc, cb) => { + if (file) { + file = mapLsFile(opts)(file) + } + + through.end(file, enc, cb) + }) + + return through + }, + + /** + * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as PullStreams. + * + * @param {string} [path="/"] - String to show listing for. (default: /) + * @param {ListOptions} [opts] - Options for list. + * @returns {PullStream} It returns a PullStream that will yield {@link ListOutputFile} + */ + lsPullStream: (path, opts = {}) => { + return pull( + toPullStream.source(methods.ls(path, opts)), + map(mapLsFile(opts)) + ) + } + } +} + +}).call(this,require("buffer").Buffer) +},{"../../utils/cid":561,"async-iterator-all":30,"async-iterator-to-pull-stream":34,"async-iterator-to-stream":35,"buffer":181,"ipfs-mfs/core":354,"is-ipfs":614,"is-pull-stream":617,"promise-nodeify":1259,"pull-stream-to-async-iterator":1309,"pull-stream/pull":1312,"pull-stream/throughs/map":1334,"stream":472}],485:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const importer = require('ipfs-unixfs-importer') +const normaliseAddInput = require('ipfs-utils/src/files/normalise-input') +const { parseChunkerString } = require('./utils') +const pipe = require('it-pipe') +const log = require('debug')('ipfs:add') +log.error = require('debug')('ipfs:add:error') + +function noop () {} + +module.exports = function (self) { + // Internal add func that gets used by all add funcs + return async function * addAsyncIterator (source, options) { + options = options || {} + + const chunkerOptions = parseChunkerString(options.chunker) + + const opts = Object.assign({}, { + shardSplitThreshold: self._options.EXPERIMENTAL.sharding + ? 1000 + : Infinity + }, options, { + chunker: chunkerOptions.chunker, + chunkerOptions: chunkerOptions.chunkerOptions + }) + + // CID v0 is for multihashes encoded with sha2-256 + if (opts.hashAlg && opts.cidVersion !== 1) { + opts.cidVersion = 1 + } + + let total = 0 + + const prog = opts.progress || noop + const progress = (bytes) => { + total += bytes + prog(total) + } + + opts.progress = progress + + const iterator = pipe( + normaliseAddInput(source), + doImport(self, opts), + transformFile(self, opts), + preloadFile(self, opts), + pinFile(self, opts) + ) + + const releaseLock = await self._gcLock.readLock() + + try { + yield * iterator + } finally { + releaseLock() + } + } +} + +function doImport (ipfs, opts) { + return async function * (source) { // eslint-disable-line require-await + yield * importer(source, ipfs._ipld, opts) + } +} + +function transformFile (ipfs, opts) { + return async function * (source) { + for await (const file of source) { + let cid = file.cid + const hash = cid.toBaseEncodedString() + let path = file.path ? file.path : hash + + if (opts.wrapWithDirectory && !file.path) { + path = '' + } + + if (opts.onlyHash) { + yield { + path, + hash, + size: file.unixfs.fileSize() + } + + return + } + + const node = await ipfs.object.get(file.cid, Object.assign({}, opts, { preload: false })) + + if (opts.cidVersion === 1) { + cid = cid.toV1() + } + + let size = node.size + + if (Buffer.isBuffer(node)) { + size = node.length + } + + yield { + path, + hash, + size + } + } + } +} + +function preloadFile (ipfs, opts) { + return async function * (source) { + for await (const file of source) { + const isRootFile = !file.path || opts.wrapWithDirectory + ? file.path === '' + : !file.path.includes('/') + + const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false + + if (shouldPreload) { + ipfs._preload(file.hash) + } + + yield file + } + } +} + +function pinFile (ipfs, opts) { + return async function * (source) { + for await (const file of source) { + // Pin a file if it is the root dir of a recursive add or the single file + // of a direct add. + const pin = 'pin' in opts ? opts.pin : true + const isRootDir = !file.path.includes('/') + const shouldPin = pin && isRootDir && !opts.onlyHash && !opts.hashAlg + + if (shouldPin) { + // Note: addAsyncIterator() has already taken a GC lock, so tell + // pin.add() not to take a (second) GC lock + await ipfs.pin.add(file.hash, { + preload: false, + lock: false + }) + } + + yield file + } + } +} + +}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) +},{"../../../../../is-buffer/index.js":608,"./utils":508,"debug":456,"ipfs-unixfs-importer":431,"ipfs-utils/src/files/normalise-input":454,"it-pipe":644}],486:[function(require,module,exports){ +'use strict' + +module.exports = (self) => require('../../runtime/add-from-fs-nodejs')(self) + +},{"../../runtime/add-from-fs-nodejs":550}],487:[function(require,module,exports){ +'use strict' + +module.exports = self => require('./add')(self) + +},{"./add":491}],488:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const { URL } = require('iso-url') +const fetch = require('../../runtime/fetch-nodejs') + +module.exports = (self) => { + return async (url, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + let files + + try { + const parsedUrl = new URL(url) + const res = await fetch(url) + + if (!res.ok) { + throw new Error('unexpected status code: ' + res.status) + } + + // TODO: use res.body when supported + const content = Buffer.from(await res.arrayBuffer()) + const path = decodeURIComponent(parsedUrl.pathname.split('/').pop()) + + files = await self.add({ content, path }, options) + } catch (err) { + if (callback) { + return callback(err) + } + throw err + } + + if (callback) { + callback(null, files) + } + + return files + } +} + +}).call(this,require("buffer").Buffer) +},{"../../runtime/fetch-nodejs":553,"buffer":181,"iso-url":641}],489:[function(require,module,exports){ +'use strict' + +const toPullStream = require('async-iterator-to-pull-stream') + +module.exports = function (self) { + return function addPullStream (options) { + return toPullStream.transform((source) => { + return self._addAsyncIterator(source, options) + }) + } +} + +},{"async-iterator-to-pull-stream":34}],490:[function(require,module,exports){ +'use strict' + +const toStream = require('it-to-stream') + +module.exports = function (self) { + return function addReadableStream (options) { + return toStream.transform(source => { + return self._addAsyncIterator(source, options) + }, { + objectMode: true + }) + } +} + +},{"it-to-stream":664}],491:[function(require,module,exports){ +'use strict' + +const all = require('async-iterator-all') + +module.exports = function (self) { + // can't use callbackify because if `data` is a pull stream + // it thinks we are passing a callback. This is why we can't have nice things. + return (data, options, callback) => { + if (!callback && typeof options === 'function') { + callback = options + options = {} + } + + const result = all(self._addAsyncIterator(data, options)) + + if (!callback) { + return result + } + + result.then((result) => callback(null, result), callback) + } +} + +},{"async-iterator-all":30}],492:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const deferred = require('pull-defer') +const toPullStream = require('async-iterator-to-pull-stream') +const { normalizePath } = require('./utils') + +module.exports = function (self) { + return function catPullStream (ipfsPath, options) { + if (typeof ipfsPath === 'function') { + throw new Error('You must supply an ipfsPath') + } + + options = options || {} + + ipfsPath = normalizePath(ipfsPath) + const pathComponents = ipfsPath.split('/') + + if (options.preload !== false) { + self._preload(pathComponents[0]) + } + + const d = deferred.source() + + exporter(ipfsPath, self._ipld, options) + .then(file => { + // File may not have unixfs prop if small & imported with rawLeaves true + if (file.unixfs && file.unixfs.type.includes('dir')) { + return d.abort(new Error('this dag node is a directory')) + } + + if (!file.content) { + return d.abort(new Error('this dag node has no content')) + } + + d.resolve(toPullStream.source(file.content(options))) + }, err => { + d.abort(err) + }) + + return d + } +} + +},{"./utils":508,"async-iterator-to-pull-stream":34,"ipfs-unixfs-exporter":400,"pull-defer":1285}],493:[function(require,module,exports){ +'use strict' + +const toStream = require('pull-stream-to-stream') + +module.exports = function (self) { + return (ipfsPath, options) => toStream.source(self.catPullStream(ipfsPath, options)) +} + +},{"pull-stream-to-stream":1310}],494:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream') + +module.exports = function (self) { + return promisify((ipfsPath, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + pull( + self.catPullStream(ipfsPath, options), + pull.collect((err, buffers) => { + if (err) { return callback(err) } + callback(null, Buffer.concat(buffers)) + }) + ) + }) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"promisify-es6":1263,"pull-stream":1311}],495:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const toPullStream = require('async-iterator-to-pull-stream') +const errCode = require('err-code') +const pull = require('pull-stream/pull') +const pullError = require('pull-stream/sources/error') +const map = require('pull-stream/throughs/map') +const { normalizePath, mapFile } = require('./utils') + +module.exports = function (self) { + return (ipfsPath, options) => { + options = options || {} + + if (options.preload !== false) { + let pathComponents + + try { + pathComponents = normalizePath(ipfsPath).split('/') + } catch (err) { + return pullError(errCode(err, 'ERR_INVALID_PATH')) + } + + self._preload(pathComponents[0]) + } + + return pull( + toPullStream.source(exporter.recursive(ipfsPath, self._ipld, options)), + map(mapFile({ + ...options, + includeContent: true + })) + ) + } +} + +},{"./utils":508,"async-iterator-to-pull-stream":34,"err-code":268,"ipfs-unixfs-exporter":400,"pull-stream/pull":1312,"pull-stream/sources/error":1323,"pull-stream/throughs/map":1334}],496:[function(require,module,exports){ +'use strict' + +const pull = require('pull-stream') +const toStream = require('pull-stream-to-stream') + +module.exports = function (self) { + return (ipfsPath, options) => { + options = options || {} + + return toStream.source( + pull( + self.getPullStream(ipfsPath, options), + pull.map((file) => { + if (file.content) { + file.content = toStream.source(file.content) + file.content.pause() + } + + return file + }) + ) + ) + } +} + +},{"pull-stream":1311,"pull-stream-to-stream":1310}],497:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream') + +module.exports = function (self) { + return promisify((ipfsPath, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + pull( + self.getPullStream(ipfsPath, options), + pull.asyncMap((file, cb) => { + if (file.content) { + pull( + file.content, + pull.collect((err, buffers) => { + if (err) { return cb(err) } + file.content = Buffer.concat(buffers) + cb(null, file) + }) + ) + } else { + cb(null, file) + } + }), + pull.collect(callback) + ) + }) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"promisify-es6":1263,"pull-stream":1311}],498:[function(require,module,exports){ +'use strict' + +module.exports = (self) => { + const filesRegular = { + add: require('./add')(self), + addFromFs: require('./add-from-fs')(self), + addFromStream: require('./add-from-stream')(self), + addFromURL: require('./add-from-url')(self), + addPullStream: require('./add-pull-stream')(self), + addReadableStream: require('./add-readable-stream')(self), + _addAsyncIterator: require('./add-async-iterator')(self), + cat: require('./cat')(self), + catPullStream: require('./cat-pull-stream')(self), + catReadableStream: require('./cat-readable-stream')(self), + get: require('./get')(self), + getPullStream: require('./get-pull-stream')(self), + getReadableStream: require('./get-readable-stream')(self), + ls: require('./ls')(self), + lsPullStream: require('./ls-pull-stream')(self), + lsReadableStream: require('./ls-readable-stream')(self), + refs: require('./refs')(self), + refsReadableStream: require('./refs-readable-stream')(self), + refsPullStream: require('./refs-pull-stream')(self) + } + filesRegular.refs.local = require('./refs-local')(self) + filesRegular.refs.localReadableStream = require('./refs-local-readable-stream')(self) + filesRegular.refs.localPullStream = require('./refs-local-pull-stream')(self) + return filesRegular +} + +},{"./add":491,"./add-async-iterator":485,"./add-from-fs":486,"./add-from-stream":487,"./add-from-url":488,"./add-pull-stream":489,"./add-readable-stream":490,"./cat":494,"./cat-pull-stream":492,"./cat-readable-stream":493,"./get":497,"./get-pull-stream":495,"./get-readable-stream":496,"./ls":501,"./ls-pull-stream":499,"./ls-readable-stream":500,"./refs":507,"./refs-local":504,"./refs-local-pull-stream":502,"./refs-local-readable-stream":503,"./refs-pull-stream":505,"./refs-readable-stream":506}],499:[function(require,module,exports){ +'use strict' + +const exporter = require('ipfs-unixfs-exporter') +const deferred = require('pull-defer') +const pull = require('pull-stream/pull') +const once = require('pull-stream/sources/once') +const map = require('pull-stream/throughs/map') +const filter = require('pull-stream/throughs/filter') +const errCode = require('err-code') +const toPullStream = require('async-iterator-to-pull-stream') +const { normalizePath, mapFile } = require('./utils') + +module.exports = function (self) { + return function (ipfsPath, options) { + options = options || {} + + const path = normalizePath(ipfsPath) + const recursive = options.recursive + const pathComponents = path.split('/') + + if (options.preload !== false) { + self._preload(pathComponents[0]) + } + + const d = deferred.source() + + exporter(ipfsPath, self._ipld, options) + .then(file => { + if (!file.unixfs) { + return d.abort(errCode(new Error('dag node was not a UnixFS node'), 'ENOTUNIXFS')) + } + + if (file.unixfs.type === 'file') { + return d.resolve(once(mapFile(options)(file))) + } + + if (file.unixfs.type.includes('dir')) { + if (recursive) { + return d.resolve(pull( + toPullStream.source(exporter.recursive(file.cid, self._ipld, options)), + filter(child => file.cid.toBaseEncodedString() !== child.cid.toBaseEncodedString()), + map(mapFile(options)) + )) + } + + return d.resolve(pull( + toPullStream.source(file.content()), + map(mapFile(options)), + map((file) => { + file.depth-- + + return file + }) + )) + } + + d.abort(errCode(new Error(`Unknown UnixFS type ${file.unixfs.type}`), 'EUNKNOWNUNIXFSTYPE')) + }, err => { + d.abort(err) + }) + + return d + } +} + +},{"./utils":508,"async-iterator-to-pull-stream":34,"err-code":268,"ipfs-unixfs-exporter":400,"pull-defer":1285,"pull-stream/pull":1312,"pull-stream/sources/once":1327,"pull-stream/throughs/filter":1331,"pull-stream/throughs/map":1334}],500:[function(require,module,exports){ +'use strict' + +const toStream = require('pull-stream-to-stream') + +module.exports = function (self) { + return (ipfsPath, options) => { + return toStream.source(self.lsPullStream(ipfsPath, options)) + } +} + +},{"pull-stream-to-stream":1310}],501:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream') + +module.exports = function (self) { + return promisify((ipfsPath, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + pull( + self.lsPullStream(ipfsPath, options), + pull.collect((err, values) => { + if (err) { + return callback(err) + } + callback(null, values) + }) + ) + }) +} + +},{"promisify-es6":1263,"pull-stream":1311}],502:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') +const base32 = require('base32.js') +const pull = require('pull-stream') +const pullDefer = require('pull-defer') + +module.exports = function (self) { + return () => { + const deferred = pullDefer.source() + + self._repo.blocks.query({ keysOnly: true }, (err, blocks) => { + if (err) { + return deferred.resolve(pull.error(err)) + } + + const refs = blocks.map(b => dsKeyToRef(b.key)) + deferred.resolve(pull.values(refs)) + }) + + return deferred + } +} + +function dsKeyToRef (key) { + try { + // Block key is of the form / + const decoder = new base32.Decoder() + const buff = Buffer.from(decoder.write(key.toString().slice(1)).finalize()) + return { ref: new CID(buff).toString() } + } catch (err) { + return { err: `Could not convert block with key '${key}' to CID: ${err.message}` } + } +} + +}).call(this,require("buffer").Buffer) +},{"base32.js":107,"buffer":181,"cids":185,"pull-defer":1285,"pull-stream":1311}],503:[function(require,module,exports){ +'use strict' + +const toStream = require('pull-stream-to-stream') + +module.exports = function (self) { + return (ipfsPath, options) => { + return toStream.source(self.refs.localPullStream()) + } +} + +},{"pull-stream-to-stream":1310}],504:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream') + +module.exports = function (self) { + return promisify((callback) => { + pull( + self.refs.localPullStream(), + pull.collect((err, values) => { + if (err) { + return callback(err) + } + callback(null, values) + }) + ) + }) +} + +},{"promisify-es6":1263,"pull-stream":1311}],505:[function(require,module,exports){ +'use strict' + +const pull = require('pull-stream') +const pullDefer = require('pull-defer') +const pullTraverse = require('pull-traverse') +const pullCat = require('pull-cat') +const isIpfs = require('is-ipfs') +const CID = require('cids') +const { DAGNode } = require('ipld-dag-pb') +const { normalizePath } = require('./utils') +const { Format } = require('./refs') + +module.exports = function (self) { + return function (ipfsPath, options = {}) { + if (options.maxDepth === 0) { + return pull.empty() + } + if (options.edges && options.format && options.format !== Format.default) { + return pull.error(new Error('Cannot set edges to true and also specify format')) + } + + options.format = options.edges ? Format.edges : options.format || Format.default + + if (typeof options.maxDepth !== 'number') { + options.maxDepth = options.recursive ? Infinity : 1 + } + + let paths + try { + const rawPaths = Array.isArray(ipfsPath) ? ipfsPath : [ipfsPath] + paths = rawPaths.map(p => getFullPath(self, p, options)) + } catch (err) { + return pull.error(err) + } + + return pullCat(paths.map(p => refsStream(self, p, options))) + } +} + +function getFullPath (ipfs, ipfsPath, options) { + // normalizePath() strips /ipfs/ off the front of the path so the CID will + // be at the front of the path + const path = normalizePath(ipfsPath) + const pathComponents = path.split('/') + const cid = pathComponents[0] + if (!isIpfs.cid(cid)) { + throw new Error(`Error resolving path '${path}': '${cid}' is not a valid CID`) + } + + if (options.preload !== false) { + ipfs._preload(cid) + } + + return '/ipfs/' + path +} + +// Get a stream of refs at the given path +function refsStream (ipfs, path, options) { + const deferred = pullDefer.source() + + // Resolve to the target CID of the path + ipfs.resolve(path, (err, resPath) => { + if (err) { + return deferred.resolve(pull.error(err)) + } + + // path is /ipfs/ + const parts = resPath.split('/') + const cid = parts[2] + deferred.resolve(pull( + // Traverse the DAG, converting it into a stream + objectStream(ipfs, cid, options.maxDepth, options.unique), + // Root object will not have a parent + pull.filter(obj => Boolean(obj.parent)), + // Filter out duplicates (isDuplicate flag is only set if options.unique is set) + pull.filter(obj => !obj.isDuplicate), + // Format the links + pull.map(obj => formatLink(obj.parent.cid, obj.node.cid, obj.node.name, options.format)), + // Clients expect refs to be in the format { ref: } + pull.map(ref => ({ ref })) + )) + }) + + return deferred +} + +// Get formatted link +function formatLink (srcCid, dstCid, linkName, format) { + let out = format.replace(//g, srcCid.toString()) + out = out.replace(//g, dstCid.toString()) + out = out.replace(//g, linkName) + return out +} + +// Do a depth first search of the DAG, starting from the given root cid +function objectStream (ipfs, rootCid, maxDepth, isUnique) { + const uniques = new Set() + + const root = { node: { cid: rootCid }, depth: 0 } + const traverseLevel = (obj) => { + const { node, depth } = obj + + // Check the depth + const nextLevelDepth = depth + 1 + if (nextLevelDepth > maxDepth) { + return pull.empty() + } + + // If unique option is enabled, check if the CID has been seen before. + // Note we need to do this here rather than before adding to the stream + // so that the unique check happens in the order that items are examined + // in the DAG. + if (isUnique) { + if (uniques.has(node.cid.toString())) { + // Mark this object as a duplicate so we can filter it out later + obj.isDuplicate = true + return pull.empty() + } + uniques.add(node.cid.toString()) + } + + const deferred = pullDefer.source() + + // Get this object's links + getLinks(ipfs, node.cid, (err, links) => { + if (err) { + if (err.code === 'ERR_NOT_FOUND') { + err.message = `Could not find object with CID: ${node.cid}` + } + return deferred.resolve(pull.error(err)) + } + + // Add to the stream each link, parent and the new depth + const vals = links.map(link => ({ + parent: node, + node: link, + depth: nextLevelDepth + })) + + deferred.resolve(pull.values(vals)) + }) + + return deferred + } + + return pullTraverse.depthFirst(root, traverseLevel) +} + +// Fetch a node from IPLD then get all its links +function getLinks (ipfs, cid, callback) { + ipfs._ipld.get(new CID(cid)) + .then(node => { + let links + if (DAGNode.isDAGNode(node)) { + links = node.Links.map(({ Name, Hash }) => { + return { name: Name, cid: new CID(Hash) } + }) + } else { + links = getNodeLinks(node) + } + callback(null, links) + }) + .catch(callback) +} + +// Recursively search the node for CIDs +function getNodeLinks (node, path = '') { + let links = [] + for (const [name, value] of Object.entries(node)) { + if (CID.isCID(value)) { + links.push({ + name: path + name, + cid: value + }) + } else if (typeof value === 'object') { + links = links.concat(getNodeLinks(value, path + name + '/')) + } + } + return links +} + +},{"./refs":507,"./utils":508,"cids":185,"ipld-dag-pb":589,"is-ipfs":614,"pull-cat":1283,"pull-defer":1285,"pull-stream":1311,"pull-traverse":1343}],506:[function(require,module,exports){ +'use strict' + +const toStream = require('pull-stream-to-stream') + +module.exports = function (self) { + return (ipfsPath, options) => { + return toStream.source(self.refsPullStream(ipfsPath, options)) + } +} + +},{"pull-stream-to-stream":1310}],507:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream') + +module.exports = function (self) { + return promisify((ipfsPath, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + pull( + self.refsPullStream(ipfsPath, options), + pull.collect((err, values) => { + if (err) { + return callback(err) + } + callback(null, values) + }) + ) + }) +} + +// Preset format strings +module.exports.Format = { + default: '', + edges: ' -> ' +} + +},{"promisify-es6":1263,"pull-stream":1311}],508:[function(require,module,exports){ +'use strict' + +const CID = require('cids') +const { Buffer } = require('buffer') +const { cidToString } = require('../../../utils/cid') +const toPullStream = require('async-iterator-to-pull-stream') + +const normalizePath = (path) => { + if (Buffer.isBuffer(path)) { + return new CID(path).toString() + } + if (CID.isCID(path)) { + return path.toString() + } + if (path.indexOf('/ipfs/') === 0) { + path = path.substring('/ipfs/'.length) + } + if (path.charAt(path.length - 1) === '/') { + path = path.substring(0, path.length - 1) + } + return path +} + +/** + * Parses chunker string into options used by DAGBuilder in ipfs-unixfs-engine + * + * + * @param {String} chunker Chunker algorithm supported formats: + * "size-{size}" + * "rabin" + * "rabin-{avg}" + * "rabin-{min}-{avg}-{max}" + * + * @return {Object} Chunker options for DAGBuilder + */ +const parseChunkerString = (chunker) => { + if (!chunker) { + return { + chunker: 'fixed' + } + } else if (chunker.startsWith('size-')) { + const sizeStr = chunker.split('-')[1] + const size = parseInt(sizeStr) + if (isNaN(size)) { + throw new Error('Chunker parameter size must be an integer') + } + return { + chunker: 'fixed', + chunkerOptions: { + maxChunkSize: size + } + } + } else if (chunker.startsWith('rabin')) { + return { + chunker: 'rabin', + chunkerOptions: parseRabinString(chunker) + } + } else { + throw new Error(`Unrecognized chunker option: ${chunker}`) + } +} + +/** + * Parses rabin chunker string + * + * @param {String} chunker Chunker algorithm supported formats: + * "rabin" + * "rabin-{avg}" + * "rabin-{min}-{avg}-{max}" + * + * @return {Object} rabin chunker options + */ +const parseRabinString = (chunker) => { + const options = {} + const parts = chunker.split('-') + switch (parts.length) { + case 1: + options.avgChunkSize = 262144 + break + case 2: + options.avgChunkSize = parseChunkSize(parts[1], 'avg') + break + case 4: + options.minChunkSize = parseChunkSize(parts[1], 'min') + options.avgChunkSize = parseChunkSize(parts[2], 'avg') + options.maxChunkSize = parseChunkSize(parts[3], 'max') + break + default: + throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"') + } + + return options +} + +const parseChunkSize = (str, name) => { + const size = parseInt(str) + if (isNaN(size)) { + throw new Error(`Chunker parameter ${name} must be an integer`) + } + + return size +} + +const mapFile = (options = {}) => { + return (file) => { + let size = 0 + let type = 'dir' + + if (file.unixfs && file.unixfs.type === 'file') { + size = file.unixfs.fileSize() + type = 'file' + } + + const output = { + hash: cidToString(file.cid, { base: options.cidBase }), + path: file.path, + name: file.name, + depth: file.path.split('/').length, + size, + type + } + + if (options.includeContent && file.unixfs && file.unixfs.type === 'file') { + output.content = toPullStream.source(file.content()) + } + + return output + } +} + +module.exports = { + normalizePath, + parseChunkSize, + parseRabinString, + parseChunkerString, + mapFile +} + +},{"../../../utils/cid":561,"async-iterator-to-pull-stream":34,"buffer":181,"cids":185}],509:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const setImmediate = require('async/setImmediate') +const pkgversion = require('../../../package.json').version + +module.exports = function id (self) { + return promisify((opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + setImmediate(() => callback(null, { + id: self._peerInfo.id.toB58String(), + publicKey: self._peerInfo.id.pubKey.bytes.toString('base64'), + addresses: self._peerInfo.multiaddrs + .toArray() + .map((ma) => ma.toString()) + .filter((ma) => ma.indexOf('ipfs') >= 0) + .sort(), + agentVersion: `js-ipfs/${pkgversion}`, + protocolVersion: '9000' + })) + }) +} + +},{"../../../package.json":475,"async/setImmediate":96,"promisify-es6":1263}],510:[function(require,module,exports){ +'use strict' + +exports.preStart = require('./pre-start') +exports.start = require('./start') +exports.stop = require('./stop') +exports.isOnline = require('./is-online') +exports.version = require('./version') +exports.id = require('./id') +exports.repo = require('./repo') +exports.init = require('./init') +exports.bootstrap = require('./bootstrap') +exports.config = require('./config') +exports.block = require('./block') +exports.object = require('./object') +exports.dag = require('./dag') +exports.libp2p = require('./libp2p') +exports.swarm = require('./swarm') +exports.ping = require('./ping') +exports.pingPullStream = require('./ping-pull-stream') +exports.pingReadableStream = require('./ping-readable-stream') +exports.pin = require('./pin') +exports.filesRegular = require('./files-regular') +exports.filesMFS = require('./files-mfs') +exports.bitswap = require('./bitswap') +exports.pubsub = require('./pubsub') +exports.dht = require('./dht') +exports.dns = require('./dns') +exports.key = require('./key') +exports.stats = require('./stats') +exports.resolve = require('./resolve') +exports.name = require('./name') + +},{"./bitswap":477,"./block":478,"./bootstrap":479,"./config":480,"./dag":481,"./dht":482,"./dns":483,"./files-mfs":484,"./files-regular":498,"./id":509,"./init":511,"./is-online":512,"./key":513,"./libp2p":514,"./name":516,"./object":518,"./pin":519,"./ping":527,"./ping-pull-stream":525,"./ping-readable-stream":526,"./pre-start":528,"./pubsub":529,"./repo":530,"./resolve":531,"./start":532,"./stats":533,"./stop":534,"./swarm":535,"./version":536}],511:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const peerId = require('peer-id') +const mergeOptions = require('merge-options') +const waterfall = require('async/waterfall') +const parallel = require('async/parallel') +const promisify = require('promisify-es6') +const defaultConfig = require('../runtime/config-nodejs.js') +const Keychain = require('libp2p-keychain') +const { + DAGNode +} = require('ipld-dag-pb') +const UnixFs = require('ipfs-unixfs') +const multicodec = require('multicodec') + +const IPNS = require('../ipns') +const OfflineDatastore = require('../ipns/routing/offline-datastore') + +const addDefaultAssets = require('./init-assets') + +module.exports = function init (self) { + return promisify((opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + const done = (err, res) => { + if (err) { + self.emit('error', err) + return callback(err) + } + + self.preStart((err) => { + if (err) { + self.emit('error', err) + return callback(err) + } + + self.state.initialized() + self.emit('init') + callback(null, res) + }) + } + + if (self.state.state() !== 'uninitialized') { + return done(new Error('Not able to init from state: ' + self.state.state())) + } + + self.state.init() + self.log('init') + + // An initialized, open repo was passed, use this one! + if (opts.repo) { + self._repo = opts.repo + return done(null, true) + } + + opts.emptyRepo = opts.emptyRepo || false + opts.bits = Number(opts.bits) || 2048 + opts.log = opts.log || function () {} + + const config = mergeOptions(defaultConfig(), self._options.config) + let privateKey + + waterfall([ + // Verify repo does not yet exist. + (cb) => self._repo.exists(cb), + (exists, cb) => { + self.log('repo exists?', exists) + if (exists === true) { + return cb(new Error('repo already exists')) + } + + if (opts.privateKey) { + self.log('using user-supplied private-key') + if (typeof opts.privateKey === 'object') { + cb(null, opts.privateKey) + } else { + peerId.createFromPrivKey(Buffer.from(opts.privateKey, 'base64'), cb) + } + } else { + // Generate peer identity keypair + transform to desired format + add to config. + opts.log(`generating ${opts.bits}-bit RSA keypair...`, false) + self.log('generating peer id: %s bits', opts.bits) + peerId.create({ bits: opts.bits }, cb) + } + }, + (peerId, cb) => { + self.log('identity generated') + config.Identity = { + PeerID: peerId.toB58String(), + PrivKey: peerId.privKey.bytes.toString('base64') + } + privateKey = peerId.privKey + if (opts.pass) { + config.Keychain = Keychain.generateOptions() + } + opts.log('done') + opts.log('peer identity: ' + config.Identity.PeerID) + + self._repo.init(config, cb) + }, + (_, cb) => self._repo.open(cb), + (cb) => { + self.log('repo opened') + if (opts.pass) { + self.log('creating keychain') + const keychainOptions = Object.assign({ passPhrase: opts.pass }, config.Keychain) + self._keychain = new Keychain(self._repo.keys, keychainOptions) + self._keychain.importPeer('self', { privKey: privateKey }, cb) + } else { + cb(null, true) + } + }, + // Setup the offline routing for IPNS. + // This is primarily used for offline ipns modifications, such as the initializeKeyspace feature. + (_, cb) => { + const offlineDatastore = new OfflineDatastore(self._repo) + + self._ipns = new IPNS(offlineDatastore, self._repo.datastore, self._peerInfo, self._keychain, self._options) + cb(null, true) + }, + // add empty unixfs dir object (go-ipfs assumes this exists) + (_, cb) => { + if (opts.emptyRepo) { + return cb(null, true) + } + + const tasks = [ + (cb) => { + waterfall([ + (cb) => { + try { + cb(null, DAGNode.create(new UnixFs('directory').marshal())) + } catch (err) { + cb(err) + } + }, + (node, cb) => self.dag.put(node, { + version: 0, + format: multicodec.DAG_PB, + hashAlg: multicodec.SHA2_256 + }).then( + (cid) => cb(null, cid), + (error) => cb(error) + ), + (cid, cb) => self._ipns.initializeKeyspace(privateKey, cid.toBaseEncodedString(), cb) + ], cb) + } + ] + + if (typeof addDefaultAssets === 'function') { + // addDefaultAssets is undefined on browsers. + // See package.json browser config + tasks.push((cb) => addDefaultAssets(self, opts.log, cb)) + } + + self.log('adding assets') + parallel(tasks, (err) => { + if (err) { + cb(err) + } else { + cb(null, true) + } + }) + } + ], done) + }) +} + +}).call(this,require("buffer").Buffer) +},{"../ipns":539,"../ipns/routing/offline-datastore":545,"../runtime/config-nodejs.js":551,"./init-assets":146,"async/parallel":91,"async/waterfall":102,"buffer":181,"ipfs-unixfs":435,"ipld-dag-pb":589,"libp2p-keychain":926,"merge-options":1127,"multicodec":1151,"peer-id":1253,"promisify-es6":1263}],512:[function(require,module,exports){ +'use strict' + +module.exports = function isOnline (self) { + return () => { + return Boolean(self._bitswap && self.libp2p && self.libp2p.isStarted()) + } +} + +},{}],513:[function(require,module,exports){ +'use strict' + +// See https://github.com/ipfs/specs/tree/master/keystore + +const promisify = require('promisify-es6') + +module.exports = function key (self) { + return { + gen: promisify((name, opts, callback) => { + opts = opts || {} + self._keychain.createKey(name, opts.type, opts.size, callback) + }), + + info: promisify((name, callback) => { + self._keychain.findKeyByName(name, callback) + }), + + list: promisify((callback) => { + self._keychain.listKeys(callback) + }), + + rm: promisify((name, callback) => { + self._keychain.removeKey(name, callback) + }), + + rename: promisify((oldName, newName, callback) => { + self._keychain.renameKey(oldName, newName, (err, key) => { + if (err) return callback(err) + const result = { + was: oldName, + now: key.name, + id: key.id, + overwrite: false + } + callback(null, result) + }) + }), + + import: promisify((name, pem, password, callback) => { + self._keychain.importKey(name, pem, password, callback) + }), + + export: promisify((name, password, callback) => { + self._keychain.exportKey(name, password, callback) + }) + } +} + +},{"promisify-es6":1263}],514:[function(require,module,exports){ +'use strict' + +const get = require('dlv') +const mergeOptions = require('merge-options') +const errCode = require('err-code') +const ipnsUtils = require('../ipns/routing/utils') +const multiaddr = require('multiaddr') +const DelegatedPeerRouter = require('libp2p-delegated-peer-routing') +const DelegatedContentRouter = require('libp2p-delegated-content-routing') +const PubsubRouters = require('../runtime/libp2p-pubsub-routers-nodejs') + +module.exports = function libp2p (self, config) { + const options = self._options || {} + config = config || {} + + // Always create libp2p via a bundle function + const createBundle = typeof options.libp2p === 'function' + ? options.libp2p + : defaultBundle + + const { datastore } = self._repo + const peerInfo = self._peerInfo + const peerBook = self._peerInfoBook + const libp2p = createBundle({ options, config, datastore, peerInfo, peerBook }) + + libp2p.on('stop', () => { + // Clear our addresses so we can start clean + peerInfo.multiaddrs.clear() + }) + + libp2p.on('start', () => { + peerInfo.multiaddrs.forEach((ma) => { + self._print('Swarm listening on', ma.toString()) + }) + }) + + libp2p.on('peer:connect', peerInfo => peerBook.put(peerInfo)) + + return libp2p +} + +function defaultBundle ({ datastore, peerInfo, peerBook, options, config }) { + // Set up Delegate Routing based on the presence of Delegates in the config + let contentRouting + let peerRouting + const delegateHosts = get(options, 'config.Addresses.Delegates', + get(config, 'Addresses.Delegates', []) + ) + if (delegateHosts.length > 0) { + // Pick a random delegate host + const delegateString = delegateHosts[Math.floor(Math.random() * delegateHosts.length)] + const delegateAddr = multiaddr(delegateString).toOptions() + const delegatedApiOptions = { + host: delegateAddr.host, + // port is a string atm, so we need to convert for the check + protocol: parseInt(delegateAddr.port) === 443 ? 'https' : 'http', + port: delegateAddr.port + } + contentRouting = [new DelegatedContentRouter(peerInfo.id, delegatedApiOptions)] + peerRouting = [new DelegatedPeerRouter(delegatedApiOptions)] + } + + const getPubsubRouter = () => { + let router = get(config, 'Pubsub.Router', 'gossipsub') + + if (!router) { + router = 'gossipsub' + } + + if (!PubsubRouters[router]) { + throw errCode(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${router} router.`), 'ERR_NOT_SUPPORTED') + } + + return PubsubRouters[router] + } + + const libp2pDefaults = { + datastore, + peerInfo, + peerBook, + modules: { + contentRouting, + peerRouting, + pubsub: getPubsubRouter() + }, + config: { + peerDiscovery: { + mdns: { + enabled: get(options, 'config.Discovery.MDNS.Enabled', + get(config, 'Discovery.MDNS.Enabled', true)) + }, + webRTCStar: { + enabled: get(options, 'config.Discovery.webRTCStar.Enabled', + get(config, 'Discovery.webRTCStar.Enabled', true)) + }, + bootstrap: { + list: get(options, 'config.Bootstrap', + get(config, 'Bootstrap', [])) + } + }, + relay: { + enabled: get(options, 'relay.enabled', + get(config, 'relay.enabled', true)), + hop: { + enabled: get(options, 'relay.hop.enabled', + get(config, 'relay.hop.enabled', false)), + active: get(options, 'relay.hop.active', + get(config, 'relay.hop.active', false)) + } + }, + dht: { + kBucketSize: get(options, 'dht.kBucketSize', 20), + // enabled: !get(options, 'offline', false), // disable if offline, on by default + enabled: false, + randomWalk: { + enabled: false // disabled waiting for https://github.com/libp2p/js-libp2p-kad-dht/issues/86 + }, + validators: { + ipns: ipnsUtils.validator + }, + selectors: { + ipns: ipnsUtils.selector + } + }, + pubsub: { + enabled: get(config, 'Pubsub.Enabled', true) + } + }, + connectionManager: get(options, 'connectionManager', + { + maxPeers: get(config, 'Swarm.ConnMgr.HighWater'), + minPeers: get(config, 'Swarm.ConnMgr.LowWater') + }) + } + + const libp2pOptions = mergeOptions(libp2pDefaults, get(options, 'libp2p', {})) + // Required inline to reduce startup time + // Note: libp2p-nodejs gets replaced by libp2p-browser when webpacked/browserified + const Node = require('../runtime/libp2p-nodejs') + return new Node(libp2pOptions) +} + +},{"../ipns/routing/utils":547,"../runtime/libp2p-nodejs":555,"../runtime/libp2p-pubsub-routers-nodejs":556,"dlv":233,"err-code":268,"libp2p-delegated-content-routing":808,"libp2p-delegated-peer-routing":844,"merge-options":1127,"multiaddr":1140}],515:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const errcode = require('err-code') +const promisify = require('promisify-es6') + +const IpnsPubsubDatastore = require('../ipns/routing/pubsub-datastore') + +const log = debug('ipfs:name-pubsub') +log.error = debug('ipfs:name-pubsub:error') + +// Is pubsub enabled +const isNamePubsubEnabled = (node) => { + try { + return Boolean(getPubsubRouting(node)) + } catch (err) { + return false + } +} + +// Get pubsub from IPNS routing +const getPubsubRouting = (node) => { + if (!node._ipns || !node._options.EXPERIMENTAL.ipnsPubsub) { + throw errcode(new Error('IPNS pubsub subsystem is not enabled'), 'ERR_IPNS_PUBSUB_NOT_ENABLED') + } + + // Only one store and it is pubsub + if (IpnsPubsubDatastore.isIpnsPubsubDatastore(node._ipns.routing)) { + return node._ipns.routing + } + + // Find in tiered + const pubsub = (node._ipns.routing.stores || []).find(s => IpnsPubsubDatastore.isIpnsPubsubDatastore(s)) + + if (!pubsub) { + throw errcode(new Error('IPNS pubsub datastore not found'), 'ERR_PUBSUB_DATASTORE_NOT_FOUND') + } + + return pubsub +} + +module.exports = function namePubsub (self) { + return { + /** + * Query the state of IPNS pubsub. + * + * @returns {Promise|void} + */ + state: promisify((callback) => { + callback(null, { + enabled: isNamePubsubEnabled(self) + }) + }), + /** + * Cancel a name subscription. + * + * @param {String} name subscription name. + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + cancel: promisify((name, callback) => { + let pubsub + try { + pubsub = getPubsubRouting(self) + } catch (err) { + return callback(err) + } + + pubsub.cancel(name, callback) + }), + /** + * Show current name subscriptions. + * + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + subs: promisify((callback) => { + let pubsub + try { + pubsub = getPubsubRouting(self) + } catch (err) { + return callback(err) + } + + pubsub.getSubscriptions(callback) + }) + } +} + +},{"../ipns/routing/pubsub-datastore":546,"debug":456,"err-code":268,"promisify-es6":1263}],516:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const promisify = require('promisify-es6') +const waterfall = require('async/waterfall') +const parallel = require('async/parallel') +const human = require('human-to-milliseconds') +const crypto = require('libp2p-crypto') +const errcode = require('err-code') +const mergeOptions = require('merge-options') +const mh = require('multihashes') +const isDomain = require('is-domain-name') + +const log = debug('ipfs:name') +log.error = debug('ipfs:name:error') + +const namePubsub = require('./name-pubsub') +const utils = require('../utils') +const path = require('../ipns/path') + +const keyLookup = (ipfsNode, kname, callback) => { + if (kname === 'self') { + return callback(null, ipfsNode._peerInfo.id.privKey) + } + + const pass = ipfsNode._options.pass + + waterfall([ + (cb) => ipfsNode._keychain.exportKey(kname, pass, cb), + (pem, cb) => crypto.keys.import(pem, pass, cb) + ], (err, privateKey) => { + if (err) { + log.error(err) + return callback(errcode(err, 'ERR_CANNOT_GET_KEY')) + } + + return callback(null, privateKey) + }) +} + +const appendRemainder = (cb, remainder) => { + return (err, result) => { + if (err) { + return cb(err) + } + if (remainder.length) { + return cb(null, result + '/' + remainder.join('/')) + } + return cb(null, result) + } +} + +/** + * @typedef { import("../index") } IPFS + */ + +/** + * IPNS - Inter-Planetary Naming System + * + * @param {IPFS} self + * @returns {Object} + */ +module.exports = function name (self) { + return { + /** + * IPNS is a PKI namespace, where names are the hashes of public keys, and + * the private key enables publishing new (signed) values. In both publish + * and resolve, the default name used is the node's own PeerID, + * which is the hash of its public key. + * + * @param {String} value ipfs path of the object to be published. + * @param {Object} options ipfs publish options. + * @param {boolean} options.resolve resolve given path before publishing. + * @param {String} options.lifetime time duration that the record will be valid for. + This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are + "ns", "ms", "s", "m", "h". Default is 24h. + * @param {String} options.ttl time duration this record should be cached for (NOT IMPLEMENTED YET). + * This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are + "ns", "ms", "s", "m", "h" (caution: experimental). + * @param {String} options.key name of the key to be used, as listed by 'ipfs key list -l'. + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + publish: promisify((value, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + const resolve = !(options.resolve === false) + const lifetime = options.lifetime || '24h' + const key = options.key || 'self' + + if (!self.isOnline()) { + return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR')) + } + + // TODO: params related logic should be in the core implementation + + // Normalize path value + try { + value = utils.normalizePath(value) + } catch (err) { + log.error(err) + return callback(err) + } + + let pubLifetime + try { + pubLifetime = human(lifetime) + + // Calculate lifetime with nanoseconds precision + pubLifetime = pubLifetime.toFixed(6) + } catch (err) { + log.error(err) + return callback(err) + } + + // TODO: ttl human for cache + + parallel([ + (cb) => keyLookup(self, key, cb), + // verify if the path exists, if not, an error will stop the execution + (cb) => resolve.toString() === 'true' ? path.resolvePath(self, value, cb) : cb() + ], (err, results) => { + if (err) { + log.error(err) + return callback(err) + } + + // Start publishing process + self._ipns.publish(results[0], value, pubLifetime, callback) + }) + }), + + /** + * Given a key, query the DHT for its best value. + * + * @param {String} name ipns name to resolve. Defaults to your node's peerID. + * @param {Object} options ipfs resolve options. + * @param {boolean} options.nocache do not use cached entries. + * @param {boolean} options.recursive resolve until the result is not an IPNS name. + * @param {function(Error)} [callback] + * @returns {Promise|void} + */ + resolve: promisify((name, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = mergeOptions({ + nocache: false, + recursive: true + }, options) + + const offline = self._options.offline + + // TODO: params related logic should be in the core implementation + if (offline && options.nocache) { + return callback(errcode(new Error('cannot specify both offline and nocache'), 'ERR_NOCACHE_AND_OFFLINE')) + } + + // Set node id as name for being resolved, if it is not received + if (!name) { + name = self._peerInfo.id.toB58String() + } + + if (!name.startsWith('/ipns/')) { + name = `/ipns/${name}` + } + + const [namespace, hash, ...remainder] = name.slice(1).split('/') + try { + mh.fromB58String(hash) + } catch (err) { + // lets check if we have a domain ex. /ipns/ipfs.io and resolve with dns + if (isDomain(hash)) { + return self.dns(hash, options, appendRemainder(callback, remainder)) + } + + log.error(err) + return callback(errcode(new Error('Invalid IPNS name'), 'ERR_IPNS_INVALID_NAME')) + } + + // multihash is valid lets resolve with IPNS + // IPNS resolve needs a online daemon + if (!self.isOnline() && !offline) { + return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR')) + } + + self._ipns.resolve(`/${namespace}/${hash}`, options, appendRemainder(callback, remainder)) + }), + pubsub: namePubsub(self) + } +} + +},{"../ipns/path":540,"../utils":560,"./name-pubsub":515,"async/parallel":91,"async/waterfall":102,"debug":456,"err-code":268,"human-to-milliseconds":312,"is-domain-name":611,"libp2p-crypto":745,"merge-options":1127,"multihashes":1157,"promisify-es6":1263}],517:[function(require,module,exports){ +'use strict' + +function fail () { + throw new Error('Key management requires \'--pass ...\' option') +} + +class NoKeychain { + static get options () { fail() } + + static generateOptions () { fail() } + + createKey () { fail() } + + listKeys () { fail() } + + findKeyById () { fail() } + + findKeyByName () { fail() } + + renameKey () { fail() } + + removeKey () { fail() } + + exportKey () { fail() } + + importKey () { fail() } + + importPeer () { fail() } + + get cms () { fail() } +} + +module.exports = NoKeychain + +},{}],518:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const waterfall = require('async/waterfall') +const parallel = require('async/parallel') +const setImmediate = require('async/setImmediate') +const promisify = require('promisify-es6') +const dagPB = require('ipld-dag-pb') +const DAGNode = dagPB.DAGNode +const DAGLink = dagPB.DAGLink +const CID = require('cids') +const mh = require('multihashes') +const multicodec = require('multicodec') +const Unixfs = require('ipfs-unixfs') +const errCode = require('err-code') + +function normalizeMultihash (multihash, enc) { + if (typeof multihash === 'string') { + if (enc === 'base58' || !enc) { + return multihash + } + + return Buffer.from(multihash, enc) + } else if (Buffer.isBuffer(multihash)) { + return multihash + } else if (CID.isCID(multihash)) { + return multihash.buffer + } else { + throw new Error('unsupported multihash') + } +} + +function parseBuffer (buf, encoding, callback) { + switch (encoding) { + case 'json': + return parseJSONBuffer(buf, callback) + case 'protobuf': + return parseProtoBuffer(buf, callback) + default: + callback(new Error(`unkown encoding: ${encoding}`)) + } +} + +function parseJSONBuffer (buf, callback) { + let data + let links + + try { + const parsed = JSON.parse(buf.toString()) + + links = (parsed.Links || []).map((link) => { + return new DAGLink( + link.Name || link.name, + link.Size || link.size, + mh.fromB58String(link.Hash || link.hash || link.multihash) + ) + }) + data = Buffer.from(parsed.Data) + } catch (err) { + return callback(new Error('failed to parse JSON: ' + err)) + } + + try { + callback(null, DAGNode.create(data, links)) + } catch (err) { + callback(err) + } +} + +function parseProtoBuffer (buf, callback) { + let obj + try { + obj = dagPB.util.deserialize(buf) + } catch (err) { + return callback(err) + } + callback(null, obj) +} + +function findLinks (node, links = []) { + for (const key in node) { + const val = node[key] + + if (key === '/' && Object.keys(node).length === 1) { + try { + links.push(new DAGLink('', 0, new CID(val))) + continue + } catch (_) { + // not a CID + } + } + + if (CID.isCID(val)) { + links.push(new DAGLink('', 0, val)) + + continue + } + + if (Array.isArray(val)) { + findLinks(val, links) + } + + if (typeof val === 'object' && !(val instanceof String)) { + findLinks(val, links) + } + } + + return links +} + +module.exports = function object (self) { + function editAndSave (edit) { + return (multihash, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + waterfall([ + (cb) => { + self.object.get(multihash, options, cb) + }, + (node, cb) => { + // edit applies the edit func passed to + // editAndSave + edit(node, (err, node) => { + if (err) { + return cb(err) + } + + self._ipld.put(node, multicodec.DAG_PB, { + cidVersion: 0, + hashAlg: multicodec.SHA2_256 + }).then( + (cid) => { + if (options.preload !== false) { + self._preload(cid) + } + + cb(null, cid) + }, + (error) => cb(error) + ) + }) + } + ], callback) + } + } + + return { + new: promisify((template, options, callback) => { + if (typeof template === 'function') { + callback = template + template = undefined + options = {} + } + + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + let data + + if (template) { + if (template !== 'unixfs-dir') { + return setImmediate(() => callback(new Error('unknown template'))) + } + data = (new Unixfs('directory')).marshal() + } else { + data = Buffer.alloc(0) + } + + let node + + try { + node = DAGNode.create(data) + } catch (err) { + return callback(err) + } + + self._ipld.put(node, multicodec.DAG_PB, { + cidVersion: 0, + hashAlg: multicodec.SHA2_256 + }).then( + (cid) => { + if (options.preload !== false) { + self._preload(cid) + } + + callback(null, cid) + }, + (error) => callback(error) + ) + }), + put: promisify((obj, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + const encoding = options.enc + let node + + if (Buffer.isBuffer(obj)) { + if (encoding) { + parseBuffer(obj, encoding, (err, _node) => { + if (err) { + return callback(err) + } + node = _node + next() + }) + } else { + try { + node = DAGNode.create(obj) + } catch (err) { + return callback(err) + } + + next() + } + } else if (DAGNode.isDAGNode(obj)) { + // already a dag node + node = obj + next() + } else if (typeof obj === 'object') { + try { + node = DAGNode.create(obj.Data, obj.Links) + } catch (err) { + return callback(err) + } + + next() + } else { + return callback(new Error('obj not recognized')) + } + + function next () { + self._gcLock.readLock((cb) => { + self._ipld.put(node, multicodec.DAG_PB, { + cidVersion: 0, + hashAlg: multicodec.SHA2_256 + }).then( + (cid) => { + if (options.preload !== false) { + self._preload(cid) + } + + cb(null, cid) + }, + cb + ) + }, callback) + } + }), + + get: promisify((multihash, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + let mh, cid + + try { + mh = normalizeMultihash(multihash, options.enc) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_MULTIHASH'))) + } + + try { + cid = new CID(mh) + } catch (err) { + return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) + } + + if (options.cidVersion === 1) { + cid = cid.toV1() + } + + if (options.preload !== false) { + self._preload(cid) + } + + self._ipld.get(cid).then( + (node) => callback(null, node), + (error) => callback(error) + ) + }), + + data: promisify((multihash, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + self.object.get(multihash, options, (err, node) => { + if (err) { + return callback(err) + } + + callback(null, node.Data) + }) + }), + + links: promisify((multihash, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + const cid = new CID(multihash) + + self.dag.get(cid, options, (err, result) => { + if (err) { + return callback(err) + } + + if (cid.codec === 'raw') { + return callback(null, []) + } + + if (cid.codec === 'dag-pb') { + return callback(null, result.value.Links) + } + + if (cid.codec === 'dag-cbor') { + const links = findLinks(result) + + return callback(null, links) + } + + callback(new Error(`Cannot resolve links from codec ${cid.codec}`)) + }) + }), + + stat: promisify((multihash, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + waterfall([ + (cb) => self.object.get(multihash, options, cb), + (node, cb) => { + cb(null, { + node, + serialized: dagPB.util.serialize(node) + }) + }, + ({ node, serialized }, cb) => { + parallel({ + serialized: (next) => next(null, serialized), + cid: (next) => dagPB.util.cid(serialized, { + cidVersion: 0 + }).then((cid) => next(null, cid), next), + node: (next) => next(null, node) + }, cb) + } + ], (err, result) => { + if (err) { + return callback(err) + } + + const blockSize = result.serialized.length + const linkLength = result.node.Links.reduce((a, l) => a + l.Tsize, 0) + + callback(null, { + Hash: result.cid.toBaseEncodedString(), + NumLinks: result.node.Links.length, + BlockSize: blockSize, + LinksSize: blockSize - result.node.Data.length, + DataSize: result.node.Data.length, + CumulativeSize: blockSize + linkLength + }) + }) + }), + + patch: promisify({ + addLink (multihash, link, options, callback) { + editAndSave((node, cb) => { + DAGNode.addLink(node, link).then((node) => { + cb(null, node) + }, cb) + })(multihash, options, callback) + }, + + rmLink (multihash, linkRef, options, callback) { + editAndSave((node, cb) => { + linkRef = linkRef.Name || linkRef.name + + try { + node = DAGNode.rmLink(node, linkRef) + } catch (err) { + return cb(err) + } + + cb(null, node) + })(multihash, options, callback) + }, + + appendData (multihash, data, options, callback) { + editAndSave((node, cb) => { + const newData = Buffer.concat([node.Data, data]) + + try { + node = DAGNode.create(newData, node.Links) + } catch (err) { + return cb(err) + } + + cb(null, node) + })(multihash, options, callback) + }, + + setData (multihash, data, options, callback) { + editAndSave((node, cb) => { + try { + node = DAGNode.create(data, node.Links) + } catch (err) { + return cb(err) + } + + cb(null, node) + })(multihash, options, callback) + } + }) + } +} + +}).call(this,require("buffer").Buffer) +},{"async/parallel":91,"async/setImmediate":96,"async/waterfall":102,"buffer":181,"cids":185,"err-code":268,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157,"promisify-es6":1263}],519:[function(require,module,exports){ +/* eslint max-nested-callbacks: ["error", 8] */ +'use strict' + +const promisify = require('promisify-es6') +const CID = require('cids') +const map = require('async/map') +const mapSeries = require('async/mapSeries') +const waterfall = require('async/waterfall') +const setImmediate = require('async/setImmediate') +const errCode = require('err-code') +const multibase = require('multibase') + +const { resolvePath } = require('../utils') +const PinManager = require('./pin/pin-manager') +const PinTypes = PinManager.PinTypes + +function toB58String (hash) { + return new CID(hash).toBaseEncodedString() +} + +module.exports = (self) => { + const dag = self.dag + const pinManager = new PinManager(self._repo, dag) + + const pin = { + add: promisify((paths, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + const recursive = options.recursive == null ? true : options.recursive + + resolvePath(self.object, paths, (err, mhs) => { + if (err) { return callback(err) } + + const pinAdd = (pinComplete) => { + // verify that each hash can be pinned + map(mhs, (multihash, cb) => { + const cid = new CID(multihash) + const key = cid.toBaseEncodedString() + + if (recursive) { + if (pinManager.recursivePins.has(key)) { + // it's already pinned recursively + return cb(null, key) + } + + // entire graph of nested links should be pinned, + // so make sure we have all the objects + pinManager.fetchCompleteDag(key, { preload: options.preload }, (err) => { + if (err) { return cb(err) } + // found all objects, we can add the pin + return cb(null, key) + }) + } else { + if (pinManager.recursivePins.has(key)) { + // recursive supersedes direct, can't have both + return cb(new Error(`${key} already pinned recursively`)) + } + if (pinManager.directPins.has(key)) { + // already directly pinned + return cb(null, key) + } + + // make sure we have the object + dag.get(cid, { preload: options.preload }, (err) => { + if (err) { return cb(err) } + // found the object, we can add the pin + return cb(null, key) + }) + } + }, (err, results) => { + if (err) { return pinComplete(err) } + + // update the pin sets in memory + const pinset = recursive ? pinManager.recursivePins : pinManager.directPins + results.forEach(key => pinset.add(key)) + + // persist updated pin sets to datastore + pinManager.flushPins((err, root) => { + if (err) { return pinComplete(err) } + pinComplete(null, results.map(hash => ({ hash }))) + }) + }) + } + + // When adding a file, we take a lock that gets released after pinning + // is complete, so don't take a second lock here + const lock = options.lock !== false + if (lock) { + self._gcLock.readLock(pinAdd, callback) + } else { + pinAdd(callback) + } + }) + }), + + rm: promisify((paths, options, callback) => { + if (typeof options === 'function') { + callback = options + } + + options = options || {} + + const recursive = options.recursive == null ? true : options.recursive + + if (options.cidBase && !multibase.names.includes(options.cidBase)) { + return setImmediate(() => { + callback(errCode(new Error('invalid multibase'), 'ERR_INVALID_MULTIBASE')) + }) + } + + resolvePath(self.object, paths, (err, mhs) => { + if (err) { return callback(err) } + + self._gcLock.readLock((lockCb) => { + // verify that each hash can be unpinned + map(mhs, (multihash, cb) => { + pinManager.isPinnedWithType(multihash, PinTypes.all, (err, res) => { + if (err) { return cb(err) } + const { pinned, reason } = res + const key = toB58String(multihash) + if (!pinned) { + return cb(new Error(`${key} is not pinned`)) + } + + switch (reason) { + case (PinTypes.recursive): + if (recursive) { + return cb(null, key) + } else { + return cb(new Error(`${key} is pinned recursively`)) + } + case (PinTypes.direct): + return cb(null, key) + default: + return cb(new Error( + `${key} is pinned indirectly under ${reason}` + )) + } + }) + }, (err, results) => { + if (err) { return lockCb(err) } + + // update the pin sets in memory + results.forEach(key => { + if (recursive && pinManager.recursivePins.has(key)) { + pinManager.recursivePins.delete(key) + } else { + pinManager.directPins.delete(key) + } + }) + + // persist updated pin sets to datastore + pinManager.flushPins((err, root) => { + if (err) { return lockCb(err) } + self.log(`Removed pins: ${results}`) + lockCb(null, results.map(hash => ({ hash }))) + }) + }) + }, callback) + }) + }), + + ls: promisify((paths, options, callback) => { + let type = PinTypes.all + if (typeof paths === 'function') { + callback = paths + options = {} + paths = null + } + if (typeof options === 'function') { + callback = options + } + if (paths && paths.type) { + options = paths + paths = null + } + + options = options || {} + + if (options.type) { + type = options.type + if (typeof options.type === 'string') { + type = options.type.toLowerCase() + } + const err = PinManager.checkPinType(type) + if (err) { + return setImmediate(() => callback(err)) + } + } + + if (paths) { + // check the pinned state of specific hashes + waterfall([ + (cb) => resolvePath(self.object, paths, cb), + (hashes, cb) => mapSeries(hashes, (hash, done) => pinManager.isPinnedWithType(hash, type, done), cb), + (results, cb) => { + results = results + .filter(result => result.pinned) + .map(({ key, reason }) => { + switch (reason) { + case PinTypes.direct: + case PinTypes.recursive: + return { + hash: key, + type: reason + } + default: + return { + hash: key, + type: `${PinTypes.indirect} through ${reason}` + } + } + }) + + if (!results.length) { + return cb(new Error(`path '${paths}' is not pinned`)) + } + + cb(null, results) + } + ], (err, results) => err ? callback(err) : callback(null, results)) // we don't want results equal [undefined] when err is present + } else { + // show all pinned items of type + let pins = [] + + if (type === PinTypes.direct || type === PinTypes.all) { + pins = pins.concat( + Array.from(pinManager.directPins).map(hash => ({ + type: PinTypes.direct, + hash + })) + ) + } + + if (type === PinTypes.recursive || type === PinTypes.all) { + pins = pins.concat( + Array.from(pinManager.recursivePins).map(hash => ({ + type: PinTypes.recursive, + hash + })) + ) + } + + if (type === PinTypes.indirect || type === PinTypes.all) { + pinManager.getIndirectKeys(options, (err, indirects) => { + if (err) { return callback(err) } + pins = pins + // if something is pinned both directly and indirectly, + // report the indirect entry + .filter(({ hash }) => + !indirects.includes(hash) || + (indirects.includes(hash) && !pinManager.directPins.has(hash)) + ) + .concat(indirects.map(hash => ({ + type: PinTypes.indirect, + hash + }))) + return callback(null, pins) + }) + } else { + callback(null, pins) + } + } + }), + + _isPinnedWithType: promisify(pinManager.isPinnedWithType.bind(pinManager)), + _getInternalBlocks: promisify(pinManager.getInternalBlocks.bind(pinManager)), + _load: promisify(pinManager.load.bind(pinManager)) + } + + return pin +} + +},{"../utils":560,"./pin/pin-manager":522,"async/map":87,"async/mapSeries":89,"async/setImmediate":96,"async/waterfall":102,"cids":185,"err-code":268,"multibase":1148,"promisify-es6":1263}],520:[function(require,module,exports){ +'use strict' + +const pull = require('pull-stream/pull') +const pullThrough = require('pull-stream/throughs/through') +const pullAsyncMap = require('pull-stream/throughs/async-map') +const Mutex = require('../../../utils/mutex') +const log = require('debug')('ipfs:gc:lock') + +class GCLock { + constructor (repoOwner, options = {}) { + this.mutex = new Mutex(repoOwner, { ...options, log }) + } + + readLock (lockedFn, cb) { + return this.mutex.readLock(lockedFn, cb) + } + + writeLock (lockedFn, cb) { + return this.mutex.writeLock(lockedFn, cb) + } + + pullReadLock (lockedPullFn) { + return this.pullLock('readLock', lockedPullFn) + } + + pullWriteLock (lockedPullFn) { + return this.pullLock('writeLock', lockedPullFn) + } + + pullLock (type, lockedPullFn) { + const pullLocker = new PullLocker(this.mutex, type) + + return pull( + pullLocker.take(), + lockedPullFn(), + pullLocker.release() + ) + } +} + +class PullLocker { + constructor (mutex, type) { + this.mutex = mutex + this.type = type + + // The function to call to release the lock. It is set when the lock is taken + this.releaseLock = null + } + + take () { + return pullAsyncMap((i, cb) => { + // Check if the lock has already been acquired. + // Note: new items will only come through the pull stream once the first + // item has acquired a lock. + if (this.releaseLock) { + // The lock has been acquired so return immediately + return cb(null, i) + } + + // Request the lock + this.mutex[this.type]() + .then(release => { + // Save the release function to be called when the stream completes + this.releaseLock = release + + // The lock has been granted, so run the locked piece of code + cb(null, i) + }, cb) + }) + } + + // Releases the lock + release () { + return pullThrough(null, (err) => { + // When the stream completes, release the lock + this.releaseLock(err) + }) + } +} + +module.exports = GCLock + +},{"../../../utils/mutex":562,"debug":456,"pull-stream/pull":1312,"pull-stream/throughs/async-map":1329,"pull-stream/throughs/through":1337}],521:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const promisify = require('promisify-es6') +const CID = require('cids') +const base32 = require('base32.js') +const parallel = require('async/parallel') +const mapLimit = require('async/mapLimit') +const expErr = require('explain-error') +const { cidToString } = require('../../../utils/cid') +const log = require('debug')('ipfs:gc') +// TODO: Use exported key from root when upgraded to ipfs-mfs@>=13 +// https://github.com/ipfs/js-ipfs-mfs/pull/58 +const { MFS_ROOT_KEY } = require('ipfs-mfs/src/core/utils/constants') + +// Limit on the number of parallel block remove operations +const BLOCK_RM_CONCURRENCY = 256 + +// Perform mark and sweep garbage collection +module.exports = function gc (self) { + return promisify((callback) => { + const start = Date.now() + log('Creating set of marked blocks') + + self._gcLock.writeLock((lockCb) => { + parallel([ + // Get all blocks keys from the blockstore + (cb) => self._repo.blocks.query({ keysOnly: true }, cb), + // Mark all blocks that are being used + (cb) => createMarkedSet(self, cb) + ], (err, [blockKeys, markedSet]) => { + if (err) { + log('GC failed to fetch all block keys and created marked set', err) + return lockCb(err) + } + + // Delete blocks that are not being used + deleteUnmarkedBlocks(self, markedSet, blockKeys, (err, res) => { + log(`Complete (${Date.now() - start}ms)`) + + if (err) { + log('GC failed to delete unmarked blocks', err) + return lockCb(err) + } + + lockCb(null, res) + }) + }) + }, callback) + }) +} + +// Get Set of CIDs of blocks to keep +function createMarkedSet (ipfs, callback) { + parallel([ + // All pins, direct and indirect + (cb) => ipfs.pin.ls((err, pins) => { + if (err) { + return cb(expErr(err, 'Could not list pinned blocks')) + } + log(`Found ${pins.length} pinned blocks`) + const cids = pins.map(p => new CID(p.hash)) + // log(' ' + cids.join('\n ')) + cb(null, cids) + }), + + // Blocks used internally by the pinner + (cb) => ipfs.pin._getInternalBlocks((err, cids) => { + if (err) { + return cb(expErr(err, 'Could not list pinner internal blocks')) + } + log(`Found ${cids.length} pinner internal blocks`) + // log(' ' + cids.join('\n ')) + cb(null, cids) + }), + + // The MFS root and all its descendants + (cb) => ipfs._repo.root.get(MFS_ROOT_KEY, (err, mh) => { + if (err) { + if (err.code === 'ERR_NOT_FOUND') { + log('No blocks in MFS') + return cb(null, []) + } + return cb(expErr(err, 'Could not get MFS root from datastore')) + } + + getDescendants(ipfs, new CID(mh), cb) + }) + ], (err, res) => { + if (err) { + return callback(err) + } + + const cids = [].concat(...res).map(cid => cidToString(cid, { base: 'base32' })) + return callback(null, new Set(cids)) + }) +} + +// Recursively get descendants of the given CID +function getDescendants (ipfs, cid, callback) { + ipfs.refs(cid, { recursive: true }, (err, refs) => { + if (err) { + return callback(expErr(err, 'Could not get MFS root descendants from store')) + } + const cids = [cid, ...refs.map(r => new CID(r.ref))] + log(`Found ${cids.length} MFS blocks`) + // log(' ' + cids.join('\n ')) + callback(null, cids) + }) +} + +// Delete all blocks that are not marked as in use +function deleteUnmarkedBlocks (ipfs, markedSet, blockKeys, callback) { + // Iterate through all blocks and find those that are not in the marked set + // The blockKeys variable has the form [ { key: Key() }, { key: Key() }, ... ] + const unreferenced = [] + const res = [] + let errCount = 0 + for (const { key: k } of blockKeys) { + try { + const cid = dsKeyToCid(k) + const b32 = cid.toV1().toString('base32') + if (!markedSet.has(b32)) { + unreferenced.push(cid) + } + } catch (err) { + errCount++ + const msg = `Could not convert block with key '${k}' to CID` + log(msg, err) + res.push({ err: new Error(msg + `: ${err.message}`) }) + } + } + + const msg = `Marked set has ${markedSet.size} unique blocks. Blockstore has ${blockKeys.length} blocks. ` + + `Deleting ${unreferenced.length} blocks.` + (errCount ? ` (${errCount} errors)` : '') + log(msg) + // log(' ' + unreferenced.join('\n ')) + + mapLimit(unreferenced, BLOCK_RM_CONCURRENCY, (cid, cb) => { + // Delete blocks from blockstore + ipfs._repo.blocks.delete(cid, (err) => { + const res = { + cid, + err: err && new Error(`Could not delete block with CID ${cid}: ${err.message}`) + } + cb(null, res) + }) + }, (_, delRes) => { + callback(null, res.concat(delRes)) + }) +} + +// TODO: Use exported utility when upgrade to ipfs-repo@>=0.27.1 +// https://github.com/ipfs/js-ipfs-repo/pull/206 +function dsKeyToCid (key) { + // Block key is of the form / + const decoder = new base32.Decoder() + const buff = decoder.write(key.toString().slice(1)).finalize() + return new CID(Buffer.from(buff)) +} + +}).call(this,require("buffer").Buffer) +},{"../../../utils/cid":561,"async/mapLimit":88,"async/parallel":91,"base32.js":107,"buffer":181,"cids":185,"debug":456,"explain-error":274,"ipfs-mfs/src/core/utils/constants":369,"promisify-es6":1263}],522:[function(require,module,exports){ +(function (Buffer){ +/* eslint max-nested-callbacks: ["error", 8] */ +'use strict' + +const { DAGNode, DAGLink } = require('ipld-dag-pb') +const CID = require('cids') +const series = require('async/series') +const parallel = require('async/parallel') +const eachLimit = require('async/eachLimit') +const waterfall = require('async/waterfall') +const detectLimit = require('async/detectLimit') +const queue = require('async/queue') +const { Key } = require('interface-datastore') +const errCode = require('err-code') +const multicodec = require('multicodec') +const debug = require('debug') +const { cidToString } = require('../../../utils/cid') + +const createPinSet = require('./pin-set') + +// arbitrary limit to the number of concurrent dag operations +const concurrencyLimit = 300 +const PIN_DS_KEY = new Key('/local/pins') + +function invalidPinTypeErr (type) { + const errMsg = `Invalid type '${type}', must be one of {direct, indirect, recursive, all}` + return errCode(new Error(errMsg), 'ERR_INVALID_PIN_TYPE') +} + +const PinTypes = { + direct: 'direct', + recursive: 'recursive', + indirect: 'indirect', + all: 'all' +} + +class PinManager { + constructor (repo, dag) { + this.repo = repo + this.dag = dag + this.log = debug('ipfs:pin') + this.pinset = createPinSet(dag) + this.directPins = new Set() + this.recursivePins = new Set() + } + + _walkDag ({ cid, preload = false, onCid = () => {} }, cb) { + const q = queue(({ cid }, done) => { + this.dag.get(cid, { preload }, (err, result) => { + if (err) { + return done(err) + } + + onCid(cid) + + if (result.value.Links) { + q.push(result.value.Links.map(link => ({ + cid: link.Hash + }))) + } + + done() + }) + }, concurrencyLimit) + q.drain = () => { + cb() + } + q.error = (err) => { + q.kill() + cb(err) + } + q.push({ cid }) + } + + directKeys () { + return Array.from(this.directPins, key => new CID(key).buffer) + } + + recursiveKeys () { + return Array.from(this.recursivePins, key => new CID(key).buffer) + } + + getIndirectKeys ({ preload }, callback) { + const indirectKeys = new Set() + eachLimit(this.recursiveKeys(), concurrencyLimit, (multihash, cb) => { + this._walkDag({ + cid: new CID(multihash), + preload: preload || false, + onCid: (cid) => { + cid = cid.toString() + + // recursive pins pre-empt indirect pins + if (!this.recursivePins.has(cid)) { + indirectKeys.add(cid) + } + } + }, cb) + }, (err) => { + if (err) { return callback(err) } + callback(null, Array.from(indirectKeys)) + }) + } + + // Encode and write pin key sets to the datastore: + // a DAGLink for each of the recursive and direct pinsets + // a DAGNode holding those as DAGLinks, a kind of root pin + flushPins (callback) { + let dLink, rLink, root + series([ + // create a DAGLink to the node with direct pins + cb => waterfall([ + cb => this.pinset.storeSet(this.directKeys(), cb), + ({ node, cid }, cb) => { + try { + cb(null, new DAGLink(PinTypes.direct, node.size, cid)) + } catch (err) { + cb(err) + } + }, + (link, cb) => { dLink = link; cb(null) } + ], cb), + + // create a DAGLink to the node with recursive pins + cb => waterfall([ + cb => this.pinset.storeSet(this.recursiveKeys(), cb), + ({ node, cid }, cb) => { + try { + cb(null, new DAGLink(PinTypes.recursive, node.size, cid)) + } catch (err) { + cb(err) + } + }, + (link, cb) => { rLink = link; cb(null) } + ], cb), + + // the pin-set nodes link to a special 'empty' node, so make sure it exists + cb => { + let empty + + try { + empty = DAGNode.create(Buffer.alloc(0)) + } catch (err) { + return cb(err) + } + + this.dag.put(empty, { + version: 0, + format: multicodec.DAG_PB, + hashAlg: multicodec.SHA2_256, + preload: false + }, cb) + }, + + // create a root node with DAGLinks to the direct and recursive DAGs + cb => { + let node + + try { + node = DAGNode.create(Buffer.alloc(0), [dLink, rLink]) + } catch (err) { + return cb(err) + } + + root = node + this.dag.put(root, { + version: 0, + format: multicodec.DAG_PB, + hashAlg: multicodec.SHA2_256, + preload: false + }, (err, cid) => { + if (!err) { + root.multihash = cid.buffer + } + cb(err) + }) + }, + + // save root to datastore under a consistent key + cb => this.repo.datastore.put(PIN_DS_KEY, root.multihash, cb) + ], (err, res) => { + if (err) { return callback(err) } + this.log(`Flushed pins with root: ${root}`) + return callback(null, root) + }) + } + + load (callback) { + waterfall([ + (cb) => this.repo.datastore.has(PIN_DS_KEY, cb), + (has, cb) => has ? cb() : cb(new Error('No pins to load')), + (cb) => this.repo.datastore.get(PIN_DS_KEY, cb), + (mh, cb) => { + this.dag.get(new CID(mh), '', { preload: false }, cb) + } + ], (err, pinRoot) => { + if (err) { + if (err.message === 'No pins to load') { + this.log('No pins to load') + return callback() + } else { + return callback(err) + } + } + + parallel([ + cb => this.pinset.loadSet(pinRoot.value, PinTypes.recursive, cb), + cb => this.pinset.loadSet(pinRoot.value, PinTypes.direct, cb) + ], (err, keys) => { + if (err) { return callback(err) } + const [rKeys, dKeys] = keys + + this.directPins = new Set(dKeys.map(k => cidToString(k))) + this.recursivePins = new Set(rKeys.map(k => cidToString(k))) + + this.log('Loaded pins from the datastore') + return callback(null) + }) + }) + } + + isPinnedWithType (multihash, type, callback) { + const key = cidToString(multihash) + const { recursive, direct, all } = PinTypes + + // recursive + if ((type === recursive || type === all) && this.recursivePins.has(key)) { + return callback(null, { + key, + pinned: true, + reason: recursive + }) + } + + if (type === recursive) { + return callback(null, { + key, + pinned: false + }) + } + + // direct + if ((type === direct || type === all) && this.directPins.has(key)) { + return callback(null, { + key, + pinned: true, + reason: direct + }) + } + + if (type === direct) { + return callback(null, { + key, + pinned: false + }) + } + + // indirect (default) + // check each recursive key to see if multihash is under it + // arbitrary limit, enables handling 1000s of pins. + detectLimit(this.recursiveKeys().map(key => new CID(key)), concurrencyLimit, (cid, cb) => { + waterfall([ + (done) => this.dag.get(cid, '', { preload: false }, done), + (result, done) => done(null, result.value), + (node, done) => this.pinset.hasDescendant(node, key, done) + ], cb) + }, (err, cid) => callback(err, { + key, + pinned: Boolean(cid), + reason: cid + })) + } + + // Gets CIDs of blocks used internally by the pinner + getInternalBlocks (callback) { + this.repo.datastore.get(PIN_DS_KEY, (err, mh) => { + if (err) { + if (err.code === 'ERR_NOT_FOUND') { + this.log('No pinned blocks') + return callback(null, []) + } + return callback(new Error(`Could not get pin sets root from datastore: ${err.message}`)) + } + + const cid = new CID(mh) + this.dag.get(cid, '', { preload: false }, (err, obj) => { + if (err) { + return callback(new Error(`Could not get pin sets from store: ${err.message}`)) + } + + // The pinner stores an object that has two links to pin sets: + // 1. The directly pinned CIDs + // 2. The recursively pinned CIDs + // If large enough, these pin sets may have links to buckets to hold + // the pins + this.pinset.getInternalCids(obj.value, (err, cids) => { + if (err) { + return callback(new Error(`Could not get pinner internal cids: ${err.message}`)) + } + + callback(null, cids.concat(cid)) + }) + }) + }) + } + + fetchCompleteDag (cid, options, callback) { + this._walkDag({ + cid, + preload: options.preload + }, callback) + } + + // Returns an error if the pin type is invalid + static checkPinType (type) { + if (typeof type !== 'string' || !Object.keys(PinTypes).includes(type)) { + return invalidPinTypeErr(type) + } + } +} + +PinManager.PinTypes = PinTypes + +module.exports = PinManager + +}).call(this,require("buffer").Buffer) +},{"../../../utils/cid":561,"./pin-set":523,"async/detectLimit":55,"async/eachLimit":57,"async/parallel":91,"async/queue":92,"async/series":95,"async/waterfall":102,"buffer":181,"cids":185,"debug":456,"err-code":268,"interface-datastore":322,"ipld-dag-pb":589,"multicodec":1151}],523:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const multihashes = require('multihashes') +const CID = require('cids') +const protobuf = require('protons') +const fnv1a = require('fnv1a') +const varint = require('varint') +const { DAGNode, DAGLink } = require('ipld-dag-pb') +const multicodec = require('multicodec') +const someSeries = require('async/someSeries') +const eachSeries = require('async/eachSeries') +const eachOfSeries = require('async/eachOfSeries') + +const pbSchema = require('./pin.proto') + +const emptyKeyHash = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n' +const emptyKey = multihashes.fromB58String(emptyKeyHash) +const defaultFanout = 256 +const maxItems = 8192 +const pb = protobuf(pbSchema) + +function toB58String (hash) { + return new CID(hash).toBaseEncodedString() +} + +function readHeader (rootNode) { + // rootNode.data should be a buffer of the format: + // < varint(headerLength) | header | itemData... > + const rootData = rootNode.Data + const hdrLength = varint.decode(rootData) + const vBytes = varint.decode.bytes + if (vBytes <= 0) { + throw new Error('Invalid Set header length') + } + if (vBytes + hdrLength > rootData.length) { + throw new Error('Impossibly large set header length') + } + const hdrSlice = rootData.slice(vBytes, hdrLength + vBytes) + const header = pb.Set.decode(hdrSlice) + if (header.version !== 1) { + throw new Error(`Unsupported Set version: ${header.version}`) + } + if (header.fanout > rootNode.Links.length) { + throw new Error('Impossibly large fanout') + } + return { + header: header, + data: rootData.slice(hdrLength + vBytes) + } +} + +function hash (seed, key) { + const buf = Buffer.alloc(4) + buf.writeUInt32LE(seed, 0) + const data = Buffer.concat([ + buf, Buffer.from(toB58String(key)) + ]) + return fnv1a(data.toString('binary')) +} + +exports = module.exports = function (dag) { + const pinSet = { + // should this be part of `object` API? + hasDescendant: (root, childhash, callback) => { + const seen = {} + + if (CID.isCID(childhash) || Buffer.isBuffer(childhash)) { + childhash = toB58String(childhash) + } + + return searchChildren(root, callback) + + function searchChildren (root, cb) { + someSeries(root.Links, (link, done) => { + const cid = link.Hash + const bs58Link = toB58String(cid) + + if (bs58Link === childhash) { + return done(null, true) + } + + if (bs58Link in seen) { + return done(null, false) + } + + seen[bs58Link] = true + + dag.get(cid, '', { preload: false }, (err, res) => { + if (err) { + return done(err) + } + + searchChildren(res.value, done) + }) + }, cb) + } + }, + + storeSet: (keys, callback) => { + const pins = keys.map(key => { + if (typeof key === 'string' || Buffer.isBuffer(key)) { + key = new CID(key) + } + + return { + key: key, + data: null + } + }) + + pinSet.storeItems(pins, (err, rootNode) => { + if (err) { return callback(err) } + + dag.put(rootNode, { + version: 0, + format: multicodec.DAG_PB, + hashAlg: multicodec.SHA2_256, + preload: false + }, (err, cid) => { + if (err) { return callback(err, cid) } + callback(null, { node: rootNode, cid }) + }) + }) + }, + + storeItems: (items, callback) => { + return storePins(items, 0, callback) + + function storePins (pins, depth, storePinsCb) { + const pbHeader = pb.Set.encode({ + version: 1, + fanout: defaultFanout, + seed: depth + }) + const headerBuf = Buffer.concat([ + Buffer.from(varint.encode(pbHeader.length)), pbHeader + ]) + const fanoutLinks = [] + for (let i = 0; i < defaultFanout; i++) { + fanoutLinks.push(new DAGLink('', 1, emptyKey)) + } + + if (pins.length <= maxItems) { + const nodes = pins + .map(item => { + return ({ + link: new DAGLink('', 1, item.key), + data: item.data || Buffer.alloc(0) + }) + }) + // sorting makes any ordering of `pins` produce the same DAGNode + .sort((a, b) => Buffer.compare(a.link.Hash.buffer, b.link.Hash.buffer)) + + const rootLinks = fanoutLinks.concat(nodes.map(item => item.link)) + const rootData = Buffer.concat( + [headerBuf].concat(nodes.map(item => item.data)) + ) + + let rootNode + + try { + rootNode = DAGNode.create(rootData, rootLinks) + } catch (err) { + return storePinsCb(err) + } + + return storePinsCb(null, rootNode) + } else { + // If the array of pins is > maxItems, we: + // - distribute the pins among `defaultFanout` bins + // - create a DAGNode for each bin + // - add each pin as a DAGLink to that bin + // - create a root DAGNode + // - add each bin as a DAGLink + // - send that root DAGNode via callback + // (using go-ipfs' "wasteful but simple" approach for consistency) + // https://github.com/ipfs/go-ipfs/blob/master/pin/set.go#L57 + + const bins = pins.reduce((bins, pin) => { + const n = hash(depth, pin.key) % defaultFanout + bins[n] = n in bins ? bins[n].concat([pin]) : [pin] + return bins + }, {}) + + eachOfSeries(bins, (bin, idx, eachCb) => { + storePins( + bin, + depth + 1, + (err, child) => storeChild(err, child, idx, eachCb) + ) + }, err => { + if (err) { return storePinsCb(err) } + + let rootNode + + try { + rootNode = DAGNode.create(headerBuf, fanoutLinks) + } catch (err) { + return storePinsCb(err) + } + + return storePinsCb(null, rootNode) + }) + } + + function storeChild (err, child, binIdx, cb) { + if (err) { return cb(err) } + + const opts = { + version: 0, + format: multicodec.DAG_PB, + hashAlg: multicodec.SHA2_256, + preload: false + } + + dag.put(child, opts, (err, cid) => { + if (err) { return cb(err) } + fanoutLinks[binIdx] = new DAGLink('', child.size, cid) + cb(null) + }) + } + } + }, + + loadSet: (rootNode, name, callback) => { + const link = rootNode.Links.find(l => l.Name === name) + if (!link) { + return callback(new Error('No link found with name ' + name)) + } + + dag.get(link.Hash, '', { preload: false }, (err, res) => { + if (err) { return callback(err) } + const keys = [] + const stepPin = link => keys.push(link.Hash.buffer) + pinSet.walkItems(res.value, { stepPin }, err => { + if (err) { return callback(err) } + return callback(null, keys) + }) + }) + }, + + walkItems: (node, { stepPin = () => {}, stepBin = () => {} }, callback) => { + let pbh + try { + pbh = readHeader(node) + } catch (err) { + return callback(err) + } + + eachOfSeries(node.Links, (link, idx, eachCb) => { + if (idx < pbh.header.fanout) { + // the first pbh.header.fanout links are fanout bins + // if a fanout bin is not 'empty', dig into and walk its DAGLinks + const linkHash = link.Hash.buffer + + if (!emptyKey.equals(linkHash)) { + stepBin(link, idx, pbh.data) + + // walk the links of this fanout bin + return dag.get(linkHash, '', { preload: false }, (err, res) => { + if (err) { return eachCb(err) } + pinSet.walkItems(res.value, { stepPin, stepBin }, eachCb) + }) + } + } else { + // otherwise, the link is a pin + stepPin(link, idx, pbh.data) + } + + eachCb(null) + }, callback) + }, + + getInternalCids: (rootNode, callback) => { + // "Empty block" used by the pinner + const cids = [new CID(emptyKey)] + + const stepBin = link => cids.push(link.Hash) + eachSeries(rootNode.Links, (topLevelLink, cb) => { + cids.push(topLevelLink.Hash) + + dag.get(topLevelLink.Hash, '', { preload: false }, (err, res) => { + if (err) { return cb(err) } + + pinSet.walkItems(res.value, { stepBin }, cb) + }) + }, (err) => callback(err, cids)) + } + } + return pinSet +} + +}).call(this,require("buffer").Buffer) +},{"./pin.proto":524,"async/eachOfSeries":60,"async/eachSeries":61,"async/someSeries":99,"buffer":181,"cids":185,"fnv1a":277,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157,"protons":1274,"varint":1521}],524:[function(require,module,exports){ +'use strict' + +/** + * Protobuf interface + * from go-ipfs/pin/internal/pb/header.proto + */ +module.exports = ` + syntax = "proto2"; + + package ipfs.pin; + + option go_package = "pb"; + + message Set { + optional uint32 version = 1; + optional uint32 fanout = 2; + optional fixed32 seed = 3; + } +` + +},{}],525:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR +const PeerId = require('peer-id') +const pull = require('pull-stream') +const Pushable = require('pull-pushable') + +const log = debug('ipfs:pingPullStream') +log.error = debug('ipfs:pingPullStream:error') + +module.exports = function pingPullStream (self) { + return (peerId, opts) => { + if (!self.isOnline()) { + return pull.error(new Error(OFFLINE_ERROR)) + } + + opts = Object.assign({ count: 10 }, opts) + + const source = Pushable() + + getPeer(self.libp2p, source, peerId, (err, peer) => { + if (err) { + log.error(err) + source.end(err) + return + } + + runPing(self.libp2p, source, opts.count, peer, (err) => { + if (err) { + log.error(err) + source.push(getPacket({ success: false, text: err.toString() })) + source.end() + } + }) + }) + + return source + } +} + +function getPacket (msg) { + // Default msg + const basePacket = { success: true, time: 0, text: '' } + return Object.assign(basePacket, msg) +} + +function getPeer (libp2pNode, statusStream, peerIdStr, cb) { + let peerId + + try { + peerId = PeerId.createFromB58String(peerIdStr) + } catch (err) { + return cb(err) + } + + let peerInfo + + try { + peerInfo = libp2pNode.peerBook.get(peerId) + } catch (err) { + log('Peer not found in peer book, trying peer routing') + + // Share lookup status just as in the go implemmentation + statusStream.push(getPacket({ text: `Looking up peer ${peerIdStr}` })) + return libp2pNode.peerRouting.findPeer(peerId, cb) + } + + cb(null, peerInfo) +} + +function runPing (libp2pNode, statusStream, count, peer, cb) { + libp2pNode.ping(peer, (err, p) => { + if (err) { return cb(err) } + + let packetCount = 0 + let totalTime = 0 + statusStream.push(getPacket({ text: `PING ${peer.id.toB58String()}` })) + + p.on('ping', (time) => { + statusStream.push(getPacket({ time })) + totalTime += time + packetCount++ + if (packetCount >= count) { + const average = totalTime / count + p.stop() + statusStream.push(getPacket({ text: `Average latency: ${average}ms` })) + statusStream.end() + } + }) + + p.on('error', (err) => { + log.error(err) + p.stop() + cb(err) + }) + + p.start() + }) +} + +},{"../utils":560,"debug":456,"peer-id":1253,"pull-pushable":1306,"pull-stream":1311}],526:[function(require,module,exports){ +'use strict' + +const toStream = require('pull-stream-to-stream') + +module.exports = function pingReadableStream (self) { + return (peerId, opts) => toStream.source(self.pingPullStream(peerId, opts)) +} + +},{"pull-stream-to-stream":1310}],527:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const pull = require('pull-stream/pull') + +module.exports = function ping (self) { + return promisify((peerId, opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + pull( + self.pingPullStream(peerId, opts), + pull.collect(callback) + ) + }) +} + +},{"promisify-es6":1263,"pull-stream/pull":1312}],528:[function(require,module,exports){ +'use strict' + +const peerId = require('peer-id') +const PeerInfo = require('peer-info') +const multiaddr = require('multiaddr') +const waterfall = require('async/waterfall') +const Keychain = require('libp2p-keychain') +const mergeOptions = require('merge-options') +const NoKeychain = require('./no-keychain') +/* + * Load stuff from Repo into memory + */ +module.exports = function preStart (self) { + return (callback) => { + self.log('pre-start') + + const pass = self._options.pass + waterfall([ + (cb) => self._repo.config.get(cb), + (config, cb) => { + if (!self._options.config) { + return cb(null, config) + } + + config = mergeOptions(config, self._options.config) + + self.config.replace(config, (err) => { + if (err) { + return cb(err) + } + + cb(null, config) + }) + }, + (config, cb) => { + // Create keychain configuration, if needed. + if (config.Keychain) { + return cb(null, config) + } + config.Keychain = Keychain.generateOptions() + self.config.set('Keychain', config.Keychain, (err) => { + self.log('using default keychain options') + cb(err, config) + }) + }, + (config, cb) => { + // Construct the keychain + if (self._keychain) { + // most likely an init or upgrade has happened + } else if (pass) { + const keychainOptions = Object.assign({ passPhrase: pass }, config.Keychain) + self._keychain = new Keychain(self._repo.keys, keychainOptions) + self.log('keychain constructed') + } else { + self._keychain = new NoKeychain() + self.log('no keychain, use --pass') + } + cb(null, config) + }, + (config, cb) => { + const privKey = config.Identity.PrivKey + + peerId.createFromPrivKey(privKey, (err, id) => { + cb(err, config, id) + }) + }, + (config, id, cb) => { + // Import the private key as 'self', if needed. + if (!pass) { + return cb(null, config, id) + } + self._keychain.findKeyByName('self', (err) => { + if (err) { + self.log('Creating "self" key') + return self._keychain.importPeer('self', id, (err) => cb(err, config, id)) + } + cb(null, config, id) + }) + }, + (config, id, cb) => { + self.log('peer created') + self._peerInfo = new PeerInfo(id) + + if (config.Addresses && config.Addresses.Swarm) { + config.Addresses.Swarm.forEach((addr) => { + let ma = multiaddr(addr) + + if (ma.getPeerId()) { + ma = ma.encapsulate('/ipfs/' + self._peerInfo.id.toB58String()) + } + + self._peerInfo.multiaddrs.add(ma) + }) + } + + cb() + }, + (cb) => self.pin._load(cb) + ], callback) + } +} + +},{"./no-keychain":517,"async/waterfall":102,"libp2p-keychain":926,"merge-options":1127,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],529:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const setImmediate = require('async/setImmediate') +const errCode = require('err-code') + +const errPubsubDisabled = () => { + return errCode(new Error('pubsub experiment is not enabled'), 'ERR_PUBSUB_DISABLED') +} + +module.exports = function pubsub (self) { + return { + subscribe: (topic, handler, options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + if (!self.libp2p.pubsub) { + return callback + ? setImmediate(() => callback(errPubsubDisabled())) + : Promise.reject(errPubsubDisabled()) + } + + if (!callback) { + return self.libp2p.pubsub.subscribe(topic, handler, options) + } + + self.libp2p.pubsub.subscribe(topic, handler, options, callback) + }, + + unsubscribe: (topic, handler, callback) => { + if (!self.libp2p.pubsub) { + return callback + ? setImmediate(() => callback(errPubsubDisabled())) + : Promise.reject(errPubsubDisabled()) + } + + if (!callback) { + return self.libp2p.pubsub.unsubscribe(topic, handler) + } + + self.libp2p.pubsub.unsubscribe(topic, handler, callback) + }, + + publish: promisify((topic, data, callback) => { + if (!self.libp2p.pubsub) { + return setImmediate(() => callback(errPubsubDisabled())) + } + self.libp2p.pubsub.publish(topic, data, callback) + }), + + ls: promisify((callback) => { + if (!self.libp2p.pubsub) { + return setImmediate(() => callback(errPubsubDisabled())) + } + self.libp2p.pubsub.ls(callback) + }), + + peers: promisify((topic, callback) => { + if (!self.libp2p.pubsub) { + return setImmediate(() => callback(errPubsubDisabled())) + } + self.libp2p.pubsub.peers(topic, callback) + }), + + setMaxListeners (n) { + if (!self.libp2p.pubsub) { + throw errPubsubDisabled() + } + self.libp2p.pubsub.setMaxListeners(n) + } + } +} + +},{"async/setImmediate":96,"err-code":268,"promisify-es6":1263}],530:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const repoVersion = require('ipfs-repo').repoVersion + +module.exports = function repo (self) { + return { + init: (bits, empty, callback) => { + // 1. check if repo already exists + }, + + /** + * If the repo has been initialized, report the current version. + * Otherwise report the version that would be initialized. + * + * @param {function(Error, Number)} [callback] + * @returns {undefined} + */ + version: promisify((callback) => { + self._repo._isInitialized(err => { + if (err) { + // TODO: (dryajov) This is really hacky, there must be a better way + const match = [ + /Key not found in database \[\/version\]/, + /ENOENT/, + /repo is not initialized yet/ + ].some((m) => { + return m.test(err.message) + }) + if (match) { + // this repo has not been initialized + return callback(null, repoVersion) + } + return callback(err) + } + + self._repo.version.get(callback) + }) + }), + + gc: require('./pin/gc')(self), + + stat: promisify((options, callback) => { + if (typeof options === 'function') { + callback = options + options = {} + } + + self._repo.stat(options, (err, stats) => { + if (err) return callback(err) + + callback(null, { + numObjects: stats.numObjects, + repoSize: stats.repoSize, + repoPath: stats.repoPath, + version: stats.version.toString(), + storageMax: stats.storageMax + }) + }) + }), + + path: () => self._repo.path + } +} + +},{"./pin/gc":521,"ipfs-repo":395,"promisify-es6":1263}],531:[function(require,module,exports){ +'use strict' + +const isIpfs = require('is-ipfs') +const CID = require('cids') +const nodeify = require('promise-nodeify') +const { cidToString } = require('../../utils/cid') + +/** + * @typedef { import("../index") } IPFS + */ + +/** + * @typedef {Object} ResolveOptions + * @prop {string} cidBase - Multibase codec name the CID in the resolved path will be encoded with + * @prop {boolean} [recursive=true] - Resolve until the result is an IPFS name + * + */ + +/** @typedef {(err: Error, path: string) => void} ResolveCallback */ + +/** + * @callback ResolveWrapper - This wrapper adds support for callbacks and promises + * @param {string} name - Path to resolve + * @param {ResolveOptions} opts - Options for resolve + * @param {ResolveCallback} [cb] - Optional callback function + * @returns {Promise | void} - When callback is provided nothing is returned + */ + +/** + * IPFS Resolve factory + * + * @param {IPFS} ipfs + * @returns {ResolveWrapper} + */ +module.exports = (ipfs) => { + /** + * IPFS Resolve - Resolve the value of names to IPFS + * + * @param {String} name + * @param {ResolveOptions} [opts={}] + * @returns {Promise} + */ + const resolve = async (name, opts = {}) => { + if (!isIpfs.path(name)) { + throw new Error('invalid argument ' + name) + } + + if (isIpfs.ipnsPath(name)) { + name = await ipfs.name.resolve(name, opts) + } + + const [, , hash, ...rest] = name.split('/') // ['', 'ipfs', 'hash', ...path] + const cid = new CID(hash) + + // nothing to resolve return the input + if (rest.length === 0) { + return `/ipfs/${cidToString(cid, { base: opts.cidBase })}` + } + + const path = rest.join('/') + const results = ipfs._ipld.resolve(cid, path) + let value = cid + let remainderPath = path + + for await (const result of results) { + if (CID.isCID(result.value)) { + value = result.value + remainderPath = result.remainderPath + } + } + + return `/ipfs/${cidToString(value, { base: opts.cidBase })}${remainderPath ? '/' + remainderPath : ''}` + } + + return (name, opts = {}, cb) => { + if (typeof opts === 'function') { + cb = opts + opts = {} + } + return nodeify(resolve(name, opts), cb) + } +} + +},{"../../utils/cid":561,"cids":185,"is-ipfs":614,"promise-nodeify":1259}],532:[function(require,module,exports){ +'use strict' + +const series = require('async/series') +const Bitswap = require('ipfs-bitswap') +const setImmediate = require('async/setImmediate') +const promisify = require('promisify-es6') + +const IPNS = require('../ipns') +const routingConfig = require('../ipns/routing/config') +const createLibp2pBundle = require('./libp2p') + +module.exports = (self) => { + return promisify((callback) => { + const done = (err) => { + if (err) { + setImmediate(() => self.emit('error', err)) + return callback(err) + } + + self.state.started() + setImmediate(() => self.emit('start')) + callback() + } + + if (self.state.state() !== 'stopped') { + return done(new Error(`Not able to start from state: ${self.state.state()}`)) + } + + self.log('starting') + self.state.start() + + series([ + (cb) => { + // The repo may be closed if previously stopped + self._repo.closed + ? self._repo.open(cb) + : cb() + }, + (cb) => { + self._repo.config.get((err, config) => { + if (err) return cb(err) + + const libp2p = createLibp2pBundle(self, config) + + libp2p.start(err => { + if (err) return cb(err) + self.libp2p = libp2p + cb() + }) + }) + }, + (cb) => { + const ipnsRouting = routingConfig(self) + self._ipns = new IPNS(ipnsRouting, self._repo.datastore, self._peerInfo, self._keychain, self._options) + + self._bitswap = new Bitswap( + self.libp2p, + self._repo.blocks, + { statsEnabled: true } + ) + + self._bitswap.start() + self._blockService.setExchange(self._bitswap) + + self._preload.start() + self._ipns.republisher.start() + self._mfsPreload.start(cb) + } + ], done) + }) +} + +},{"../ipns":539,"../ipns/routing/config":544,"./libp2p":514,"async/series":95,"async/setImmediate":96,"ipfs-bitswap":339,"promisify-es6":1263}],533:[function(require,module,exports){ +(function (process){ +'use strict' + +const promisify = require('promisify-es6') +const Big = require('bignumber.js') +const Pushable = require('pull-pushable') +const human = require('human-to-milliseconds') +const toStream = require('pull-stream-to-stream') +const errCode = require('err-code') + +function bandwidthStats (self, opts) { + return new Promise((resolve, reject) => { + let stats + + if (opts.peer) { + stats = self.libp2p.stats.forPeer(opts.peer) + } else if (opts.proto) { + stats = self.libp2p.stats.forProtocol(opts.proto) + } else { + stats = self.libp2p.stats.global + } + + if (!stats) { + resolve({ + totalIn: new Big(0), + totalOut: new Big(0), + rateIn: new Big(0), + rateOut: new Big(0) + }) + return + } + + resolve({ + totalIn: stats.snapshot.dataReceived, + totalOut: stats.snapshot.dataSent, + rateIn: new Big(stats.movingAverages.dataReceived['60000'].movingAverage() / 60), + rateOut: new Big(stats.movingAverages.dataSent['60000'].movingAverage() / 60) + }) + }) +} + +module.exports = function stats (self) { + const _bwPullStream = (opts) => { + opts = opts || {} + let interval = null + const stream = Pushable(true, () => { + if (interval) { + clearInterval(interval) + } + }) + + if (opts.poll) { + let value + try { + value = human(opts.interval || '1s') + } catch (err) { + // Pull stream expects async work, so we need to simulate it. + process.nextTick(() => { + stream.end(errCode(err, 'ERR_INVALID_POLL_INTERVAL')) + }) + } + + interval = setInterval(() => { + bandwidthStats(self, opts) + .then((stats) => stream.push(stats)) + .catch((err) => { + if (interval) { + clearInterval(interval) + } + stream.end(err) + }) + }, value) + } else { + bandwidthStats(self, opts) + .then((stats) => { + stream.push(stats) + stream.end() + }) + .catch((err) => stream.end(err)) + } + + return stream.source + } + + return { + bitswap: require('./bitswap')(self).stat, + repo: require('./repo')(self).stat, + bw: promisify((opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + opts = opts || {} + + bandwidthStats(self, opts) + .then((stats) => callback(null, stats)) + .catch((err) => callback(err)) + }), + bwReadableStream: (opts) => toStream.source(_bwPullStream(opts)), + bwPullStream: _bwPullStream + } +} + +}).call(this,require('_process')) +},{"./bitswap":477,"./repo":530,"_process":1258,"bignumber.js":110,"err-code":268,"human-to-milliseconds":312,"promisify-es6":1263,"pull-pushable":1306,"pull-stream-to-stream":1310}],534:[function(require,module,exports){ +'use strict' + +const parallel = require('async/parallel') +const promisify = require('promisify-es6') + +module.exports = (self) => { + return promisify((callback) => { + callback = callback || function noop () {} + + self.log('stop') + + if (self.state.state() === 'stopped') { + return callback(new Error('Already stopped')) + } + + if (self.state.state() !== 'running') { + return callback(new Error('Not able to stop from state: ' + self.state.state())) + } + + self.state.stop() + self._blockService.unsetExchange() + self._bitswap.stop() + self._preload.stop() + + parallel([ + cb => self._ipns.republisher.stop(cb), + cb => self._mfsPreload.stop(cb), + cb => { + const libp2p = self.libp2p + self.libp2p = null + libp2p.stop(cb) + } + ], err => { + self._repo.close(closeErr => { + if (err || closeErr) { + self.emit('error', err || closeErr) + return callback(err || closeErr) + } + + self.state.stopped() + self.emit('stop') + callback() + }) + }) + }) +} + +},{"async/parallel":91,"promisify-es6":1263}],535:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') + +const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR + +module.exports = function swarm (self) { + return { + peers: promisify((opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + opts = opts || {} + + if (!self.isOnline()) { + return callback(new Error(OFFLINE_ERROR)) + } + + const verbose = opts.v || opts.verbose + // TODO: return latency and streams when verbose is set + // we currently don't have this information + + const peers = [] + + Object.values(self._peerInfoBook.getAll()).forEach((peer) => { + const connectedAddr = peer.isConnected() + + if (!connectedAddr) { return } + + const tupple = { + addr: connectedAddr, + peer: peer.id + } + if (verbose) { + tupple.latency = 'n/a' + } + + peers.push(tupple) + }) + + callback(null, peers) + }), + + // all the addrs we know + addrs: promisify((callback) => { + if (!self.isOnline()) { + return callback(new Error(OFFLINE_ERROR)) + } + + const peers = Object.values(self._peerInfoBook.getAll()) + + callback(null, peers) + }), + + localAddrs: promisify((callback) => { + if (!self.isOnline()) { + return callback(new Error(OFFLINE_ERROR)) + } + + callback(null, self.libp2p.peerInfo.multiaddrs.toArray()) + }), + + connect: promisify((maddr, callback) => { + if (!self.isOnline()) { + return callback(new Error(OFFLINE_ERROR)) + } + + self.libp2p.dial(maddr, callback) + }), + + disconnect: promisify((maddr, callback) => { + if (!self.isOnline()) { + return callback(new Error(OFFLINE_ERROR)) + } + + self.libp2p.hangUp(maddr, callback) + }), + + filters: promisify((callback) => callback(new Error('Not implemented'))) + } +} + +},{"../utils":560,"promisify-es6":1263}],536:[function(require,module,exports){ +'use strict' + +const pkg = require('../../../package.json') +const promisify = require('promisify-es6') + +// TODO add the commit hash of the current ipfs version to the response. +module.exports = function version (self) { + return promisify((opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + self.repo.version((err, repoVersion) => { + if (err) { + return callback(err) + } + + callback(null, { + version: pkg.version, + repo: repoVersion, + commit: '' + }) + }) + }) +} + +},{"../../../package.json":475,"promisify-es6":1263}],537:[function(require,module,exports){ +'use strict' + +const Multiaddr = require('multiaddr') +const mafmt = require('mafmt') +const { struct, superstruct } = require('superstruct') + +const { optional, union } = struct +const s = superstruct({ + types: { + multiaddr: v => { + if (v === null) { + return `multiaddr invalid, value must be a string, Buffer, or another Multiaddr got ${v}` + } + + try { + Multiaddr(v) + } catch (err) { + return `multiaddr invalid, ${err.message}` + } + + return true + }, + 'multiaddr-ipfs': v => mafmt.IPFS.matches(v) ? true : 'multiaddr IPFS invalid' + } +}) + +const configSchema = s({ + repo: optional(s('object|string')), + repoOwner: 'boolean?', + preload: s({ + enabled: 'boolean?', + addresses: optional(s(['multiaddr'])), + interval: 'number?' + }, { enabled: true, interval: 30 * 1000 }), + init: optional(union(['boolean', s({ + bits: 'number?', + emptyRepo: 'boolean?', + privateKey: optional(s('object|string')), // object should be a custom type for PeerId using 'kind-of' + pass: 'string?' + })])), + start: 'boolean?', + offline: 'boolean?', + pass: 'string?', + silent: 'boolean?', + relay: 'object?', // relay validates in libp2p + EXPERIMENTAL: optional(s({ + pubsub: 'boolean?', + ipnsPubsub: 'boolean?', + sharding: 'boolean?', + dht: 'boolean?' + })), + connectionManager: 'object?', + config: optional(s({ + API: 'object?', + Addresses: optional(s({ + Delegates: optional(s(['multiaddr'])), + Swarm: optional(s(['multiaddr'])), + API: optional(union([s('multiaddr'), s(['multiaddr'])])), + Gateway: optional(union([s('multiaddr'), s(['multiaddr'])])) + })), + Discovery: optional(s({ + MDNS: optional(s({ + Enabled: 'boolean?', + Interval: 'number?' + })), + webRTCStar: optional(s({ + Enabled: 'boolean?' + })) + })), + Bootstrap: optional(s(['multiaddr-ipfs'])), + Pubsub: optional(s({ + Router: 'string?', + Enabled: 'boolean?' + })), + Swarm: optional(s({ + ConnMgr: optional(s({ + LowWater: 'number?', + HighWater: 'number?' + })) + })) + })), + ipld: 'object?', + libp2p: optional(union(['function', 'object'])) // libp2p validates this +}, { + repoOwner: true +}) + +const validate = (opts) => { + const [err, options] = configSchema.validate(opts) + + if (err) { + throw err + } + + return options +} + +module.exports = { validate } + +},{"mafmt":1125,"multiaddr":1140,"superstruct":1498}],538:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const BlockService = require('ipfs-block-service') +const Ipld = require('ipld') +const PeerId = require('peer-id') +const PeerInfo = require('peer-info') +const crypto = require('libp2p-crypto') +const isIPFS = require('is-ipfs') +const multiaddr = require('multiaddr') +const multihash = require('multihashes') +const PeerBook = require('peer-book') +const multibase = require('multibase') +const multicodec = require('multicodec') +const multihashing = require('multihashing-async') +const CID = require('cids') +const debug = require('debug') +const mergeOptions = require('merge-options') +const EventEmitter = require('events') + +const config = require('./config') +const boot = require('./boot') +const components = require('./components') +const GCLock = require('./components/pin/gc-lock') + +// replaced by repo-browser when running in the browser +const defaultRepo = require('./runtime/repo-nodejs') +const preload = require('./preload') +const mfsPreload = require('./mfs-preload') +const ipldOptions = require('./runtime/ipld-nodejs') + +/** + * @typedef { import("./ipns/index") } IPNS + */ + +/** + * + * + * @class IPFS + * @extends {EventEmitter} + */ +class IPFS extends EventEmitter { + constructor (options) { + super() + + const defaults = { + init: true, + start: true, + EXPERIMENTAL: {}, + preload: { + enabled: true, + addresses: [ + '/dnsaddr/node0.preload.ipfs.io/https', + '/dnsaddr/node1.preload.ipfs.io/https' + ] + } + } + + options = config.validate(options || {}) + + this._options = mergeOptions(defaults, options) + + if (options.init === false) { + this._options.init = false + } + + if (!(options.start === false)) { + this._options.start = true + } + + if (typeof options.repo === 'string' || + options.repo === undefined) { + this._repo = defaultRepo(options.repo) + } else { + this._repo = options.repo + } + + // IPFS utils + this.log = debug('ipfs') + this.log.err = debug('ipfs:err') + + // IPFS Core Internals + // this._repo - assigned above + this._peerInfoBook = new PeerBook() + this._peerInfo = undefined + this._bitswap = undefined + this._blockService = new BlockService(this._repo) + this._ipld = new Ipld(ipldOptions(this._blockService, this._options.ipld, this.log)) + this._preload = preload(this) + this._mfsPreload = mfsPreload(this) + /** @type {IPNS} */ + this._ipns = undefined + // eslint-disable-next-line no-console + this._print = this._options.silent ? this.log : console.log + this._gcLock = new GCLock(this._options.repoOwner, { + // Make sure GCLock is specific to repo, for tests where there are + // multiple instances of IPFS + morticeId: this._repo.path + }) + + // IPFS Core exposed components + // - for booting up a node + this.init = components.init(this) + this.preStart = components.preStart(this) + this.start = components.start(this) + this.stop = components.stop(this) + this.shutdown = this.stop + this.isOnline = components.isOnline(this) + // - interface-ipfs-core defined API + Object.assign(this, components.filesRegular(this)) + this.version = components.version(this) + this.id = components.id(this) + this.repo = components.repo(this) + this.bootstrap = components.bootstrap(this) + this.config = components.config(this) + this.block = components.block(this) + this.object = components.object(this) + this.dag = components.dag(this) + this.files = components.filesMFS(this) + this.libp2p = null // assigned on start + this.swarm = components.swarm(this) + this.name = components.name(this) + this.bitswap = components.bitswap(this) + this.pin = components.pin(this) + this.ping = components.ping(this) + this.pingPullStream = components.pingPullStream(this) + this.pingReadableStream = components.pingReadableStream(this) + this.pubsub = components.pubsub(this) + this.dht = components.dht(this) + this.dns = components.dns(this) + this.key = components.key(this) + this.stats = components.stats(this) + this.resolve = components.resolve(this) + + if (this._options.EXPERIMENTAL.ipnsPubsub) { + this.log('EXPERIMENTAL IPNS pubsub is enabled') + } + if (this._options.EXPERIMENTAL.sharding) { + this.log('EXPERIMENTAL sharding is enabled') + } + + this.state = require('./state')(this) + + const onReady = () => { + this.removeListener('error', onError) + this._ready = true + } + + const onError = err => { + this.removeListener('ready', onReady) + this._readyError = err + } + + this.once('ready', onReady).once('error', onError) + + boot(this) + } + + get ready () { + return new Promise((resolve, reject) => { + if (this._ready) return resolve(this) + if (this._readyError) return reject(this._readyError) + this.once('ready', () => resolve(this)) + this.once('error', reject) + }) + } +} + +module.exports = IPFS + +// Note: We need to do this to force browserify to load the Buffer module +const BufferImpl = Buffer +Object.assign(module.exports, { crypto, isIPFS, Buffer: BufferImpl, CID, multiaddr, multibase, multihash, multihashing, multicodec, PeerId, PeerInfo }) + +module.exports.createNode = (options) => { + return new IPFS(options) +} + +module.exports.create = (options) => { + return new IPFS(options).ready +} + +}).call(this,require("buffer").Buffer) +},{"./boot":476,"./components":510,"./components/pin/gc-lock":520,"./config":537,"./mfs-preload":548,"./preload":549,"./runtime/ipld-nodejs":554,"./runtime/repo-nodejs":558,"./state":559,"buffer":181,"cids":185,"debug":456,"events":272,"ipfs-block-service":352,"ipld":600,"is-ipfs":614,"libp2p-crypto":745,"merge-options":1127,"multiaddr":1140,"multibase":1148,"multicodec":1151,"multihashes":1157,"multihashing-async":1161,"peer-book":1252,"peer-id":1253,"peer-info":1254}],539:[function(require,module,exports){ +'use strict' + +const { createFromPrivKey } = require('peer-id') +const series = require('async/series') + +const errcode = require('err-code') +const debug = require('debug') +const log = debug('ipfs:ipns') +log.error = debug('ipfs:ipns:error') + +const IpnsPublisher = require('./publisher') +const IpnsRepublisher = require('./republisher') +const IpnsResolver = require('./resolver') +const path = require('./path') +const { normalizePath } = require('../utils') +const TLRU = require('../../utils/tlru') +const defaultRecordTtl = 60 * 1000 + +class IPNS { + constructor (routing, datastore, peerInfo, keychain, options) { + this.publisher = new IpnsPublisher(routing, datastore) + this.republisher = new IpnsRepublisher(this.publisher, datastore, peerInfo, keychain, options) + this.resolver = new IpnsResolver(routing) + this.cache = new TLRU(1000) + this.routing = routing + } + + // Publish + publish (privKey, value, lifetime = IpnsPublisher.defaultRecordLifetime, callback) { + try { + value = normalizePath(value) + } catch (err) { + log.error(err) + return callback(err) + } + + series([ + (cb) => createFromPrivKey(privKey.bytes, cb), + (cb) => this.publisher.publishWithEOL(privKey, value, lifetime, cb) + ], (err, results) => { + if (err) { + log.error(err) + return callback(err) + } + + log(`IPNS value ${value} was published correctly`) + + // // Add to cache + const id = results[0].toB58String() + const ttEol = parseFloat(lifetime) + const ttl = (ttEol < defaultRecordTtl) ? ttEol : defaultRecordTtl + + this.cache.set(id, value, ttl) + + log(`IPNS value ${value} was cached correctly`) + + callback(null, { + name: id, + value: value + }) + }) + } + + // Resolve + resolve (name, options, callback) { + if (typeof name !== 'string') { + return callback(errcode(new Error('name received is not valid'), 'ERR_INVALID_NAME')) + } + + if (typeof options === 'function') { + callback = options + options = {} + } + + options = options || {} + + // If recursive, we should not try to get the cached value + if (!options.nocache && !options.recursive) { + // Try to get the record from cache + const id = name.split('/')[2] + const result = this.cache.get(id) + + if (result) { + return callback(null, result) + } + } + + this.resolver.resolve(name, options, (err, result) => { + if (err) { + log.error(err) + return callback(err) + } + + log(`IPNS record from ${name} was resolved correctly`) + + callback(null, result) + }) + } + + // Initialize keyspace + // sets the ipns record for the given key to point to an empty directory + initializeKeyspace (privKey, value, callback) { + this.publish(privKey, value, IpnsPublisher.defaultRecordLifetime, callback) + } +} + +IPNS.path = path + +module.exports = IPNS + +},{"../../utils/tlru":563,"../utils":560,"./path":540,"./publisher":541,"./republisher":542,"./resolver":543,"async/series":95,"debug":456,"err-code":268,"peer-id":1253}],540:[function(require,module,exports){ +'use strict' + +const isIPFS = require('is-ipfs') + +const debug = require('debug') +const log = debug('ipfs:ipns:path') +log.error = debug('ipfs:ipns:path:error') + +// resolves the given path by parsing out protocol-specific entries +// (e.g. /ipns/) and then going through the /ipfs/ entries and returning the final node +const resolvePath = (ipfsNode, name, callback) => { + // ipns path + if (isIPFS.ipnsPath(name)) { + log(`resolve ipns path ${name}`) + + return ipfsNode._ipns.resolve(name, callback) + } + + // ipfs path + ipfsNode.dag.get(name.substring('/ipfs/'.length), (err, value) => { + if (err) { + return callback(err) + } + + return callback(null, value) + }) +} + +module.exports = { + resolvePath +} + +},{"debug":456,"is-ipfs":614}],541:[function(require,module,exports){ +'use strict' + +const PeerId = require('peer-id') +const { Key } = require('interface-datastore') +const series = require('async/series') +const errcode = require('err-code') + +const debug = require('debug') +const log = debug('ipfs:ipns:publisher') +log.error = debug('ipfs:ipns:publisher:error') + +const ipns = require('ipns') + +const defaultRecordLifetime = 60 * 60 * 1000 + +// IpnsPublisher is capable of publishing and resolving names to the IPFS routing system. +class IpnsPublisher { + constructor (routing, datastore) { + this._routing = routing + this._datastore = datastore + } + + // publish record with a eol + publishWithEOL (privKey, value, lifetime, callback) { + if (!privKey || !privKey.bytes) { + return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY')) + } + + PeerId.createFromPrivKey(privKey.bytes, (err, peerId) => { + if (err) { + return callback(err) + } + + this._updateOrCreateRecord(privKey, value, lifetime, peerId, (err, record) => { + if (err) { + return callback(err) + } + + this._putRecordToRouting(record, peerId, callback) + }) + }) + } + + // Accepts a keypair, as well as a value (ipfsPath), and publishes it out to the routing system + publish (privKey, value, callback) { + this.publishWithEOL(privKey, value, defaultRecordLifetime, callback) + } + + _putRecordToRouting (record, peerId, callback) { + if (!(PeerId.isPeerId(peerId))) { + const errMsg = 'peerId received is not valid' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) + } + const publicKey = peerId._pubKey + + ipns.embedPublicKey(publicKey, record, (err, embedPublicKeyRecord) => { + if (err) { + return callback(err) + } + + let keys + try { + keys = ipns.getIdKeys(peerId.toBytes()) + } catch (err) { + log.error(err) + return callback(err) + } + + series([ + (cb) => this._publishEntry(keys.routingKey, embedPublicKeyRecord || record, peerId, cb), + // Publish the public key to support old go-ipfs nodes that are looking for it in the routing + // We will be able to deprecate this part in the future, since the public keys will be only + // in IPNS record and the peerId. + (cb) => this._publishPublicKey(keys.routingPubKey, publicKey, peerId, cb) + ], (err) => { + if (err) { + log.error(err) + return callback(err) + } + + callback(null, embedPublicKeyRecord || record) + }) + }) + } + + _publishEntry (key, entry, peerId, callback) { + if (!(Key.isKey(key))) { + const errMsg = 'datastore key does not have a valid format' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY')) + } + + let entryData + try { + // Marshal record + entryData = ipns.marshal(entry) + } catch (err) { + log.error(err) + return callback(err) + } + + // Add record to routing (buffer key) + this._routing.put(key.toBuffer(), entryData, (err, res) => { + if (err) { + const errMsg = `ipns record for ${key.toString('base64')} could not be stored in the routing` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')) + } + + log(`ipns record for ${key.toString('base64')} was stored in the routing`) + callback(null, res) + }) + } + + _publishPublicKey (key, publicKey, peerId, callback) { + if ((!Key.isKey(key))) { + const errMsg = 'datastore key does not have a valid format' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY')) + } + + if (!publicKey || !publicKey.bytes) { + const errMsg = 'one or more of the provided parameters are not defined' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_UNDEFINED_PARAMETER')) + } + + // Add public key to routing (buffer key) + this._routing.put(key.toBuffer(), publicKey.bytes, (err, res) => { + if (err) { + const errMsg = `public key for ${key.toString('base64')} could not be stored in the routing` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')) + } + + log(`public key for ${key.toString('base64')} was stored in the routing`) + callback(null, res) + }) + } + + // Returns the record this node has published corresponding to the given peer ID. + // If `checkRouting` is true and we have no existing record, this method will check the routing system for any existing records. + _getPublished (peerId, options, callback) { + if (!(PeerId.isPeerId(peerId))) { + const errMsg = 'peerId received is not valid' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) + } + + options = options || {} + const checkRouting = options.checkRouting !== false + + this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => { + if (err) { + if (err.code !== 'ERR_NOT_FOUND') { + const errMsg = `unexpected error getting the ipns record ${peerId.id} from datastore` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_UNEXPECTED_DATASTORE_RESPONSE')) + } + + if (!checkRouting) { + return callback((errcode(err))) + } + + // Try to get from routing + let keys + try { + keys = ipns.getIdKeys(peerId.toBytes()) + } catch (err) { + log.error(err) + return callback(err) + } + + this._routing.get(keys.routingKey.toBuffer(), (err, res) => { + if (err) { + return callback(err) + } + + // unmarshal data + this._unmarshalData(res, callback) + }) + } else { + // unmarshal data + this._unmarshalData(dsVal, callback) + } + }) + } + + _unmarshalData (data, callback) { + let result + try { + result = ipns.unmarshal(data) + } catch (err) { + log.error(err) + return callback(errcode(err, 'ERR_INVALID_RECORD_DATA')) + } + + callback(null, result) + } + + _updateOrCreateRecord (privKey, value, validity, peerId, callback) { + if (!(PeerId.isPeerId(peerId))) { + const errMsg = 'peerId received is not valid' + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) + } + + const getPublishedOptions = { + checkRouting: true + } + + this._getPublished(peerId, getPublishedOptions, (err, record) => { + if (err) { + if (err.code !== 'ERR_NOT_FOUND') { + const errMsg = `unexpected error when determining the last published IPNS record for ${peerId.id}` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_DETERMINING_PUBLISHED_RECORD')) + } + } + + // Determinate the record sequence number + let seqNumber = 0 + if (record && record.sequence !== undefined) { + seqNumber = record.value.toString() !== value ? record.sequence + 1 : record.sequence + } + + // Create record + ipns.create(privKey, value, seqNumber, validity, (err, entryData) => { + if (err) { + const errMsg = `ipns record for ${value} could not be created` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_CREATING_IPNS_RECORD')) + } + + // TODO IMPROVEMENT - set ttl (still experimental feature for go) + + // Marshal record + const data = ipns.marshal(entryData) + + // Store the new record + this._datastore.put(ipns.getLocalKey(peerId.id), data, (err, res) => { + if (err) { + const errMsg = `ipns record for ${value} could not be stored in the datastore` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_STORING_IN_DATASTORE')) + } + + log(`ipns record for ${value} was stored in the datastore`) + callback(null, entryData) + }) + }) + }) + } +} + +IpnsPublisher.defaultRecordLifetime = defaultRecordLifetime +exports = module.exports = IpnsPublisher + +},{"async/series":95,"debug":456,"err-code":268,"interface-datastore":322,"ipns":605,"peer-id":1253}],542:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const ipns = require('ipns') +const crypto = require('libp2p-crypto') +const PeerId = require('peer-id') +const errcode = require('err-code') + +const debug = require('debug') +const each = require('async/each') +const waterfall = require('async/waterfall') +const log = debug('ipfs:ipns:republisher') +log.error = debug('ipfs:ipns:republisher:error') + +const minute = 60 * 1000 +const hour = 60 * minute + +const defaultBroadcastInterval = 4 * hour +const defaultRecordLifetime = 24 * hour + +class IpnsRepublisher { + constructor (publisher, datastore, peerInfo, keychain, options) { + this._publisher = publisher + this._datastore = datastore + this._peerInfo = peerInfo + this._keychain = keychain + this._options = options + this._republishHandle = null + } + + start () { + if (this._republishHandle) { + throw errcode(new Error('republisher is already running'), 'ERR_REPUBLISH_ALREADY_RUNNING') + } + + // TODO: this handler should be isolated in another module + const republishHandle = { + _onCancel: null, + _timeoutId: null, + runPeriodically: (fn, period) => { + republishHandle._timeoutId = setTimeout(() => { + republishHandle._timeoutId = null + + fn((nextPeriod) => { + // Was republish cancelled while fn was being called? + if (republishHandle._onCancel) { + return republishHandle._onCancel() + } + // Schedule next + republishHandle.runPeriodically(fn, nextPeriod || period) + }) + }, period) + }, + cancel: (cb) => { + // Not currently running a republish, can callback immediately + if (republishHandle._timeoutId) { + clearTimeout(republishHandle._timeoutId) + return cb() + } + // Wait for republish to finish then call callback + republishHandle._onCancel = cb + } + } + + const { privKey } = this._peerInfo.id + const { pass } = this._options + + republishHandle.runPeriodically((done) => { + this._republishEntries(privKey, pass, () => done(defaultBroadcastInterval)) + }, minute) + + this._republishHandle = republishHandle + } + + stop (callback) { + const republishHandle = this._republishHandle + + if (!republishHandle) { + return callback(errcode(new Error('republisher is not running'), 'ERR_REPUBLISH_NOT_RUNNING')) + } + + this._republishHandle = null + republishHandle.cancel(callback) + } + + _republishEntries (privateKey, pass, callback) { + // TODO: Should use list of published entries. + // We can't currently *do* that because go uses this method for now. + this._republishEntry(privateKey, (err) => { + if (err) { + const errMsg = 'cannot republish entry for the node\'s private key' + + log.error(errMsg) + return + } + + // keychain needs pass to get the cryptographic keys + if (pass) { + this._keychain.listKeys((err, list) => { + if (err) { + log.error(err) + return + } + + each(list, (key, cb) => { + waterfall([ + (cb) => this._keychain.exportKey(key.name, pass, cb), + (pem, cb) => crypto.keys.import(pem, pass, cb) + ], (err, privKey) => { + if (err) { + log.error(err) + return + } + + this._republishEntry(privKey, cb) + }) + }, (err) => { + if (err) { + log.error(err) + } + callback(null) + }) + }) + } else { + callback(null) + } + }) + } + + _republishEntry (privateKey, callback) { + if (!privateKey || !privateKey.bytes) { + return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY')) + } + + waterfall([ + (cb) => PeerId.createFromPrivKey(privateKey.bytes, cb), + (peerId, cb) => this._getPreviousValue(peerId, cb) + ], (err, value) => { + if (err) { + return callback(err.code === 'ERR_NO_ENTRY_FOUND' ? null : err) + } + + this._publisher.publishWithEOL(privateKey, value, defaultRecordLifetime, callback) + }) + } + + _getPreviousValue (peerId, callback) { + if (!(PeerId.isPeerId(peerId))) { + return callback(errcode(new Error('invalid peer ID'), 'ERR_INVALID_PEER_ID')) + } + + this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => { + // error handling + // no need to republish + if (err && err.notFound) { + return callback(errcode(new Error(`no previous entry for record with id: ${peerId.id}`), 'ERR_NO_ENTRY_FOUND')) + } else if (err) { + return callback(err) + } + + if (!Buffer.isBuffer(dsVal)) { + return callback(errcode(new Error("found ipns record that we couldn't process"), 'ERR_INVALID_IPNS_RECORD')) + } + + // unmarshal data + let record + try { + record = ipns.unmarshal(dsVal) + } catch (err) { + log.error(err) + return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_IPNS_RECORD')) + } + + callback(null, record.value) + }) + } +} + +exports = module.exports = IpnsRepublisher + +}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) +},{"../../../../is-buffer/index.js":608,"async/each":56,"async/waterfall":102,"debug":456,"err-code":268,"ipns":605,"libp2p-crypto":745,"peer-id":1253}],543:[function(require,module,exports){ +'use strict' + +const ipns = require('ipns') +const crypto = require('libp2p-crypto') +const PeerId = require('peer-id') +const errcode = require('err-code') + +const debug = require('debug') +const log = debug('ipfs:ipns:resolver') +log.error = debug('ipfs:ipns:resolver:error') + +const defaultMaximumRecursiveDepth = 32 + +class IpnsResolver { + constructor (routing) { + this._routing = routing + } + + resolve (name, options, callback) { + if (typeof options === 'function') { + callback = options + options = {} + } + + if (typeof name !== 'string') { + return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME')) + } + + options = options || {} + const recursive = options.recursive && options.recursive.toString() === 'true' + + const nameSegments = name.split('/') + + if (nameSegments.length !== 3 || nameSegments[0] !== '') { + return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME')) + } + + const key = nameSegments[2] + + // Define a maximum depth if recursive option enabled + let depth + + if (recursive) { + depth = defaultMaximumRecursiveDepth + } + + this.resolver(key, depth, (err, res) => { + if (err) { + return callback(err) + } + + log(`${name} was locally resolved correctly`) + callback(null, res) + }) + } + + // Recursive resolver according to the specified depth + resolver (name, depth, callback) { + // Exceeded recursive maximum depth + if (depth === 0) { + const errMsg = `could not resolve name (recursion limit of ${defaultMaximumRecursiveDepth} exceeded)` + + log.error(errMsg) + return callback(errcode(new Error(errMsg), 'ERR_RESOLVE_RECURSION_LIMIT')) + } + + this._resolveName(name, (err, res) => { + if (err) { + return callback(err) + } + + const nameSegments = res.split('/') + + // If obtained a ipfs cid or recursive option is disabled + if (nameSegments[1] === 'ipfs' || !depth) { + return callback(null, res) + } + + // continue recursively until depth equals 0 + this.resolver(nameSegments[2], depth - 1, callback) + }) + } + + // resolve ipns entries from the provided routing + _resolveName (name, callback) { + let peerId + + try { + peerId = PeerId.createFromB58String(name) + } catch (err) { + return callback(err) + } + + const { routingKey, routingPubKey } = ipns.getIdKeys(peerId.toBytes()) + + this._routing.get(routingKey.toBuffer(), (err, record) => { + if (err) { + log.error(err) + if (err.code !== 'ERR_NOT_FOUND') { + return callback(errcode(new Error(`unexpected error getting the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')) + } + return callback(errcode(new Error(`record requested was not found for ${name} (${routingKey}) in the network`), 'ERR_NO_RECORD_FOUND')) + } + + // IPNS entry + let ipnsEntry + try { + ipnsEntry = ipns.unmarshal(record) + } catch (err) { + log.error(err) + return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_RECORD_RECEIVED')) + } + + // if the record has a public key validate it + if (ipnsEntry.pubKey) { + return this._validateRecord(peerId, ipnsEntry, callback) + } + + // Otherwise, try to get the public key from routing + this._routing.get(routingKey.toBuffer(), (err, pubKey) => { + if (err) { + log.error(err) + if (err.code !== 'ERR_NOT_FOUND') { + return callback(errcode(new Error(`unexpected error getting the public key for the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_PUB_KEY')) + } + return callback(errcode(new Error(`public key requested was not found for ${name} (${routingPubKey}) in the network`), 'ERR_NO_RECORD_FOUND')) + } + + try { + // Insert it into the peer id, in order to be validated by IPNS validator + peerId.pubKey = crypto.keys.unmarshalPublicKey(pubKey) + } catch (err) { + log.error(err) + return callback(errcode(new Error('found public key record that we couldn\'t convert to a value'), 'ERR_INVALID_PUB_KEY_RECEIVED')) + } + + this._validateRecord(peerId, ipnsEntry, callback) + }) + }) + } + + // validate a resolved record + _validateRecord (peerId, ipnsEntry, callback) { + ipns.extractPublicKey(peerId, ipnsEntry, (err, pubKey) => { + if (err) { + return callback(err) + } + + // IPNS entry validation + ipns.validate(pubKey, ipnsEntry, (err) => { + if (err) { + return callback(err) + } + + callback(null, ipnsEntry.value.toString()) + }) + }) + } +} + +exports = module.exports = IpnsResolver + +},{"debug":456,"err-code":268,"ipns":605,"libp2p-crypto":745,"peer-id":1253}],544:[function(require,module,exports){ +'use strict' + +const { TieredDatastore } = require('datastore-core') +const get = require('dlv') + +const PubsubDatastore = require('./pubsub-datastore') +const OfflineDatastore = require('./offline-datastore') + +module.exports = (ipfs) => { + // Setup online routing for IPNS with a tiered routing composed by a DHT and a Pubsub router (if properly enabled) + const ipnsStores = [] + + // Add IPNS pubsub if enabled + let pubsubDs + if (get(ipfs._options, 'EXPERIMENTAL.ipnsPubsub', false)) { + const pubsub = ipfs.libp2p.pubsub + const localDatastore = ipfs._repo.datastore + const peerId = ipfs._peerInfo.id + + pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId) + ipnsStores.push(pubsubDs) + } + + // DHT should not be added as routing if we are offline or it is disabled + if (get(ipfs._options, 'offline') || !get(ipfs._options, 'libp2p.config.dht.enabled', false)) { + const offlineDatastore = new OfflineDatastore(ipfs._repo) + ipnsStores.push(offlineDatastore) + } else { + ipnsStores.push(ipfs.libp2p.dht) + } + + // Create ipns routing with a set of datastores + return new TieredDatastore(ipnsStores) +} + +},{"./offline-datastore":545,"./pubsub-datastore":546,"datastore-core":199,"dlv":233}],545:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const { Key } = require('interface-datastore') +const { Record } = require('libp2p-record') +const { encodeBase32 } = require('./utils') + +const errcode = require('err-code') +const debug = require('debug') +const log = debug('ipfs:ipns:offline-datastore') +log.error = debug('ipfs:ipns:offline-datastore:error') + +// Offline datastore aims to mimic the same encoding as routing when storing records +// to the local datastore +class OfflineDatastore { + constructor (repo) { + this._repo = repo + } + + /** + * Put a value to the local datastore indexed by the received key properly encoded. + * @param {Buffer} key identifier of the value. + * @param {Buffer} value value to be stored. + * @param {function(Error)} callback + * @returns {void} + */ + put (key, value, callback) { + if (!Buffer.isBuffer(key)) { + return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY')) + } + + if (!Buffer.isBuffer(value)) { + return callback(errcode(new Error('Offline datastore value must be a buffer'), 'ERR_INVALID_VALUE')) + } + + let routingKey + + try { + routingKey = this._routingKey(key) + } catch (err) { + log.error(err) + return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')) + } + + // Marshal to libp2p record as the DHT does + const record = new Record(key, value) + + this._repo.datastore.put(routingKey, record.serialize(), callback) + } + + /** + * Get a value from the local datastore indexed by the received key properly encoded. + * @param {Buffer} key identifier of the value to be obtained. + * @param {function(Error, Buffer)} callback + * @returns {void} + */ + get (key, callback) { + if (!Buffer.isBuffer(key)) { + return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY')) + } + + let routingKey + + try { + routingKey = this._routingKey(key) + } catch (err) { + log.error(err) + return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')) + } + + this._repo.datastore.get(routingKey, (err, res) => { + if (err) { + return callback(err) + } + + // Unmarshal libp2p record as the DHT does + let record + try { + record = Record.deserialize(res) + } catch (err) { + log.error(err) + return callback(err) + } + + callback(null, record.value) + }) + } + + // encode key properly - base32(/ipns/{cid}) + _routingKey (key) { + return new Key('/' + encodeBase32(key), false) + } +} + +exports = module.exports = OfflineDatastore + +}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) +},{"../../../../../is-buffer/index.js":608,"./utils":547,"debug":456,"err-code":268,"interface-datastore":322,"libp2p-record":945}],546:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const ipns = require('ipns') +const { fromB58String, toB58String } = require('multihashes') +const PubsubDatastore = require('datastore-pubsub') + +const withIs = require('class-is') + +const errcode = require('err-code') +const debug = require('debug') +const log = debug('ipfs:ipns:pubsub') +log.error = debug('ipfs:ipns:pubsub:error') + +// Pubsub datastore aims to manage the pubsub subscriptions for IPNS +class IpnsPubsubDatastore { + constructor (pubsub, localDatastore, peerId) { + this._pubsub = pubsub + this._subscriptions = {} + + // Bind _handleSubscriptionKey function, which is called by PubsubDatastore. + this._handleSubscriptionKey = this._handleSubscriptionKey.bind(this) + this._pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId, ipns.validator, this._handleSubscriptionKey) + } + + /** + * Put a value to the pubsub datastore indexed by the received key properly encoded. + * @param {Buffer} key identifier of the value. + * @param {Buffer} value value to be stored. + * @param {function(Error)} callback + * @returns {void} + */ + put (key, value, callback) { + this._pubsubDs.put(key, value, callback) + } + + /** + * Get a value from the pubsub datastore indexed by the received key properly encoded. + * Moreover, the identifier topic is subscribed and the pubsub datastore records will be + * updated once new publishes occur. + * @param {Buffer} key identifier of the value to be obtained. + * @param {function(Error, Buffer)} callback + * @returns {void} + */ + get (key, callback) { + this._pubsubDs.get(key, (err, res) => { + // Add topic subscribed + const ns = key.slice(0, ipns.namespaceLength) + + if (ns.toString() === ipns.namespace) { + const stringifiedTopic = key.toString() + const id = toB58String(key.slice(ipns.namespaceLength)) + + this._subscriptions[stringifiedTopic] = id + + log(`subscribed pubsub ${stringifiedTopic}: ${id}`) + } + + // If no data was obtained, after storing the subscription, return the error. + if (err) { + return callback(err) + } + + callback(null, res) + }) + } + + // Modify subscription key to have a proper encoding + _handleSubscriptionKey (key, callback) { + const subscriber = this._subscriptions[key] + + if (!subscriber) { + return callback(errcode(new Error(`key ${key} does not correspond to a subscription`), 'ERR_INVALID_KEY')) + } + + let keys + try { + keys = ipns.getIdKeys(fromB58String(subscriber)) + } catch (err) { + log.error(err) + return callback(err) + } + + callback(null, keys.routingKey.toBuffer()) + } + + /** + * Get pubsub subscriptions related to ipns. + * @param {function(Error, Object)} callback + * @returns {void} + */ + getSubscriptions (callback) { + const subscriptions = Object.values(this._subscriptions).filter(Boolean) + + return callback(null, subscriptions.map((sub) => `${ipns.namespace}${sub}`)) + } + + /** + * Cancel pubsub subscriptions related to ipns. + * @param {String} name ipns path to cancel the pubsub subscription. + * @param {function(Error, Object)} callback + * @returns {void} + */ + cancel (name, callback) { + if (typeof name !== 'string') { + return callback(errcode(new Error('invalid subscription name'), 'ERR_INVALID_SUBSCRIPTION_NAME')) + } + + // Trim /ipns/ prefix from the name + if (name.startsWith(ipns.namespace)) { + name = name.substring(ipns.namespaceLength) + } + + const stringifiedTopic = Object.keys(this._subscriptions).find((key) => this._subscriptions[key] === name) + + // Not found topic + if (!stringifiedTopic) { + return callback(null, { + canceled: false + }) + } + + // Unsubscribe topic + try { + const bufTopic = Buffer.from(stringifiedTopic) + + this._pubsubDs.unsubscribe(bufTopic) + } catch (err) { + return callback(err) + } + + this._subscriptions[stringifiedTopic] = undefined + log(`unsubscribed pubsub ${stringifiedTopic}: ${name}`) + + callback(null, { + canceled: true + }) + } +} + +exports = module.exports = withIs(IpnsPubsubDatastore, { className: 'IpnsPubsubDatastore', symbolName: '@js-ipfs/ipns/IpnsPubsubDatastore' }) + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"class-is":187,"datastore-pubsub":211,"debug":456,"err-code":268,"ipns":605,"multihashes":1157}],547:[function(require,module,exports){ +'use strict' + +const multibase = require('multibase') +const ipns = require('ipns') + +module.exports = { + encodeBase32: (buf) => { + const m = multibase.encode('base32', buf).slice(1) // slice off multibase codec + + return m.toString().toUpperCase() // should be uppercase for interop with go + }, + validator: { + func: (key, record, cb) => ipns.validator.validate(record, key, cb) + }, + selector: (k, records) => ipns.validator.select(records[0], records[1]) +} + +},{"ipns":605,"multibase":1148}],548:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const setImmediate = require('async/setImmediate') +const log = debug('ipfs:mfs-preload') +log.error = debug('ipfs:mfs-preload:error') + +module.exports = (self) => { + const options = self._options.preload || {} + options.interval = options.interval || 30 * 1000 + + if (!options.enabled) { + log('MFS preload disabled') + return { + start: (cb) => setImmediate(cb), + stop: (cb) => setImmediate(cb) + } + } + + let rootCid + let timeoutId + + const preloadMfs = () => { + self.files.stat('/', (err, stats) => { + if (err) { + timeoutId = setTimeout(preloadMfs, options.interval) + return log.error('failed to stat MFS root for preload', err) + } + + if (rootCid !== stats.hash) { + log(`preloading updated MFS root ${rootCid} -> ${stats.hash}`) + + return self._preload(stats.hash, (err) => { + timeoutId = setTimeout(preloadMfs, options.interval) + if (err) return log.error(`failed to preload MFS root ${stats.hash}`, err) + rootCid = stats.hash + }) + } + + timeoutId = setTimeout(preloadMfs, options.interval) + }) + } + + return { + start (cb) { + self.files.stat('/', (err, stats) => { + if (err) return cb(err) + rootCid = stats.hash + log(`monitoring MFS root ${rootCid}`) + timeoutId = setTimeout(preloadMfs, options.interval) + cb() + }) + }, + stop (cb) { + clearTimeout(timeoutId) + cb() + } + } +} + +},{"async/setImmediate":96,"debug":456}],549:[function(require,module,exports){ +'use strict' + +const setImmediate = require('async/setImmediate') +const retry = require('async/retry') +const toUri = require('multiaddr-to-uri') +const debug = require('debug') +const CID = require('cids') +const shuffle = require('array-shuffle') +const preload = require('./runtime/preload-nodejs') + +const log = debug('ipfs:preload') +log.error = debug('ipfs:preload:error') + +const noop = (err) => { if (err) log.error(err) } + +module.exports = self => { + const options = self._options.preload || {} + options.enabled = Boolean(options.enabled) + options.addresses = options.addresses || [] + + if (!options.enabled || !options.addresses.length) { + log('preload disabled') + const api = (_, callback) => { + if (callback) { + setImmediate(() => callback()) + } + } + api.start = () => {} + api.stop = () => {} + return api + } + + let stopped = true + let requests = [] + const apiUris = options.addresses.map(toUri) + + const api = (path, callback) => { + callback = callback || noop + + if (typeof path !== 'string') { + try { + path = new CID(path).toBaseEncodedString() + } catch (err) { + return setImmediate(() => callback(err)) + } + } + + const fallbackApiUris = shuffle(apiUris) + let request + const now = Date.now() + + retry({ times: fallbackApiUris.length }, (cb) => { + if (stopped) return cb(new Error(`preload aborted for ${path}`)) + + // Remove failed request from a previous attempt + requests = requests.filter(r => r !== request) + + const apiUri = fallbackApiUris.shift() + + request = preload(`${apiUri}/api/v0/refs?r=true&arg=${encodeURIComponent(path)}`, cb) + requests = requests.concat(request) + }, (err) => { + requests = requests.filter(r => r !== request) + + if (err) { + return callback(err) + } + + log(`preloaded ${path} in ${Date.now() - now}ms`) + callback() + }) + } + + api.start = () => { + stopped = false + } + + api.stop = () => { + stopped = true + log(`canceling ${requests.length} pending preload request(s)`) + requests.forEach(r => r.cancel()) + requests = [] + } + + return api +} + +},{"./runtime/preload-nodejs":557,"array-shuffle":9,"async/retry":94,"async/setImmediate":96,"cids":185,"debug":456,"multiaddr-to-uri":1137}],550:[function(require,module,exports){ +'use strict' + +const callbackify = require('callbackify') + +module.exports = () => { + return callbackify(() => { + throw new Error('not available in the browser') + }) +} + +},{"callbackify":183}],551:[function(require,module,exports){ +'use strict' + +module.exports = () => ({ + Addresses: { + Swarm: [ + ], + API: '', + Gateway: '', + Delegates: [] + }, + Discovery: { + MDNS: { + Enabled: false, + Interval: 10 + }, + webRTCStar: { + Enabled: true + } + }, + Bootstrap: [ + '/dns4/ams-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd', + '/dns4/lon-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3', + '/dns4/sfo-3.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM', + '/dns4/sgp-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu', + '/dns4/nyc-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm', + '/dns4/nyc-2.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64', + '/dns4/node0.preload.ipfs.io/tcp/443/wss/ipfs/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic', + '/dns4/node1.preload.ipfs.io/tcp/443/wss/ipfs/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6' + ], + Pubsub: { + Enabled: true + }, + Swarm: { + ConnMgr: { + LowWater: 200, + HighWater: 500 + } + } +}) + +},{}],552:[function(require,module,exports){ +/* global self */ +'use strict' + +module.exports = (domain, opts, callback) => { + if (typeof opts === 'function') { + callback = opts + opts = {} + } + + opts = opts || {} + + domain = encodeURIComponent(domain) + let url = `https://ipfs.io/api/v0/dns?arg=${domain}` + + Object.keys(opts).forEach(prop => { + url += `&${encodeURIComponent(prop)}=${encodeURIComponent(opts[prop])}` + }) + + self.fetch(url, { mode: 'cors' }) + .then((response) => { + return response.json() + }) + .then((response) => { + if (response.Path) { + return callback(null, response.Path) + } else { + return callback(new Error(response.Message)) + } + }) + .catch((error) => { + callback(error) + }) +} + +},{}],553:[function(require,module,exports){ +/* eslint-env browser */ +'use strict' +module.exports = fetch + +},{}],554:[function(require,module,exports){ +'use strict' +const mergeOptions = require('merge-options') +const ipldDagCbor = require('ipld-dag-cbor') +const ipldDagPb = require('ipld-dag-pb') +const ipldRaw = require('ipld-raw') + +module.exports = (blockService, options = {}) => { + return mergeOptions.call( + // ensure we have the defaults formats even if the user overrides `formats: []` + { concatArrays: true }, + { + blockService: blockService, + formats: [ipldDagCbor, ipldDagPb, ipldRaw] + }, options) +} + +},{"ipld-dag-cbor":570,"ipld-dag-pb":589,"ipld-raw":599,"merge-options":1127}],555:[function(require,module,exports){ +'use strict' + +const WS = require('libp2p-websockets') +const WebRTCStar = require('libp2p-webrtc-star') +const WebSocketStarMulti = require('libp2p-websocket-star-multi') +const Multiplex = require('pull-mplex') +const SECIO = require('libp2p-secio') +const Bootstrap = require('libp2p-bootstrap') +const KadDHT = require('libp2p-kad-dht') +const GossipSub = require('libp2p-gossipsub') +const libp2p = require('libp2p') +const mergeOptions = require('merge-options') +const multiaddr = require('multiaddr') + +class Node extends libp2p { + constructor (_options) { + const wrtcstar = new WebRTCStar({ id: _options.peerInfo.id }) + + // this can be replaced once optional listening is supported with the below code. ref: https://github.com/libp2p/interface-transport/issues/41 + // const wsstar = new WebSocketStar({ id: _options.peerInfo.id }) + const wsstarServers = _options.peerInfo.multiaddrs.toArray().map(String).filter(addr => addr.includes('p2p-websocket-star')) + _options.peerInfo.multiaddrs.replace(wsstarServers.map(multiaddr), '/p2p-websocket-star') // the ws-star-multi module will replace this with the chosen ws-star servers + const wsstar = new WebSocketStarMulti({ servers: wsstarServers, id: _options.peerInfo.id, ignore_no_online: !wsstarServers.length || _options.wsStarIgnoreErrors }) + + const defaults = { + switch: { + denyTTL: 2 * 60 * 1e3, // 2 minute base + denyAttempts: 5, // back off 5 times + maxParallelDials: 100, + maxColdCalls: 25, + dialTimeout: 20e3 + }, + modules: { + transport: [ + WS, + wrtcstar, + wsstar + ], + streamMuxer: [ + Multiplex + ], + connEncryption: [ + SECIO + ], + peerDiscovery: [ + wrtcstar.discovery, + wsstar.discovery, + Bootstrap + ], + dht: KadDHT, + pubsub: GossipSub + }, + config: { + peerDiscovery: { + autoDial: true, + bootstrap: { + enabled: true + }, + webRTCStar: { + enabled: true + }, + websocketStar: { + enabled: true + } + }, + dht: { + enabled: false + }, + pubsub: { + enabled: true, + emitSelf: true + } + } + } + + super(mergeOptions(defaults, _options)) + } +} + +module.exports = Node + +},{"libp2p":1012,"libp2p-bootstrap":718,"libp2p-gossipsub":852,"libp2p-kad-dht":869,"libp2p-secio":969,"libp2p-webrtc-star":974,"libp2p-websocket-star-multi":978,"libp2p-websockets":987,"merge-options":1127,"multiaddr":1140,"pull-mplex":1301}],556:[function(require,module,exports){ +'use strict' + +module.exports = { + gossipsub: require('libp2p-gossipsub') +} + +},{"libp2p-gossipsub":852}],557:[function(require,module,exports){ +/* eslint-env browser */ +'use strict' + +const debug = require('debug') + +const log = debug('ipfs:preload') +log.error = debug('ipfs:preload:error') + +module.exports = function preload (url, callback) { + log(url) + + const controller = new AbortController() + const signal = controller.signal + + fetch(url, { signal }) + .then(res => { + if (!res.ok) { + log.error('failed to preload', url, res.status, res.statusText) + throw new Error(`failed to preload ${url}`) + } + return res.text() + }) + .then(() => callback()) + .catch(callback) + + return { + cancel: () => controller.abort() + } +} + +},{"debug":456}],558:[function(require,module,exports){ +'use strict' + +const IPFSRepo = require('ipfs-repo') + +module.exports = (dir) => { + const repoPath = dir || 'ipfs' + return new IPFSRepo(repoPath) +} + +},{"ipfs-repo":395}],559:[function(require,module,exports){ +'use strict' + +const debug = require('debug') +const log = debug('ipfs:state') +log.error = debug('ipfs:state:error') + +const fsm = require('fsm-event') + +module.exports = (self) => { + const s = fsm('uninitialized', { + uninitialized: { + init: 'initializing', + initialized: 'stopped' + }, + initializing: { + initialized: 'stopped' + }, + stopped: { + start: 'starting' + }, + starting: { + started: 'running' + }, + running: { + stop: 'stopping' + }, + stopping: { + stopped: 'stopped' + } + }) + + // log events + s.on('error', (err) => log.error(err)) + s.on('done', () => log('-> ' + s._state)) + + // -- Actions + + s.init = () => { + s('init') + } + + s.initialized = () => { + s('initialized') + } + + s.stop = () => { + s('stop') + } + + s.stopped = () => { + s('stopped') + } + + s.start = () => { + s('start') + } + + s.started = () => { + s('started') + } + + s.state = () => s._state + + return s +} + +},{"debug":456,"fsm-event":278}],560:[function(require,module,exports){ +'use strict' + +const promisify = require('promisify-es6') +const map = require('async/map') +const isIpfs = require('is-ipfs') +const CID = require('cids') + +const ERR_BAD_PATH = 'ERR_BAD_PATH' +exports.OFFLINE_ERROR = 'This command must be run in online mode. Try running \'ipfs daemon\' first.' + +/** + * Break an ipfs-path down into it's hash and an array of links. + * + * examples: + * b58Hash -> { hash: 'b58Hash', links: [] } + * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']} + * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] } + * + * @param {String} ipfsPath An ipfs-path + * @return {Object} { hash: base58 string, links: [string], ?err: Error } + * @throws on an invalid @param ipfsPath + */ +function parseIpfsPath (ipfsPath) { + const invalidPathErr = new Error('invalid ipfs ref path') + ipfsPath = ipfsPath.replace(/^\/ipfs\//, '') + const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/) + if (!matched) { + throw invalidPathErr + } + + const [hash, ...links] = matched[1].split('/') + + // check that a CID can be constructed with the hash + if (isIpfs.cid(hash)) { + return { hash, links } + } else { + throw invalidPathErr + } +} + +/** + * Returns a well-formed ipfs Path. + * The returned path will always be prefixed with /ipfs/ or /ipns/. + * If the received string is not a valid ipfs path, an error will be returned + * examples: + * b58Hash -> { hash: 'b58Hash', links: [] } + * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']} + * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] } + * + * @param {String} pathStr An ipfs-path, or ipns-path or a cid + * @return {String} ipfs-path or ipns-path + * @throws on an invalid @param ipfsPath + */ +const normalizePath = (pathStr) => { + if (isIpfs.cid(pathStr)) { + return `/ipfs/${pathStr}` + } else if (isIpfs.path(pathStr)) { + return pathStr + } else { + throw Object.assign(new Error(`invalid ${pathStr} path`), { code: ERR_BAD_PATH }) + } +} + +/** + * Resolve various styles of an ipfs-path to the hash of the target node. + * Follows links in the path. + * + * Accepts formats: + * - + * - /link/to/venus + * - /ipfs//link/to/pluto + * - multihash Buffer + * - Arrays of the above + * + * @param {IPFS} objectAPI The IPFS object api + * @param {Described above} ipfsPaths A single or collection of ipfs-paths + * @param {Function} callback res is Array + * if no callback is passed, returns a Promise + * @return {Promise|void} + */ +const resolvePath = promisify(function (objectAPI, ipfsPaths, callback) { + if (!Array.isArray(ipfsPaths)) { + ipfsPaths = [ipfsPaths] + } + + map(ipfsPaths, (path, cb) => { + if (typeof path !== 'string') { + let cid + + try { + cid = new CID(path) + } catch (err) { + return cb(err) + } + + return cb(null, cid.buffer) + } + + let parsedPath + try { + parsedPath = exports.parseIpfsPath(path) + } catch (err) { + return cb(err) + } + + const rootHash = new CID(parsedPath.hash) + const rootLinks = parsedPath.links + + if (!rootLinks.length) { + return cb(null, rootHash.buffer) + } + + objectAPI.get(rootHash, follow.bind(null, rootHash, rootLinks)) + + // recursively follow named links to the target node + function follow (cid, links, err, obj) { + if (err) { + return cb(err) + } + + if (!links.length) { + // done tracing, obj is the target node + return cb(null, cid.buffer) + } + + const linkName = links[0] + const nextObj = obj.Links.find(link => link.Name === linkName) + + if (!nextObj) { + return cb(new Error(`no link named "${linkName}" under ${cid}`)) + } + + objectAPI.get(nextObj.Hash, follow.bind(null, nextObj.Hash, links.slice(1))) + } + }, callback) +}) + +exports.normalizePath = normalizePath +exports.parseIpfsPath = parseIpfsPath +exports.resolvePath = resolvePath + +},{"async/map":87,"cids":185,"is-ipfs":614,"promisify-es6":1263}],561:[function(require,module,exports){ +'use strict' + +const CID = require('cids') + +/** +* Stringify a CID encoded in the requested base, upgrading to v1 if necessary. +* +* Setting upgrade to false will disable automatic CID upgrading from v0 to v1 +* which is necessary if the multibase is something other than base58btc. Note +* that it will also not apply the encoding (since v0 CIDs can only be encoded +* as base58btc). +* +* @param {CID|Buffer|String} cid The CID to encode +* @param {Object} [options] Optional options +* @param {String} [options.base] Name of multibase codec to encode the CID with +* @param {Boolean} [options.upgrade] Automatically upgrade v0 CIDs to v1 when +* necessary. Default: true. +* @returns {String} +*/ +exports.cidToString = (cid, options) => { + options = options || {} + options.upgrade = options.upgrade !== false + + if (!CID.isCID(cid)) { + cid = new CID(cid) + } + + if (cid.version === 0 && options.base && options.base !== 'base58btc') { + if (!options.upgrade) return cid.toString() + cid = cid.toV1() + } + + return cid.toBaseEncodedString(options.base) +} + +},{"cids":185}],562:[function(require,module,exports){ +'use strict' + +const assert = require('assert') +const mortice = require('mortice') +const noop = () => {} + +// Wrap mortice to present a callback interface +class Mutex { + constructor (repoOwner, options = {}) { + this.mutex = mortice(options.morticeId, { + singleProcess: repoOwner + }) + + this.log = options.log || noop + this.lockId = 0 + } + + readLock (lockedFn, cb) { + if (lockedFn && cb) { + this._lock('readLock').then(release => { + lockedFn((err, res) => { + release() + + cb(err, res) + }) + }, cb) + return + } + + return this._lock('readLock') + } + + writeLock (lockedFn, cb) { + if (lockedFn && cb) { + this._lock('writeLock').then(release => { + lockedFn((err, res) => { + release() + + cb(err, res) + }) + }, cb) + return + } + + return this._lock('writeLock') + } + + /** + * Request a read or write lock + * + * @param {String} type The type of lock: readLock / writeLock + * @returns {Promise} + */ + async _lock (type) { + assert(typeof type === 'string', `first argument to Mutex.${type}() must be a string, got ${typeof type}`) + + const lockId = this.lockId++ + this.log(`[${lockId}] ${type} requested`) + + // Get a Promise for the lock, wrap it for logging + const release = await this.mutex[type]() + + this.log(`[${lockId}] ${type} started`) + + return () => { + this.log(`[${lockId}] ${type} released`) + release() + } + } +} + +module.exports = Mutex + +},{"assert":26,"mortice":1133}],563:[function(require,module,exports){ +'use strict' +const hashlru = require('hashlru') + +/** + * Time Aware Least Recent Used Cache + * @see https://arxiv.org/pdf/1801.00390 + * @todo move this to ipfs-utils or it's own package + * + * @class TLRU + */ +class TLRU { + /** + * Creates an instance of TLRU. + * + * @param {number} maxSize + * @memberof TLRU + */ + constructor (maxSize) { + this.lru = hashlru(maxSize) + } + + /** + * Get the value from the a key + * + * @param {string} key + * @returns {any} + * @memberof TLRU + */ + get (key) { + const value = this.lru.get(key) + if (value) { + if ((value.expire) && (value.expire < Date.now())) { + this.lru.remove(key) + return undefined + } + } + return value.value + } + + /** + * Set a key value pair + * + * @param {string} key + * @param {any} value + * @param {number} ttl - in miliseconds + * @memberof TLRU + */ + set (key, value, ttl) { + this.lru.set(key, { value, expire: Date.now() + ttl }) + } + + /** + * Find if the cache has the key + * + * @param {string} key + * @returns {boolean} + * @memberof TLRU + */ + has (key) { + const value = this.get(key) + if (value) { + return true + } + return false + } + + /** + * Remove key + * + * @param {string} key + * @memberof TLRU + */ + remove (key) { + this.lru.remove(key) + } + + /** + * Clears the cache + * + * @memberof TLRU + */ + clear () { + this.lru.clear() + } +} + +module.exports = TLRU + +},{"hashlru":306}],564:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],565:[function(require,module,exports){ +arguments[4][412][0].apply(exports,arguments) +},{"blakejs":132,"buffer":181,"dup":412}],566:[function(require,module,exports){ +arguments[4][413][0].apply(exports,arguments) +},{"./blake":565,"./sha":568,"./utils":569,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],567:[function(require,module,exports){ +arguments[4][414][0].apply(exports,arguments) +},{"./crypto":566,"buffer":181,"dup":414,"err-code":564,"multihashes":1157}],568:[function(require,module,exports){ +arguments[4][415][0].apply(exports,arguments) +},{"buffer":181,"dup":415}],569:[function(require,module,exports){ +arguments[4][416][0].apply(exports,arguments) +},{"buffer":181,"dup":416}],570:[function(require,module,exports){ +'use strict' + +exports.util = require('./util.js') +exports.resolver = require('./resolver.js') +exports.codec = exports.util.codec +exports.defaultHashAlg = exports.util.defaultHashAlg + +},{"./resolver.js":571,"./util.js":572}],571:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') + +const util = require('./util') + +/** + * Resolves a path within a CBOR block. + * + * Returns the value or a link and the partial mising path. This way the + * IPLD Resolver can fetch the link and continue to resolve. + * + * @param {Buffer} binaryBlob - Binary representation of a CBOR block + * @param {string} [path='/'] - Path that should be resolved + * @returns {Object} result - Result of the path it it was resolved successfully + * @returns {*} result.value - Value the path resolves to + * @returns {string} result.remainderPath - If the path resolves half-way to a + * link, then the `remainderPath` is the part after the link that can be used + * for further resolving + */ +exports.resolve = (binaryBlob, path) => { + let node = util.deserialize(binaryBlob) + + const parts = path.split('/').filter(Boolean) + while (parts.length) { + const key = parts.shift() + if (node[key] === undefined) { + throw new Error(`Object has no property '${key}'`) + } + + node = node[key] + if (CID.isCID(node)) { + return { + value: node, + remainderPath: parts.join('/') + } + } + } + + return { + value: node, + remainderPath: '' + } +} + +const traverse = function * (node, path) { + // Traverse only objects and arrays + if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' || + node === null) { + return + } + for (const item of Object.keys(node)) { + const nextpath = path === undefined ? item : path + '/' + item + yield nextpath + yield * traverse(node[item], nextpath) + } +} + +/** + * Return all available paths of a block. + * + * @generator + * @param {Buffer} binaryBlob - Binary representation of a CBOR block + * @yields {string} - A single path + */ +exports.tree = function * (binaryBlob) { + const node = util.deserialize(binaryBlob) + + yield * traverse(node) +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608,"./util":572,"cids":185}],572:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const cbor = require('borc') +const multicodec = require('multicodec') +const multihashing = require('multihashing-async') +const CID = require('cids') +const isCircular = require('is-circular') + +// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692 +const CID_CBOR_TAG = 42 + +function tagCID (cid) { + if (typeof cid === 'string') { + cid = new CID(cid).buffer + } else if (CID.isCID(cid)) { + cid = cid.buffer + } + + return new cbor.Tagged(CID_CBOR_TAG, Buffer.concat([ + Buffer.from('00', 'hex'), // thanks jdag + cid + ])) +} + +function replaceCIDbyTAG (dagNode) { + let circular + try { + circular = isCircular(dagNode) + } catch (e) { + circular = false + } + if (circular) { + throw new Error('The object passed has circular references') + } + + function transform (obj) { + if (!obj || Buffer.isBuffer(obj) || typeof obj === 'string') { + return obj + } + + if (Array.isArray(obj)) { + return obj.map(transform) + } + + if (CID.isCID(obj)) { + return tagCID(obj) + } + + const keys = Object.keys(obj) + + if (keys.length > 0) { + // Recursive transform + const out = {} + keys.forEach((key) => { + if (typeof obj[key] === 'object') { + out[key] = transform(obj[key]) + } else { + out[key] = obj[key] + } + }) + return out + } else { + return obj + } + } + + return transform(dagNode) +} + +exports = module.exports + +exports.codec = multicodec.DAG_CBOR +exports.defaultHashAlg = multicodec.SHA2_256 + +const defaultTags = { + [CID_CBOR_TAG]: (val) => { + // remove that 0 + val = val.slice(1) + return new CID(val) + } +} +const defaultSize = 64 * 1024 // current decoder heap size, 64 Kb +let currentSize = defaultSize +const defaultMaxSize = 64 * 1024 * 1024 // max heap size when auto-growing, 64 Mb +let maxSize = defaultMaxSize +let decoder = null + +/** + * Configure the underlying CBOR decoder. + * + * @param {Object} [options] - The options the decoder takes. The decoder will reset to the defaul values if no options are given. + * @param {number} [options.size=65536] - The current heap size used in CBOR parsing, this may grow automatically as larger blocks are encountered up to `maxSize` + * @param {number} [options.maxSize=67108864] - The maximum size the CBOR parsing heap is allowed to grow to before `dagCBOR.util.deserialize()` returns an error + * @param {Object} [options.tags] - An object whose keys are CBOR tag numbers and values are transform functions that accept a `value` and return a decoded representation of that `value` + */ +exports.configureDecoder = (options) => { + let tags = defaultTags + + if (options) { + if (typeof options.size === 'number') { + currentSize = options.size + } + if (typeof options.maxSize === 'number') { + maxSize = options.maxSize + } + if (options.tags) { + tags = Object.assign({}, defaultTags, options && options.tags) + } + } else { + // no options, reset to defaults + currentSize = defaultSize + maxSize = defaultMaxSize + } + + let decoderOptions = { + tags: tags, + size: currentSize + } + + decoder = new cbor.Decoder(decoderOptions) + // borc edits opts.size in-place so we can capture _actual_ size + currentSize = decoderOptions.size +} + +exports.configureDecoder() // Setup default cbor.Decoder + +/** + * Serialize internal representation into a binary CBOR block. + * + * @param {Object} node - Internal representation of a CBOR block + * @returns {Buffer} - The encoded binary representation + */ +exports.serialize = (node) => { + const nodeTagged = replaceCIDbyTAG(node) + const serialized = cbor.encode(nodeTagged) + + return serialized +} + +/** + * Deserialize CBOR block into the internal representation. + * + * @param {Buffer} data - Binary representation of a CBOR block + * @returns {Object} - An object that conforms to the IPLD Data Model + */ +exports.deserialize = (data) => { + if (data.length > currentSize && data.length <= maxSize) { + exports.configureDecoder({ size: data.length }) + } + + if (data.length > currentSize) { + throw new Error('Data is too large to deserialize with current decoder') + } + + const deserialized = decoder.decodeFirst(data) + + return deserialized +} + +/** + * Calculate the CID of the binary blob. + * + * @param {Object} binaryBlob - Encoded IPLD Node + * @param {Object} [userOptions] - Options to create the CID + * @param {number} [userOptions.cidVersion=1] - CID version number + * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format + * @returns {Promise.} + */ +exports.cid = async (binaryBlob, userOptions) => { + const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg } + const options = Object.assign(defaultOptions, userOptions) + + const multihash = await multihashing(binaryBlob, options.hashAlg) + const codecName = multicodec.print[exports.codec] + const cid = new CID(options.cidVersion, codecName, multihash) + + return cid +} + +}).call(this,require("buffer").Buffer) +},{"borc":141,"buffer":181,"cids":185,"is-circular":609,"multicodec":1151,"multihashing-async":567}],573:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],574:[function(require,module,exports){ +arguments[4][412][0].apply(exports,arguments) +},{"blakejs":132,"buffer":181,"dup":412}],575:[function(require,module,exports){ +arguments[4][413][0].apply(exports,arguments) +},{"./blake":574,"./sha":577,"./utils":578,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],576:[function(require,module,exports){ +arguments[4][414][0].apply(exports,arguments) +},{"./crypto":575,"buffer":181,"dup":414,"err-code":573,"multihashes":1157}],577:[function(require,module,exports){ +arguments[4][415][0].apply(exports,arguments) +},{"buffer":181,"dup":415}],578:[function(require,module,exports){ +arguments[4][416][0].apply(exports,arguments) +},{"buffer":181,"dup":416}],579:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') +const assert = require('assert') +const withIs = require('class-is') +const visibility = require('../visibility') + +// Link represents an IPFS Merkle DAG Link between Nodes. +class DAGLink { + constructor (name, size, cid) { + assert(cid, 'A link requires a cid to point to') + // assert(size, 'A link requires a size') + // note - links should include size, but this assert is disabled + // for now to maintain consistency with go-ipfs pinset + + this._name = name || '' + this._nameBuf = null + this._size = size + this._cid = new CID(cid) + + // Make sure we have a nice public API that can be used by an IPLD resolver + visibility.hidePrivateFields(this) + visibility.addEnumerableGetters(this, ['Hash', 'Name', 'Tsize']) + } + + toString () { + return `DAGLink <${this._cid.toBaseEncodedString()} - name: "${this.Name}", size: ${this.Tsize}>` + } + + toJSON () { + if (!this._json) { + this._json = Object.freeze({ + name: this.Name, + size: this.Tsize, + cid: this.Hash.toBaseEncodedString() + }) + } + + return Object.assign({}, this._json) + } + + get Name () { + return this._name + } + + // Memoize the Buffer representation of name + // We need this to sort the links, otherwise + // we will reallocate new buffers every time + get nameAsBuffer () { + if (this._nameBuf !== null) { + return this._nameBuf + } + + this._nameBuf = Buffer.from(this._name) + return this._nameBuf + } + + set Name (name) { + throw new Error("Can't set property: 'name' is immutable") + } + + get Tsize () { + return this._size + } + + set Tsize (size) { + throw new Error("Can't set property: 'size' is immutable") + } + + get Hash () { + return this._cid + } + + set Hash (cid) { + throw new Error("Can't set property: 'cid' is immutable") + } +} + +exports = module.exports = withIs(DAGLink, { className: 'DAGLink', symbolName: '@ipld/js-ipld-dag-pb/daglink' }) +exports.util = require('./util') + +}).call(this,require("buffer").Buffer) +},{"../visibility":592,"./util":580,"assert":26,"buffer":181,"cids":185,"class-is":187}],580:[function(require,module,exports){ +'use strict' + +const DAGLink = require('./index') + +function createDagLinkFromB58EncodedHash (link) { + return new DAGLink( + link.Name || link.name || '', + link.Tsize || link.Size || link.size || 0, + link.Hash || link.hash || link.multihash || link.cid + ) +} + +exports = module.exports +exports.createDagLinkFromB58EncodedHash = createDagLinkFromB58EncodedHash + +},{"./index":579}],581:[function(require,module,exports){ +'use strict' + +const dagNodeUtil = require('./util') +const cloneLinks = dagNodeUtil.cloneLinks +const cloneData = dagNodeUtil.cloneData +const toDAGLink = dagNodeUtil.toDAGLink +const DAGLink = require('../dag-link') +const DAGNode = require('./index') +const create = require('./create') + +const asDAGLink = async (link) => { + if (DAGLink.isDAGLink(link)) { + // It's a DAGLink instance + // no need to do anything + return link + } + + if (DAGNode.isDAGNode(link)) { + // It's a DAGNode instance + // convert to link + return toDAGLink(link, {}) + } + + // It's a Object with name, multihash/hash/cid and size + return new DAGLink(link.Name || link.name, link.Tsize || link.size, link.Hash || link.multihash || link.hash || link.cid) +} + +const addLink = async (node, link) => { + const links = cloneLinks(node) + const data = cloneData(node) + + const dagLink = await asDAGLink(link) + links.push(dagLink) + return create(data, links) +} + +module.exports = addLink + +},{"../dag-link":579,"./create":584,"./index":585,"./util":587}],582:[function(require,module,exports){ +'use strict' + +/** + * Adds a link with its name as property to an object. + * + * The link won't be added if its name is empty or matches one of the existing + * properties. + * + * @param {Object} object - The object that contains an array of links + * @param {string} name - The name of the link to add + * @param {numner} position - The position within the array of links + */ +const addNamedLink = (object, name, position) => { + const skipNames = ['', ...Object.keys(object)] + if (skipNames.includes(name)) { + return + } + Object.defineProperty(object, name, { + enumerable: true, + configurable: true, + get: () => object._links[position].Hash + }) +} + +module.exports = addNamedLink + +},{}],583:[function(require,module,exports){ +'use strict' + +const dagNodeUtil = require('./util') +const cloneLinks = dagNodeUtil.cloneLinks +const cloneData = dagNodeUtil.cloneData +const create = require('./create') + +function clone (dagNode) { + const data = cloneData(dagNode) + const links = cloneLinks(dagNode) + return create(data, links) +} + +module.exports = clone + +},{"./create":584,"./util":587}],584:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const sort = require('stable') +const { + serialize +} = require('../util.js') +const dagNodeUtil = require('./util.js') +const linkSort = dagNodeUtil.linkSort +const DAGNode = require('./index.js') +const DAGLink = require('../dag-link') + +const create = (data, links = []) => { + if (typeof data === 'string') { + data = Buffer.from(data) + } + + if (!Buffer.isBuffer(data)) { + throw new Error('Passed \'data\' is not a buffer or a string!') + } + links = links.map((link) => { + return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link) + }) + links = sort(links, linkSort) + + const serialized = serialize({ + Data: data, + Links: links + }) + + return new DAGNode(data, links, serialized.length) +} + +module.exports = create + +}).call(this,require("buffer").Buffer) +},{"../dag-link":579,"../util.js":591,"./index.js":585,"./util.js":587,"buffer":181,"stable":1458}],585:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const assert = require('assert') +const withIs = require('class-is') +const addNamedLink = require('./addNamedLink') +const visibility = require('../visibility') + +class DAGNode { + constructor (data, links, serializedSize) { + if (serializedSize !== 0) { + assert(serializedSize, 'A DAGNode requires it\'s serialized size') + } + + this._data = data || Buffer.alloc(0) + this._links = links + this._serializedSize = serializedSize + + // Make sure we have a nice public API that can be used by an IPLD resolver + visibility.hidePrivateFields(this) + visibility.addEnumerableGetters(this, ['Data', 'Links']) + + // Add getters for existing links by the name of the link + // This is how paths are traversed in IPFS. Links with names won't + // override existing fields like `data` or `links`. + links.forEach((link, position) => { + addNamedLink(this, link.Name, position) + }) + } + + toJSON () { + if (!this._json) { + this._json = Object.freeze({ + data: this.Data, + links: this._links.map((l) => l.toJSON()), + size: this.size + }) + } + + return Object.assign({}, this._json) + } + + toString () { + return `DAGNode ` + } + + get size () { + if (this._size === undefined) { + this._size = this._links.reduce((sum, l) => sum + l.Tsize, this._serializedSize) + } + + return this._size + } + + set size (size) { + throw new Error("Can't set property: 'size' is immutable") + } + + // Getters for backwards compatible path resolving + get Data () { + return this._data + } + set Data (_) { + throw new Error("Can't set property: 'Data' is immutable") + } + get Links () { + return this._links.map((link) => { + return { + Name: link.Name, + Tsize: link.Tsize, + Hash: link.Hash + } + }) + } + set Links (_) { + throw new Error("Can't set property: 'Links' is immutable") + } +} + +exports = module.exports = withIs(DAGNode, { className: 'DAGNode', symbolName: '@ipld/js-ipld-dag-pb/dagnode' }) +exports.create = require('./create') +exports.clone = require('./clone') +exports.addLink = require('./addLink') +exports.rmLink = require('./rmLink') + +}).call(this,require("buffer").Buffer) +},{"../visibility":592,"./addLink":581,"./addNamedLink":582,"./clone":583,"./create":584,"./rmLink":586,"assert":26,"buffer":181,"class-is":187}],586:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const dagNodeUtil = require('./util') +const cloneLinks = dagNodeUtil.cloneLinks +const cloneData = dagNodeUtil.cloneData +const create = require('./create') +const CID = require('cids') + +const rmLink = (dagNode, nameOrCid) => { + const data = cloneData(dagNode) + let links = cloneLinks(dagNode) + + if (typeof nameOrCid === 'string') { + links = links.filter((link) => link.Name !== nameOrCid) + } else if (Buffer.isBuffer(nameOrCid) || CID.isCID(nameOrCid)) { + links = links.filter((link) => !link.Hash.equals(nameOrCid)) + } else { + throw new Error('second arg needs to be a name or CID') + } + + return create(data, links) +} + +module.exports = rmLink + +}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) +},{"../../../is-buffer/index.js":608,"./create":584,"./util":587,"cids":185}],587:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const DAGLink = require('./../dag-link') +const { + cid, + serialize +} = require('../util') + +exports = module.exports + +function cloneData (dagNode) { + let data + + if (dagNode.Data && dagNode.Data.length > 0) { + data = Buffer.alloc(dagNode.Data.length) + dagNode.Data.copy(data) + } else { + data = Buffer.alloc(0) + } + + return data +} + +function cloneLinks (dagNode) { + return dagNode.Links.slice() +} + +function linkSort (a, b) { + return Buffer.compare(a.nameAsBuffer, b.nameAsBuffer) +} + +/* + * toDAGLink converts a DAGNode to a DAGLink + */ +const toDAGLink = async (node, options = {}) => { + const serialized = serialize(node) + const nodeCid = await cid(serialized) + return new DAGLink(options.name || '', serialized.length, nodeCid) +} + +exports.cloneData = cloneData +exports.cloneLinks = cloneLinks +exports.linkSort = linkSort +exports.toDAGLink = toDAGLink + +}).call(this,require("buffer").Buffer) +},{"../util":591,"./../dag-link":579,"buffer":181}],588:[function(require,module,exports){ +'use strict' + +module.exports = `// An IPFS MerkleDAG Link +message PBLink { + + // multihash of the target object + optional bytes Hash = 1; + + // utf string name. should be unique per object + optional string Name = 2; + + // cumulative size of target object + optional uint64 Tsize = 3; +} + +// An IPFS MerkleDAG Node +message PBNode { + + // refs to other objects + repeated PBLink Links = 2; + + // opaque user data + optional bytes Data = 1; +}` + +},{}],589:[function(require,module,exports){ +'use strict' + +exports.DAGNode = require('./dag-node') +exports.DAGLink = require('./dag-link') + +/* + * Functions to fulfil IPLD Format interface + * https://github.com/ipld/interface-ipld-format + */ +exports.resolver = require('./resolver') +exports.util = require('./util') +exports.codec = exports.util.codec +exports.defaultHashAlg = exports.util.defaultHashAlg + +},{"./dag-link":579,"./dag-node":585,"./resolver":590,"./util":591}],590:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') + +const util = require('./util') + +/** + * Resolves a path within a PB block. + * + * Returns the value or a link and the partial mising path. This way the + * IPLD Resolver can fetch the link and continue to resolve. + * + * @param {Buffer} binaryBlob - Binary representation of a PB block + * @param {string} [path='/'] - Path that should be resolved + * @returns {Object} result - Result of the path it it was resolved successfully + * @returns {*} result.value - Value the path resolves to + * @returns {string} result.remainderPath - If the path resolves half-way to a + * link, then the `remainderPath` is the part after the link that can be used + * for further resolving + */ +exports.resolve = (binaryBlob, path) => { + let node = util.deserialize(binaryBlob) + + const parts = path.split('/').filter(Boolean) + while (parts.length) { + const key = parts.shift() + if (node[key] === undefined) { + throw new Error(`Object has no property '${key}'`) + } + + node = node[key] + if (CID.isCID(node)) { + return { + value: node, + remainderPath: parts.join('/') + } + } + } + + return { + value: node, + remainderPath: '' + } +} + +const traverse = function * (node, path) { + // Traverse only objects and arrays + if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' || + node === null) { + return + } + for (const item of Object.keys(node)) { + const nextpath = path === undefined ? item : path + '/' + item + yield nextpath + yield * traverse(node[item], nextpath) + } +} + +/** + * Return all available paths of a block. + * + * @generator + * @param {Buffer} binaryBlob - Binary representation of a PB block + * @yields {string} - A single path + */ +exports.tree = function * (binaryBlob) { + const node = util.deserialize(binaryBlob) + + yield * traverse(node) +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608,"./util":591,"cids":185}],591:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const CID = require('cids') +const protons = require('protons') +const proto = protons(require('./dag.proto.js')) +const DAGLink = require('./dag-link') +const DAGNode = require('./dag-node') +const multicodec = require('multicodec') +const multihashing = require('multihashing-async') + +exports = module.exports + +exports.codec = multicodec.DAG_PB +exports.defaultHashAlg = multicodec.SHA2_256 + +/** + * Calculate the CID of the binary blob. + * + * @param {Object} binaryBlob - Encoded IPLD Node + * @param {Object} [userOptions] - Options to create the CID + * @param {number} [userOptions.cidVersion=1] - CID version number + * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format + * @returns {Promise.} + */ +const cid = async (binaryBlob, userOptions) => { + const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg } + const options = Object.assign(defaultOptions, userOptions) + + const multihash = await multihashing(binaryBlob, options.hashAlg) + const codecName = multicodec.print[exports.codec] + const cid = new CID(options.cidVersion, codecName, multihash) + + return cid +} + +/** + * Serialize internal representation into a binary PB block. + * + * @param {Object} node - Internal representation of a CBOR block + * @returns {Buffer} - The encoded binary representation + */ +const serialize = (node) => { + let data = node.Data + let links = node.Links || [] + + // If the node is not an instance of a DAGNode, the link.hash might be a Base58 encoded string; decode it + if (!DAGNode.isDAGNode(node) && links) { + links = links.map((link) => { + return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link) + }) + } + + const serialized = proto.PBNode.encode(toProtoBuf({ + Data: data, + Links: links + })) + + return serialized +} + +/** + * Deserialize PB block into the internal representation. + * + * @param {Buffer} buffer - Binary representation of a PB block + * @returns {Object} - An object that conforms to the IPLD Data Model + */ +const deserialize = (buffer) => { + const pbn = proto.PBNode.decode(buffer) + + const links = pbn.Links.map((link) => { + return new DAGLink(link.Name, link.Tsize, link.Hash) + }) + + const data = pbn.Data == null ? Buffer.alloc(0) : pbn.Data + + return new DAGNode(data, links, buffer.length) +} + +function toProtoBuf (node) { + const pbn = {} + + if (node.Data && node.Data.length > 0) { + pbn.Data = node.Data + } else { + // NOTE: this has to be null in order to match go-ipfs serialization `null !== new Buffer(0)` + pbn.Data = null + } + + if (node.Links && node.Links.length > 0) { + pbn.Links = node.Links + .map((link) => ({ + Hash: link.Hash.buffer, + Name: link.Name, + Tsize: link.Tsize + })) + } else { + pbn.Links = null + } + + return pbn +} + +exports.serialize = serialize +exports.deserialize = deserialize +exports.cid = cid + +}).call(this,require("buffer").Buffer) +},{"./dag-link":579,"./dag-node":585,"./dag.proto.js":588,"buffer":181,"cids":185,"multicodec":1151,"multihashing-async":576,"protons":1274}],592:[function(require,module,exports){ +'use strict' + +/** + * Make certain getters enumnerable + * + * This can be used to add additional getters that are enumerable and hence + * show up on an `Object.keys()` call. + * + * @param {Object} object - The object it should be applied to + * @param {Array.} fields - The fields that should be made enumnerable + */ +const addEnumerableGetters = (object, fields) => { + for (const field of fields) { + let prop + let proto = object + // Walk up the proottype chain until a property with the given name is + // found + while (prop === undefined) { + proto = Object.getPrototypeOf(proto) + if (proto === null) { + throw new Error(`no getter named '${field}' found`) + } + prop = Object.getOwnPropertyDescriptor(proto, field) + } + + // There is a property with the correct name, but it's not a getter + if (prop.get === undefined) { + throw new Error(`no getter named '${field}' found`) + } + Object.defineProperty(object, field, { + enumerable: true, + get: prop.get + }) + } +} + +/** + * Makes all properties with a leading underscore non-enumerable. + * + * @param {Object} object - The object it should be applied to + */ +const hidePrivateFields = (object) => { + for (const key in object) { + if (key[0] === '_') { + Object.defineProperty(object, key, { enumerable: false }) + } + } +} + +module.exports = { + addEnumerableGetters, + hidePrivateFields +} + +},{}],593:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],594:[function(require,module,exports){ +arguments[4][412][0].apply(exports,arguments) +},{"blakejs":132,"buffer":181,"dup":412}],595:[function(require,module,exports){ +arguments[4][413][0].apply(exports,arguments) +},{"./blake":594,"./sha":597,"./utils":598,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],596:[function(require,module,exports){ +arguments[4][414][0].apply(exports,arguments) +},{"./crypto":595,"buffer":181,"dup":414,"err-code":593,"multihashes":1157}],597:[function(require,module,exports){ +arguments[4][415][0].apply(exports,arguments) +},{"buffer":181,"dup":415}],598:[function(require,module,exports){ +arguments[4][416][0].apply(exports,arguments) +},{"buffer":181,"dup":416}],599:[function(require,module,exports){ +'use strict' +const CID = require('cids') +const multihashing = require('multihashing-async') +const multicodec = require('multicodec') + +// binary resolver +module.exports = { + codec: multicodec.RAW, + defaultHashAlg: multicodec.SHA2_256, + resolver: { + /** + * Resolves a path within a Raw block. + * + * Always returns the raw data as value without any remainderPath. + * + * @param {Buffer} binaryBlob - Binary representation of a PB block + * @param {string} [path='/'] - Path that should be resolved (that value is ignored) + * @returns {Object} result - Result of the path it it was resolved successfully + * @returns {*} result.value - The raw data + * @returns {string} result.remainderPath - An empty string + */ + resolve: (binaryBlob, path) => { + return { + value: binaryBlob, + remainderPath: '' + } + }, + /** + * Return all available paths of a block. + * + * @generator + * @param {Buffer} binaryBlob - The raw data + * @returns {Object} - Finished generator with `done: true` + */ + tree: (binaryBlob) => { + return { + done: true + } + } + }, + util: { + deserialize: (data) => { + return data + }, + serialize: (data) => { + return data + }, + /** + * Calculate the CID of the binary blob. + * + * @param {Object} binaryBlob - Encoded IPLD Node + * @param {Object} [userOptions] - Options to create the CID + * @param {number} [userOptions.cidVersion=1] - CID version number + * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format + * @returns {Promise.} + */ + cid: async (binaryBlob, userOptions) => { + const defaultOptions = { cidVersion: 1, hashAlg: module.exports.defaultHashAlg } + const options = Object.assign(defaultOptions, userOptions) + + const multihash = await multihashing(binaryBlob, options.hashAlg) + const codecName = multicodec.print[module.exports.codec] + const cid = new CID(options.cidVersion, codecName, multihash) + + return cid + } + } +} + +},{"cids":185,"multicodec":1151,"multihashing-async":596}],600:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const Block = require('ipfs-block') +const CID = require('cids') +const mergeOptions = require('merge-options') +const ipldDagCbor = require('ipld-dag-cbor') +const ipldDagPb = require('ipld-dag-pb') +const ipldRaw = require('ipld-raw') +const multicodec = require('multicodec') +const promisify = require('promisify-es6') +const typical = require('typical') +const { extendIterator } = require('./util') + +class IPLDResolver { + constructor (userOptions) { + const options = mergeOptions(IPLDResolver.defaultOptions, userOptions) + + if (!options.blockService) { + throw new Error('Missing blockservice') + } + this.bs = options.blockService + + // Object with current list of active resolvers + this.resolvers = {} + + if (typeof options.loadFormat !== 'function') { + this.loadFormat = async (codec) => { + const codecName = multicodec.print[codec] + throw new Error(`No resolver found for codec "${codecName}"`) + } + } else { + this.loadFormat = options.loadFormat + } + + // Enable all supplied formats + for (const format of options.formats) { + this.addFormat(format) + } + } + + /** + * Add support for an IPLD Format. + * + * @param {Object} format - The implementation of an IPLD Format. + * @returns {this} + */ + addFormat (format) { + const codec = format.codec + if (this.resolvers[format.format]) { + const codecName = multicodec.print[codec] + throw new Error(`Resolver already exists for codec "${codecName}"`) + } + + this.resolvers[codec] = format + + return this + } + + /** + * Remove support for an IPLD Format. + * + * @param {number} codec - The codec of the IPLD Format to remove. + * @returns {this} + */ + removeFormat (codec) { + if (this.resolvers[codec]) { + delete this.resolvers[codec] + } + + return this + } + + /** + * Retrieves IPLD Nodes along the `path` that is rooted at `cid`. + * + * @param {CID} cid - the CID the resolving starts. + * @param {string} path - the path that should be resolved. + * @returns {Iterable.>} - Returns an async iterator of all the IPLD Nodes that were traversed during the path resolving. Every element is an object with these fields: + * - `remainderPath`: the part of the path that wasn’t resolved yet. + * - `value`: the value where the resolved path points to. If further traversing is possible, then the value is a CID object linking to another IPLD Node. If it was possible to fully resolve the path, value is the value the path points to. So if you need the CID of the IPLD Node you’re currently at, just take the value of the previously returned IPLD Node. + */ + resolve (cid, path) { + if (!CID.isCID(cid)) { + throw new Error('`cid` argument must be a CID') + } + if (typeof path !== 'string') { + throw new Error('`path` argument must be a string') + } + + const generator = async function * () { + // End iteration if there isn't a CID to follow anymore + while (cid !== null) { + const format = await this._getFormat(cid.codec) + + // get block + // use local resolver + // update path value + const block = await promisify(this.bs.get.bind(this.bs))(cid) + const result = format.resolver.resolve(block.data, path) + + // Prepare for the next iteration if there is a `remainderPath` + path = result.remainderPath + let value = result.value + // NOTE vmx 2018-11-29: Not all IPLD Formats return links as + // CIDs yet. Hence try to convert old style links to CIDs + if (Object.keys(value).length === 1 && '/' in value) { + try { + value = new CID(value['/']) + } catch (_error) { + value = null + } + } + cid = CID.isCID(value) ? value : null + + yield { + remainderPath: path, + value + } + } + }.bind(this) + + return extendIterator(generator()) + } + + /** + * Get a node by CID. + * + * @param {CID} cid - The CID of the IPLD Node that should be retrieved. + * @returns {Promise.} - Returns a Promise with the IPLD Node that correspond to the given `cid`. + */ + async get (cid) { + const block = await promisify(this.bs.get.bind(this.bs))(cid) + const format = await this._getFormat(block.cid.codec) + const node = format.util.deserialize(block.data) + + return node + } + + /** + * Get multiple nodes back from an array of CIDs. + * + * @param {Iterable.} cids - The CIDs of the IPLD Nodes that should be retrieved. + * @returns {Iterable.>} - Returns an async iterator with the IPLD Nodes that correspond to the given `cids`. + */ + getMany (cids) { + if (!typical.isIterable(cids) || typeof cids === 'string' || + Buffer.isBuffer(cids)) { + throw new Error('`cids` must be an iterable of CIDs') + } + + const generator = async function * () { + for await (const cid of cids) { + yield this.get(cid) + } + }.bind(this) + + return extendIterator(generator()) + } + + /** + * Stores the given IPLD Node of a recognized IPLD Format. + * + * @param {Object} node - The deserialized IPLD node that should be inserted. + * @param {number} format - The multicodec of the format that IPLD Node should be encoded in. + * @param {Object} [userOptions] - Options is an object with the following properties. + * @param {number} [userOtions.hashAlg=hash algorithm of the given multicodec] - The hashing algorithm that is used to calculate the CID. + * @param {number} [userOptions.cidVersion=1] - The CID version to use. + * @param {boolean} [userOptions.onlyHash=false] - If true the serialized form of the IPLD Node will not be passed to the underlying block store. + * @returns {Promise.} - Returns the CID of the serialized IPLD Nodes. + */ + async put (node, format, userOptions) { + if (format === undefined) { + throw new Error('`put` requires a format') + } + if (typeof format !== 'number') { + throw new Error('`format` parameter must be number (multicodec)') + } + + const formatImpl = await this._getFormat(format) + const defaultOptions = { + hashAlg: formatImpl.defaultHashAlg, + cidVersion: 1, + onlyHash: false + } + const options = mergeOptions(defaultOptions, userOptions) + + const cidOptions = { + cidVersion: options.cidVersion, + hashAlg: options.hashAlg, + onlyHash: options.onlyHash + } + const serialized = formatImpl.util.serialize(node) + const cid = await formatImpl.util.cid(serialized, cidOptions) + + if (!options.onlyHash) { + const block = new Block(serialized, cid) + await promisify(this.bs.put.bind(this.bs))(block) + } + + return cid + } + + /** + * Stores the given IPLD Nodes of a recognized IPLD Format. + * + * @param {Iterable.} nodes - Deserialized IPLD nodes that should be inserted. + * @param {number} format - The multicodec of the format that IPLD Node should be encoded in. + * @param {Object} [userOptions] - Options are applied to any of the `nodes` and is an object with the following properties. + * @param {number} [userOtions.hashAlg=hash algorithm of the given multicodec] - The hashing algorithm that is used to calculate the CID. + * @param {number} [userOptions.cidVersion=1] - The CID version to use. + * @param {boolean} [userOptions.onlyHash=false] - If true the serialized form of the IPLD Node will not be passed to the underlying block store. + * @returns {Iterable.>} - Returns an async iterator with the CIDs of the serialized IPLD Nodes. + */ + putMany (nodes, format, userOptions) { + if (!typical.isIterable(nodes) || typeof nodes === 'string' || + Buffer.isBuffer(nodes)) { + throw new Error('`nodes` must be an iterable') + } + if (format === undefined) { + throw new Error('`put` requires a format') + } + if (typeof format !== 'number') { + throw new Error('`format` parameter must be number (multicodec)') + } + + let options + let formatImpl + + const generator = async function * () { + for await (const node of nodes) { + // Lazy load the options not when the iterator is initialized, but + // when we hit the first iteration. This way the constructor can be + // a synchronous function. + if (options === undefined) { + formatImpl = await this._getFormat(format) + const defaultOptions = { + hashAlg: formatImpl.defaultHashAlg, + cidVersion: 1, + onlyHash: false + } + options = mergeOptions(defaultOptions, userOptions) + } + + yield this.put(node, format, options) + } + }.bind(this) + + return extendIterator(generator()) + } + + /** + * Remove an IPLD Node by the given CID. + * + * @param {CID} cid - The CID of the IPLD Node that should be removed. + * @return {Promise.} The CID of the removed IPLD Node. + */ + async remove (cid) { + return promisify(this.bs.delete.bind(this.bs))(cid) + } + + /** + * Remove IPLD Nodes by the given CIDs. + * + * Throws an error if any of the Blocks can’t be removed. This operation is + * *not* atomic, some Blocks might have already been removed. + * + * @param {Iterable.} cids - The CIDs of the IPLD Nodes that should be removed. + * @return {Iterable.>} Returns an async iterator with the CIDs of the removed IPLD Nodes. + */ + removeMany (cids) { + if (!typical.isIterable(cids) || typeof cids === 'string' || + Buffer.isBuffer(cids)) { + throw new Error('`cids` must be an iterable of CIDs') + } + + const generator = async function * () { + for await (const cid of cids) { + yield this.remove(cid) + } + }.bind(this) + + return extendIterator(generator()) + } + + /** + * Returns all the paths that can be resolved into. + * + * @param {Object} cid - The ID to get the paths from + * @param {string} [offsetPath=''] - the path to start to retrieve the other paths from. + * @param {Object} [userOptions] + * @param {number} [userOptions.recursive=false] - whether to get the paths recursively or not. `false` resolves only the paths of the given CID. + * @returns {Iterable.>} - Returns an async iterator with paths that can be resolved into + */ + tree (cid, offsetPath, userOptions) { + if (typeof offsetPath === 'object') { + userOptions = offsetPath + offsetPath = undefined + } + offsetPath = offsetPath || '' + + const defaultOptions = { + recursive: false + } + const options = mergeOptions(defaultOptions, userOptions) + + // If a path is a link then follow it and return its CID + const maybeRecurse = async (block, treePath) => { + // A treepath we might want to follow recursively + const format = await this._getFormat(block.cid.codec) + const result = format.resolver.resolve(block.data, treePath) + // Something to follow recusively, hence push it into the queue + if (CID.isCID(result.value)) { + return result.value + } else { + return null + } + } + + const generator = async function * () { + // The list of paths that will get returned + const treePaths = [] + // The current block, needed to call `isLink()` on every interation + let block + // The list of items we want to follow recursively. The items are + // an object consisting of the CID and the currently already resolved + // path + const queue = [{ cid, basePath: '' }] + // The path that was already traversed + let basePath + + // End of iteration if there aren't any paths left to return or + // if we don't want to traverse recursively and have already + // returne the first level + while (treePaths.length > 0 || queue.length > 0) { + // There aren't any paths left, get them from the given CID + if (treePaths.length === 0 && queue.length > 0) { + ({ cid, basePath } = queue.shift()) + const format = await this._getFormat(cid.codec) + block = await promisify(this.bs.get.bind(this.bs))(cid) + + const paths = format.resolver.tree(block.data) + treePaths.push(...paths) + } + + const treePath = treePaths.shift() + let fullPath = basePath + treePath + + // Only follow links if recursion is intended + if (options.recursive) { + cid = await maybeRecurse(block, treePath) + if (cid !== null) { + queue.push({ cid, basePath: fullPath + '/' }) + } + } + + // Return it if it matches the given offset path, but is not the + // offset path itself + if (fullPath.startsWith(offsetPath) && + fullPath.length > offsetPath.length) { + if (offsetPath.length > 0) { + fullPath = fullPath.slice(offsetPath.length + 1) + } + + yield fullPath + } + } + }.bind(this) + + return extendIterator(generator()) + } + + /* */ + /* internals */ + /* */ + async _getFormat (codec) { + // TODO vmx 2019-01-24: Once all CIDs support accessing the codec code + // instead of the name, remove this part + if (typeof codec === 'string') { + const constantName = codec.toUpperCase().replace(/-/g, '_') + codec = multicodec[constantName] + } + + if (this.resolvers[codec]) { + return this.resolvers[codec] + } + + // If not supported, attempt to dynamically load this format + const format = await this.loadFormat(codec) + this.addFormat(format) + return format + } +} + +/** + * Default options for IPLD. + */ +IPLDResolver.defaultOptions = { + formats: [ipldDagCbor, ipldDagPb, ipldRaw] +} + +module.exports = IPLDResolver + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608,"./util":601,"cids":185,"ipfs-block":353,"ipld-dag-cbor":570,"ipld-dag-pb":589,"ipld-raw":599,"merge-options":1127,"multicodec":1151,"promisify-es6":1263,"typical":1505}],601:[function(require,module,exports){ +'use strict' + +exports.first = async (iterator) => { + for await (const value of iterator) { + return value + } +} + +exports.last = async (iterator) => { + let value + for await (value of iterator) { + // Intentionally empty + } + return value +} + +exports.all = async (iterator) => { + const values = [] + for await (const value of iterator) { + values.push(value) + } + return values +} + +exports.extendIterator = (iterator) => { + iterator.first = () => exports.first(iterator) + iterator.last = () => exports.last(iterator) + iterator.all = () => exports.all(iterator) + return iterator +} + +},{}],602:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":603,"_process":1258,"dup":208}],603:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],604:[function(require,module,exports){ +'use strict' + +exports.ERR_IPNS_EXPIRED_RECORD = 'ERR_IPNS_EXPIRED_RECORD' +exports.ERR_UNRECOGNIZED_VALIDITY = 'ERR_UNRECOGNIZED_VALIDITY' +exports.ERR_SIGNATURE_CREATION = 'ERR_SIGNATURE_CREATION' +exports.ERR_SIGNATURE_VERIFICATION = 'ERR_SIGNATURE_VERIFICATION' +exports.ERR_UNRECOGNIZED_FORMAT = 'ERR_UNRECOGNIZED_FORMAT' +exports.ERR_PEER_ID_FROM_PUBLIC_KEY = 'ERR_PEER_ID_FROM_PUBLIC_KEY' +exports.ERR_PUBLIC_KEY_FROM_ID = 'ERR_PUBLIC_KEY_FROM_ID' +exports.ERR_UNDEFINED_PARAMETER = 'ERR_UNDEFINED_PARAMETER' + +},{}],605:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const base32Encode = require('base32-encode') +const NanoDate = require('timestamp-nano') +const { Key } = require('interface-datastore') +const crypto = require('libp2p-crypto') +const PeerId = require('peer-id') +const multihash = require('multihashes') + +const debug = require('debug') +const log = debug('jsipns') +log.error = debug('jsipns:error') + +const ipnsEntryProto = require('./pb/ipns.proto') +const { parseRFC3339 } = require('./utils') +const ERRORS = require('./errors') + +const ID_MULTIHASH_CODE = multihash.names.id + +const namespace = '/ipns/' + +/** + * Creates a new ipns entry and signs it with the given private key. + * The ipns entry validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision. + * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`. + * + * @param {Object} privateKey private key for signing the record. + * @param {string} value value to be stored in the record. + * @param {number} seq number representing the current version of the record. + * @param {number|string} lifetime lifetime of the record (in milliseconds). + * @param {function(Error, entry)} [callback] + */ +const create = (privateKey, value, seq, lifetime, callback) => { + // Validity in ISOString with nanoseconds precision and validity type EOL + const isoValidity = new NanoDate(Date.now() + Number(lifetime)).toString() + const validityType = ipnsEntryProto.ValidityType.EOL + _create(privateKey, value, seq, isoValidity, validityType, callback) +} + +/** + * Same as create(), but instead of generating a new Date, it receives the intended expiration time + * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided. + * @param {Object} privateKey private key for signing the record. + * @param {string} value value to be stored in the record. + * @param {number} seq number representing the current version of the record. + * @param {string} expiration expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision. + * @param {function(Error, entry)} [callback] + */ +const createWithExpiration = (privateKey, value, seq, expiration, callback) => { + const validityType = ipnsEntryProto.ValidityType.EOL + _create(privateKey, value, seq, expiration, validityType, callback) +} + +const _create = (privateKey, value, seq, isoValidity, validityType, callback) => { + sign(privateKey, value, validityType, isoValidity, (error, signature) => { + if (error) { + log.error('record signature creation failed') + return callback(Object.assign(new Error('record signature verification failed'), { code: ERRORS.ERR_SIGNATURE_CREATION })) + } + + const entry = { + value: value, + signature: signature, + validityType: validityType, + validity: isoValidity, + sequence: seq + } + + log(`ipns entry for ${value} created`) + return callback(null, entry) + }) +} + +/** + * Validates the given ipns entry against the given public key. + * + * @param {Object} publicKey public key for validating the record. + * @param {Object} entry ipns entry record. + * @param {function(Error)} [callback] + */ +const validate = (publicKey, entry, callback) => { + const { value, validityType, validity } = entry + const dataForSignature = ipnsEntryDataForSig(value, validityType, validity) + + // Validate Signature + publicKey.verify(dataForSignature, entry.signature, (err, isValid) => { + if (err || !isValid) { + log.error('record signature verification failed') + return callback(Object.assign(new Error('record signature verification failed'), { code: ERRORS.ERR_SIGNATURE_VERIFICATION })) + } + + // Validate according to the validity type + if (validityType === ipnsEntryProto.ValidityType.EOL) { + let validityDate + + try { + validityDate = parseRFC3339(validity.toString()) + } catch (e) { + log.error('unrecognized validity format (not an rfc3339 format)') + return callback(Object.assign(new Error('unrecognized validity format (not an rfc3339 format)'), { code: ERRORS.ERR_UNRECOGNIZED_FORMAT })) + } + + if (validityDate < Date.now()) { + log.error('record has expired') + return callback(Object.assign(new Error('record has expired'), { code: ERRORS.ERR_IPNS_EXPIRED_RECORD })) + } + } else if (validityType) { + log.error('unrecognized validity type') + return callback(Object.assign(new Error('unrecognized validity type'), { code: ERRORS.ERR_UNRECOGNIZED_VALIDITY })) + } + + log(`ipns entry for ${value} is valid`) + return callback(null, null) + }) +} + +/** + * Embed the given public key in the given entry. While not strictly required, + * some nodes (eg. DHT servers) may reject IPNS entries that don't embed their + * public keys as they may not be able to validate them efficiently. + * As a consequence of nodes needing to validade a record upon receipt, they need + * the public key associated with it. For olde RSA keys, it is easier if we just + * send this as part of the record itself. For newer ed25519 keys, the public key + * can be embedded in the peerId. + * + * @param {Object} publicKey public key to embed. + * @param {Object} entry ipns entry record. + * @param {function(Error)} [callback] + * @return {Void} + */ +const embedPublicKey = (publicKey, entry, callback) => { + if (!publicKey || !publicKey.bytes || !entry) { + const error = 'one or more of the provided parameters are not defined' + + log.error(error) + return callback(Object.assign(new Error(error), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) + } + + // Create a peer id from the public key. + PeerId.createFromPubKey(publicKey.bytes, (err, peerId) => { + if (err) { + log.error(err) + return callback(Object.assign(new Error(err), { code: ERRORS.ERR_PEER_ID_FROM_PUBLIC_KEY })) + } + + // Try to extract the public key from the ID. If we can, no need to embed it + let extractedPublicKey + try { + extractedPublicKey = extractPublicKeyFromId(peerId) + } catch (err) { + log.error(err) + return callback(Object.assign(new Error(err), { code: ERRORS.ERR_PUBLIC_KEY_FROM_ID })) + } + + if (extractedPublicKey) { + return callback(null, null) + } + + // If we failed to extract the public key from the peer ID, embed it in the record. + try { + entry.pubKey = crypto.keys.marshalPublicKey(publicKey) + } catch (err) { + log.error(err) + return callback(err) + } + callback(null, entry) + }) +} + +/** + * Extracts a public key matching `pid` from the ipns record. + * + * @param {Object} peerId peer identifier object. + * @param {Object} entry ipns entry record. + * @param {function(Error)} [callback] + * @return {Void} + */ +const extractPublicKey = (peerId, entry, callback) => { + if (!entry || !peerId) { + const error = 'one or more of the provided parameters are not defined' + + log.error(error) + return callback(Object.assign(new Error(error), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) + } + + if (entry.pubKey) { + let pubKey + try { + pubKey = crypto.keys.unmarshalPublicKey(entry.pubKey) + } catch (err) { + log.error(err) + return callback(err) + } + return callback(null, pubKey) + } + + if (peerId.pubKey) { + callback(null, peerId.pubKey) + } else { + callback(Object.assign(new Error('no public key is available'), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) + } +} + +// rawStdEncoding with RFC4648 +const rawStdEncoding = (key) => base32Encode(key, 'RFC4648', { padding: false }) + +/** + * Get key for storing the record locally. + * Format: /ipns/${base32()} + * + * @param {Buffer} key peer identifier object. + * @returns {string} + */ +const getLocalKey = (key) => new Key(`/ipns/${rawStdEncoding(key)}`) + +/** + * Get key for sharing the record in the routing mechanism. + * Format: ${base32(/ipns/)}, ${base32(/pk/)} + * + * @param {Buffer} pid peer identifier represented by the multihash of the public key as Buffer. + * @returns {Object} containing the `nameKey` and the `ipnsKey`. + */ +const getIdKeys = (pid) => { + const pkBuffer = Buffer.from('/pk/') + const ipnsBuffer = Buffer.from('/ipns/') + + return { + routingPubKey: new Key(Buffer.concat([pkBuffer, pid])), // Added on https://github.com/ipfs/js-ipns/pull/8#issue-213857876 (pkKey will be deprecated in a future release) + pkKey: new Key(rawStdEncoding(Buffer.concat([pkBuffer, pid]))), + routingKey: new Key(Buffer.concat([ipnsBuffer, pid])), // Added on https://github.com/ipfs/js-ipns/pull/6#issue-213631461 (ipnsKey will be deprecated in a future release) + ipnsKey: new Key(rawStdEncoding(Buffer.concat([ipnsBuffer, pid]))) + } +} + +// Sign ipns record data +const sign = (privateKey, value, validityType, validity, callback) => { + const dataForSignature = ipnsEntryDataForSig(value, validityType, validity) + + privateKey.sign(dataForSignature, (err, signature) => { + if (err) { + return callback(err) + } + return callback(null, signature) + }) +} + +// Utility for getting the validity type code name of a validity +const getValidityType = (validityType) => { + if (validityType.toString() === '0') { + return 'EOL' + } else { + const error = `unrecognized validity type ${validityType.toString()}` + log.error(error) + throw Object.assign(new Error(error), { code: ERRORS.ERR_UNRECOGNIZED_VALIDITY }) + } +} + +// Utility for creating the record data for being signed +const ipnsEntryDataForSig = (value, validityType, validity) => { + const valueBuffer = Buffer.from(value) + const validityTypeBuffer = Buffer.from(getValidityType(validityType)) + const validityBuffer = Buffer.from(validity) + + return Buffer.concat([valueBuffer, validityBuffer, validityTypeBuffer]) +} + +// Utility for extracting the public key from a peer-id +const extractPublicKeyFromId = (peerId) => { + const decodedId = multihash.decode(peerId.id) + + if (decodedId.code !== ID_MULTIHASH_CODE) { + return null + } + + return crypto.keys.unmarshalPublicKey(decodedId.digest) +} + +const marshal = ipnsEntryProto.encode + +const unmarshal = ipnsEntryProto.decode + +const validator = { + validate: (marshalledData, key, callback) => { + const receivedEntry = unmarshal(marshalledData) + const bufferId = key.slice('/ipns/'.length) + let peerId + + try { + peerId = PeerId.createFromBytes(bufferId) + } catch (err) { + return callback(err) + } + + // extract public key + extractPublicKey(peerId, receivedEntry, (err, pubKey) => { + if (err) { + return callback(err) + } + + // Record validation + validate(pubKey, receivedEntry, (err) => { + if (err) { + return callback(err) + } + + callback(null, true) + }) + }) + }, + select: (dataA, dataB, callback) => { + const entryA = unmarshal(dataA) + const entryB = unmarshal(dataB) + + const index = entryA.sequence > entryB.sequence ? 0 : 1 + + if (typeof callback !== 'function') { + return index + } + + callback(null, index) + } +} + +module.exports = { + // create ipns entry record + create, + // create ipns entry record specifying the expiration time + createWithExpiration, + // validate ipns entry record + validate, + // embed public key in the record + embedPublicKey, + // extract public key from the record + extractPublicKey, + // get key for storing the entry locally + getLocalKey, + // get keys for routing + getIdKeys, + // marshal + marshal, + // unmarshal + unmarshal, + // validator + validator, + // namespace + namespace, + namespaceLength: namespace.length +} + +}).call(this,require("buffer").Buffer) +},{"./errors":604,"./pb/ipns.proto":606,"./utils":607,"base32-encode":106,"buffer":181,"debug":602,"interface-datastore":322,"libp2p-crypto":745,"multihashes":1157,"peer-id":1253,"timestamp-nano":1501}],606:[function(require,module,exports){ +'use strict' + +const protons = require('protons') + +/* eslint-disable no-tabs */ +const message = ` +message IpnsEntry { + enum ValidityType { + EOL = 0; // setting an EOL says "this record is valid until..." + } + + required bytes value = 1; + required bytes signature = 2; + + optional ValidityType validityType = 3; + optional bytes validity = 4; + + optional uint64 sequence = 5; + + optional uint64 ttl = 6; + + // in order for nodes to properly validate a record upon receipt, they need the public + // key associated with it. For old RSA keys, its easiest if we just send this as part of + // the record itself. For newer ed25519 keys, the public key can be embedded in the + // peerID, making this field unnecessary. + optional bytes pubKey = 7; +} +` + +module.exports = protons(message).IpnsEntry + +},{"protons":1274}],607:[function(require,module,exports){ +'use strict' + +/** + * Convert a JavaScript date into an `RFC3339Nano` formatted + * string. + * + * @param {Date} time + * @returns {string} + */ +module.exports.toRFC3339 = (time) => { + const year = time.getUTCFullYear() + const month = String(time.getUTCMonth() + 1).padStart(2, '0') + const day = String(time.getUTCDate()).padStart(2, '0') + const hour = String(time.getUTCHours()).padStart(2, '0') + const minute = String(time.getUTCMinutes()).padStart(2, '0') + const seconds = String(time.getUTCSeconds()).padStart(2, '0') + const milliseconds = time.getUTCMilliseconds() + const nanoseconds = milliseconds * 1000 * 1000 + + return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z` +} + +/** + * Parses a date string formatted as `RFC3339Nano` into a + * JavaScript Date object. + * + * @param {string} time + * @returns {Date} + */ +module.exports.parseRFC3339 = (time) => { + const rfc3339Matcher = new RegExp( + // 2006-01-02T + '(\\d{4})-(\\d{2})-(\\d{2})T' + + // 15:04:05 + '(\\d{2}):(\\d{2}):(\\d{2})' + + // .999999999Z + '\\.(\\d+)Z' + ) + const m = String(time).trim().match(rfc3339Matcher) + + if (!m) { + throw new Error('Invalid format') + } + + const year = parseInt(m[1], 10) + const month = parseInt(m[2], 10) - 1 + const date = parseInt(m[3], 10) + const hour = parseInt(m[4], 10) + const minute = parseInt(m[5], 10) + const second = parseInt(m[6], 10) + const millisecond = parseInt(m[7].slice(0, -6), 10) + + return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond)) +} + +},{}],608:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],609:[function(require,module,exports){ +var Node = require('./lib/node') + +module.exports = isCircular + +/** + * checks whether the object is circular + * @param {object} obj - object to check circularity for + * @return {Boolean} true if obj is circular, false if it is not + */ +function isCircular (obj) { + if (!(obj instanceof Object)) { + throw new TypeError('"obj" must be an object (or inherit from it)') + } + return _isCircular(obj) +} + +/** + * @private + * checks whether the object is circular + * @param {object} obj - object to check circularity for + * @param {Node} parentList - linked-list that contains all the object's parents + * @return {Boolean} true if obj is circular, false if it is not + */ +function _isCircular (obj, parentList) { + parentList = new Node(obj, parentList) + + // breadth-first search for circular object + for (var key in obj) { + var val = obj[key] + if (val instanceof Object) { + if (parentList.contains(val) || _isCircular(val, parentList)) { + return true + } + } + } + + return false +} + +},{"./lib/node":610}],610:[function(require,module,exports){ +module.exports = Node + +/** + * a linked-list node + * @class + * @param {any} value - node's value + * @param {Node} next - next node + */ +function Node (value, next) { + this.value = value + this.next = next +} + +/** + * checks if this node or any of its children has the value + * @param {any} value - value to check if linked-list contains + * @return {boolean} true if the list contains the value; false if not + */ +Node.prototype.contains = function (value) { + var cursor = this + + while (cursor) { + if (cursor.value === value) return true + cursor = cursor.next + } + + return false +} + +},{}],611:[function(require,module,exports){ +'use strict' + +// Adapted from RFC 2181 (See section 11) +// +// The RFC defines a Domain Name to be at most 255 chars including seperators +// between labels. +// Subdomains are labels plus a seperator. A label is a string starting and +// ending with an alphanum, with dashes allowed in the middle. It is between 1 and 63 chars. +// +// We make some assumptions below that go beyond the RFC. We assume the TLD +// to be at least 2 chars. The regex also allows domains longer than 255 chars, +// but allows at most 127 subdomains, as assuming a lower-bound of one char per +// subdomain will yield 252, and adding a TLD of 2 chars sums to 254. +/* +(?: // Group 1: This is for subdomain, which is composed of a label and a seperator (length = [1, 63] + 1) + [a-z0-9] + (?: + [a-z0-9\-]{0,61} // Limited to 61 chars as we have at least two chars if we reach this group (61 + 2 = 63 which is the limit) + [a-z0-9] + )? + \. // Label seperator +){0,126} // If we assume the lower-bound of 1 char labels, we can at most have 126 groups before approaching the total limit of 255 chars +(?: // Group 2: Assume that the TLD is at least 2 chars (for sanity) + [a-z0-9] + [a-z0-9\-]{0,61} + [a-z0-9] +) +\.? // Some consider a trailing dot to be considered valid as it signifies the root of the domain tree + */ +var domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i + +/** + * Test whether a string is a valid domain name, optionally checking for a root dot as well + * @param {String} domainName + * @param {Boolean} rootDot Check for a root dot eg. 'example.com.'. Defaults to false + * @return {Boolean} + */ +module.exports = function isDomainName (domainName, rootDot) { + if (rootDot == null) rootDot = false + + if (domainName.length < 2) return false + if (domainName.length > 255) return false + + var lastChar = domainName[domainName.length - 1] + if (rootDot) { + if (lastChar !== '.') return false + } else { + if (lastChar === '.') return false + } + + return domainNameRegex.test(domainName) +} + +},{}],612:[function(require,module,exports){ +'use strict'; +var toString = Object.prototype.toString; + +module.exports = function (x) { + return toString.call(x) === '[object Function]'; +}; + +},{}],613:[function(require,module,exports){ +'use strict'; +const ipRegex = require('ip-regex'); + +const isIp = module.exports = x => ipRegex({exact: true}).test(x); +isIp.v4 = x => ipRegex.v4({exact: true}).test(x); +isIp.v6 = x => ipRegex.v6({exact: true}).test(x); + +},{"ip-regex":326}],614:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +const base58 = require('bs58') +const multihash = require('multihashes') +const multibase = require('multibase') +const Multiaddr = require('multiaddr') +const mafmt = require('mafmt') +const CID = require('cids') + +const urlPattern = /^https?:\/\/[^/]+\/(ip(f|n)s)\/((\w+).*)/ +const pathPattern = /^\/(ip(f|n)s)\/((\w+).*)/ +const defaultProtocolMatch = 1 +const defaultHashMath = 4 + +const fqdnPattern = /^https?:\/\/([^/]+)\.(ip(?:f|n)s)\.[^/]+/ +const fqdnHashMatch = 1 +const fqdnProtocolMatch = 2 + +function isMultihash (hash) { + const formatted = convertToString(hash) + try { + const buffer = Buffer.from(base58.decode(formatted)) + multihash.decode(buffer) + return true + } catch (e) { + return false + } +} + +function isMultibase (hash) { + try { + return multibase.isEncoded(hash) + } catch (e) { + return false + } +} + +function isCID (hash) { + try { + new CID(hash) // eslint-disable-line no-new + return true + } catch (e) { + return false + } +} + +function isMultiaddr (input) { + if (!input) return false + if (Multiaddr.isMultiaddr(input)) return true + try { + new Multiaddr(input) // eslint-disable-line no-new + return true + } catch (e) { + return false + } +} + +function isPeerMultiaddr (input) { + return isMultiaddr(input) && mafmt.IPFS.matches(input) +} + +function isIpfs (input, pattern, protocolMatch = defaultProtocolMatch, hashMatch = defaultHashMath) { + const formatted = convertToString(input) + if (!formatted) { + return false + } + + const match = formatted.match(pattern) + if (!match) { + return false + } + + if (match[protocolMatch] !== 'ipfs') { + return false + } + + let hash = match[hashMatch] + + if (hash && pattern === fqdnPattern) { + // when doing checks for subdomain context + // ensure hash is case-insensitive + // (browsers force-lowercase authority compotent anyway) + hash = hash.toLowerCase() + } + + return isCID(hash) +} + +function isIpns (input, pattern, protocolMatch = defaultProtocolMatch, hashMatch) { + const formatted = convertToString(input) + if (!formatted) { + return false + } + const match = formatted.match(pattern) + if (!match) { + return false + } + + if (match[protocolMatch] !== 'ipns') { + return false + } + + if (hashMatch && pattern === fqdnPattern) { + let hash = match[hashMatch] + // when doing checks for subdomain context + // ensure hash is case-insensitive + // (browsers force-lowercase authority compotent anyway) + hash = hash.toLowerCase() + return isCID(hash) + } + + return true +} + +function isString (input) { + return typeof input === 'string' +} + +function convertToString (input) { + if (Buffer.isBuffer(input)) { + return base58.encode(input) + } + + if (isString(input)) { + return input + } + + return false +} + +const ipfsSubdomain = (url) => isIpfs(url, fqdnPattern, fqdnProtocolMatch, fqdnHashMatch) +const ipnsSubdomain = (url) => isIpns(url, fqdnPattern, fqdnProtocolMatch, fqdnHashMatch) + +module.exports = { + multihash: isMultihash, + multiaddr: isMultiaddr, + peerMultiaddr: isPeerMultiaddr, + cid: isCID, + base32cid: (cid) => (isMultibase(cid) === 'base32' && isCID(cid)), + ipfsSubdomain: ipfsSubdomain, + ipnsSubdomain: ipnsSubdomain, + subdomain: (url) => (ipfsSubdomain(url) || ipnsSubdomain(url)), + subdomainPattern: fqdnPattern, + ipfsUrl: (url) => isIpfs(url, urlPattern), + ipnsUrl: (url) => isIpns(url, urlPattern), + url: (url) => (isIpfs(url, urlPattern) || isIpns(url, urlPattern)), + urlPattern: urlPattern, + ipfsPath: (path) => isIpfs(path, pathPattern), + ipnsPath: (path) => isIpns(path, pathPattern), + path: (path) => (isIpfs(path, pathPattern) || isIpns(path, pathPattern)), + pathPattern: pathPattern, + urlOrPath: (x) => (isIpfs(x, urlPattern) || isIpns(x, urlPattern) || isIpfs(x, pathPattern) || isIpns(x, pathPattern)), + cidPath: path => isString(path) && !isCID(path) && isIpfs(`/ipfs/${path}`, pathPattern) +} + +}).call(this,require("buffer").Buffer) +},{"bs58":177,"buffer":181,"cids":185,"mafmt":1125,"multiaddr":1140,"multibase":1148,"multihashes":1157}],615:[function(require,module,exports){ +'use strict'; +var toString = Object.prototype.toString; + +module.exports = function (x) { + var prototype; + return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); +}; + +},{}],616:[function(require,module,exports){ +module.exports = isPromise; + +function isPromise(obj) { + return obj && typeof obj.then === 'function'; +} +},{}],617:[function(require,module,exports){ + +function isFunction (f) { + return 'function' === typeof f +} + +function isDuplex (d) { + return 'object' === typeof d && isSource(d.source) && isSink(d.sink) +} + +function isSource (s) { + return isFunction(s) && s.length === 2 +} + +function isSink (s) { + return isFunction(s) && s.length === 1 +} + +exports.isDuplex = isDuplex +exports.isSource = isSource +exports.isSink = isSink +//can't do is through, it will appear as a sink til you git it a source. + + +},{}],618:[function(require,module,exports){ +'use strict'; + +const { randomBytes } = require('crypto'); + +module.exports = randomBytes; + +},{"crypto":197}],619:[function(require,module,exports){ +const http = require('./lib/http') +const https = http +const URL = self.URL + +module.exports = { + http, + https, + getRequest: (options, cb) => { + let protocol = 'http:' + + if (typeof options === 'string') { + const url = new URL(options) + protocol = url.protocol + } else if (options.protocol) { + protocol = options.protocol + } + + return protocol === 'http:' ? http.request(options, cb) : https.request(options, cb) + } +} + +},{"./lib/http":621}],620:[function(require,module,exports){ +function isFunction (value) { + return typeof value === 'function' +} + +module.exports = { + fetch: 'fetch' in self && isFunction(self.fecth), + writableStream: 'WritableStream' in self && isFunction(self.WritableStream), + abortController: 'AbortController' in self && isFunction(self.AbortController), + arrayBuffer: 'ArrayBuffer' in self +} +},{}],621:[function(require,module,exports){ +(function (global){ +var ClientRequest = require('./request') +var IncomingMessage = require('./incoming-message') +var statusCodes = require('builtin-status-codes') +var URL = self.URL + + +const request = (opts, cb) => { + if (typeof opts === 'string') { + + opts = new URL(opts, self.location.protocol + '//' +self.location.host) + opts.path = opts.pathname + opts.search + opts.auth = (opts.username && opts.password) ? opts.username + ':' + opts.password : null + } else { + opts = Object.assign({}, opts) + } + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +const get = (opts, cb) => { + var req = request(opts, cb) + req.end() + return req +} + +const Agent = function () {} +Agent.defaultMaxSockets = 4 + +const METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] + +module.exports = { + Agent, + ClientRequest, + IncomingMessage, + METHODS, + STATUS_CODES: statusCodes, + get, + globalAgent : new Agent(), + request, + maxHeaderSize: '8KB' + +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./incoming-message":622,"./request":623,"builtin-status-codes":182}],622:[function(require,module,exports){ +(function (process,Buffer){ +var capability = require('./capability') +var inherits = require('inherits') +var stream = require('readable-stream') + +var IncomingMessage = function (response, mode, fetchTimer) { + stream.Readable.call(this) + + this._mode = mode + this.headers = {} + this.rawHeaders = [] + this.trailers = {} + this.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + this.on('end', () => { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(() =>this.emit('close')) + }) + + this._fetchResponse = response + + this.url = response.url + this.statusCode = response.status + this.statusMessage = response.statusText + + response.headers.forEach((header, key) => { + this.headers[key.toLowerCase()] = header + this.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: chunk => { + return new Promise((resolve, reject) => { + if (this._destroyed) { + reject() + } else if(this.push(Buffer.from(chunk))) { + resolve() + } else { + this._resumeFetch = resolve + } + }) + }, + close: () => { + clearTimeout(fetchTimer) + if (!this._destroyed){ + this.push(null) + } + }, + abort: err => { + if (!this._destroyed){ + this.emit('error', err) + } + } + }) + + try { + response.body + .pipeTo(writable) + .catch(err => { + console.log(err); + self.clearTimeout(fetchTimer) + if (!this._destroyed){ + this.emit('error', err) + } + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + + function read (context) { + reader.read() + .then(result => { + if (context._destroyed){ + return + } + if (result.done) { + clearTimeout(fetchTimer) + context.push(null) + return + } + context.push(Buffer.from(result.value)) + read(context) + }) + .catch(err => { + clearTimeout(fetchTimer) + if (!context._destroyed){ + context.emit('error', err) + } + }) + } + + read(this) + +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var resolve = this._resumeFetch + if (resolve) { + this._resumeFetch = null + resolve() + } +} + +module.exports = IncomingMessage +}).call(this,require('_process'),require("buffer").Buffer) +},{"./capability":620,"_process":1258,"buffer":181,"inherits":317,"readable-stream":638}],623:[function(require,module,exports){ +(function (Buffer){ +var capability = require('./capability') +var inherits = require('inherits') +var IncomingMessage = require('./incoming-message') +var stream = require('readable-stream') + +var fetch = self.fetch + +var ClientRequest = module.exports = function (opts) { + stream.Writable.call(this) + + this._opts = opts + this._body = [] + this._headers = {} + if (opts.auth) + this.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) + + + Object.keys(opts.headers).forEach(name => { + this.setHeader(name, opts.headers[name]) + }) + + this._mode = 'fetch' + this._fetchTimer = null + + this.on('finish', () => this._onFinish()) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1){ + return + } + this._headers[lowerName] = value +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + delete this._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + if (this._destroyed) + return + var opts = this._opts + + var headersObj = this._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + body = new Blob(this._body, { + type: (headersObj['content-type'] || {}).value || '' + }); + } + + var signal = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + this._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + this._fetchTimer = setTimeout(() => { + this.emit('requestTimeout') + if (this._fetchAbortController) + this._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + fetch(this._opts.url, { + method: this._opts.method, + headers: this._headers, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }) + .then(response => { + this._fetchResponse = response + this._connect() + }, reason => { + clearTimeout(this._fetchTimer) + if (!this._destroyed) + this.emit('error', reason) + }) +} + +ClientRequest.prototype._connect = function () { + if (this._destroyed) + return + + this._response = new IncomingMessage(this._fetchResponse, this._mode, this._fetchTimer) + this._response.on('error', (err) => this.emit('error', err)) + + this.emit('response', this._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + this._body.push(chunk) + cb() +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { + this._destroyed = true + + + clearTimeout(this._fetchTimer) + + if (this._response) + this._response._destroyed = true + if (this._xhr) + this._xhr.abort() + else if (this._fetchAbortController) + this._fetchAbortController.abort() +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(this, data, encoding, cb) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setTimeout = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] + +}).call(this,require("buffer").Buffer) +},{"./capability":620,"./incoming-message":622,"buffer":181,"inherits":317,"readable-stream":638}],624:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],625:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],626:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":628,"./_stream_writable":630,"_process":1258,"dup":38,"inherits":317}],627:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":629,"dup":39,"inherits":317}],628:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":624,"../experimentalWarning":625,"./_stream_duplex":626,"./internal/streams/async_iterator":631,"./internal/streams/buffer_list":632,"./internal/streams/destroy":633,"./internal/streams/state":636,"./internal/streams/stream":637,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":640,"util":146}],629:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":624,"./_stream_duplex":626,"dup":41,"inherits":317}],630:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":624,"./_stream_duplex":626,"./internal/streams/destroy":633,"./internal/streams/state":636,"./internal/streams/stream":637,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],631:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":634,"_process":1258,"dup":43}],632:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],633:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],634:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":624,"dup":46}],635:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":624,"./end-of-stream":634,"dup":47}],636:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":624,"dup":48}],637:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],638:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":626,"./lib/_stream_passthrough.js":627,"./lib/_stream_readable.js":628,"./lib/_stream_transform.js":629,"./lib/_stream_writable.js":630,"./lib/internal/streams/end-of-stream.js":634,"./lib/internal/streams/pipeline.js":635,"dup":50}],639:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],640:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":639}],641:[function(require,module,exports){ +'use strict'; + +const { + URLWithLegacySupport, + format, + URLSearchParams, + defaultBase +} = require('./src/url'); +const relative = require('./src/relative'); + +module.exports = { + URL: URLWithLegacySupport, + URLSearchParams, + format, + relative, + defaultBase +}; + +},{"./src/relative":642,"./src/url":643}],642:[function(require,module,exports){ +'use strict'; + +const { URLWithLegacySupport, format } = require('./url'); + +module.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => { + let protocol = location.protocol ? + location.protocol.replace(':', '') : + 'http'; + + // Check protocol map + protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':'; + let urlParsed; + + try { + urlParsed = new URLWithLegacySupport(url); + } catch (err) { + urlParsed = {}; + } + + const base = Object.assign({}, location, { + protocol: protocol || urlParsed.protocol, + host: location.host || urlParsed.host + }); + + return new URLWithLegacySupport(url, format(base)).toString(); +}; + +},{"./url":643}],643:[function(require,module,exports){ +'use strict'; + +const defaultBase = self.location ? + self.location.protocol + '//' + self.location.host : + ''; +const URL = self.URL; + +class URLWithLegacySupport { + constructor(url, base = defaultBase) { + this.super = new URL(url, base); + this.path = this.pathname + this.search; + this.auth = + this.username && this.password ? + this.username + ':' + this.password : + null; + + this.query = + this.search && this.search.startsWith('?') ? + this.search.slice(1) : + null; + } + + get hash() { + return this.super.hash; + } + get host() { + return this.super.host; + } + get hostname() { + return this.super.hostname; + } + get href() { + return this.super.href; + } + get origin() { + return this.super.origin; + } + get password() { + return this.super.password; + } + get pathname() { + return this.super.pathname; + } + get port() { + return this.super.port; + } + get protocol() { + return this.super.protocol; + } + get search() { + return this.super.search; + } + get searchParams() { + return this.super.searchParams; + } + get username() { + return this.super.username; + } + + set hash(hash) { + this.super.hash = hash; + } + set host(host) { + this.super.host = host; + } + set hostname(hostname) { + this.super.hostname = hostname; + } + set href(href) { + this.super.href = href; + } + set origin(origin) { + this.super.origin = origin; + } + set password(password) { + this.super.password = password; + } + set pathname(pathname) { + this.super.pathname = pathname; + } + set port(port) { + this.super.port = port; + } + set protocol(protocol) { + this.super.protocol = protocol; + } + set search(search) { + this.super.search = search; + } + set searchParams(searchParams) { + this.super.searchParams = searchParams; + } + set username(username) { + this.super.username = username; + } + + createObjectURL(o) { + return this.super.createObjectURL(o); + } + revokeObjectURL(o) { + this.super.revokeObjectURL(o); + } + toJSON() { + return this.super.toJSON(); + } + toString() { + return this.super.toString(); + } + format() { + return this.toString(); + } +} + +function format(obj) { + if (typeof obj === 'string') { + const url = new URL(obj); + + return url.toString(); + } + + if (!(obj instanceof URL)) { + const userPass = + obj.username && obj.password ? + `${obj.username}:${obj.password}@` : + ''; + const auth = obj.auth ? obj.auth + '@' : ''; + const port = obj.port ? ':' + obj.port : ''; + const protocol = obj.protocol ? obj.protocol + '//' : ''; + const host = obj.host || ''; + const hostname = obj.hostname || ''; + const search = obj.search || (obj.query ? '?' + obj.query : ''); + const hash = obj.hash || ''; + const pathname = obj.pathname || ''; + const path = obj.path || pathname + search; + + return `${protocol}${userPass || auth}${host || + hostname + port}${path}${hash}`; + } +} + +module.exports = { + URLWithLegacySupport, + URLSearchParams: self.URLSearchParams, + defaultBase, + format +}; + +},{}],644:[function(require,module,exports){ +const rawPipe = (...fns) => { + let res + while (fns.length) { + res = fns.shift()(res) + } + return res +} + +const isIterable = obj => obj && ( + typeof obj[Symbol.asyncIterator] === 'function' || + typeof obj[Symbol.iterator] === 'function' || + typeof obj.next === 'function' // Probably, right? +) + +const isDuplex = obj => obj && typeof obj.sink === 'function' && isIterable(obj.source) + +const duplexPipelineFn = duplex => source => { + duplex.sink(source) // TODO: error on sink side is unhandled rejection - this is the same as pull streams + return duplex.source +} + +const pipe = (...fns) => { + // Duplex at start: wrap in function and return duplex source + if (isDuplex(fns[0])) { + const duplex = fns[0] + fns[0] = () => duplex.source + // Iterable at start: wrap in function + } else if (isIterable(fns[0])) { + const source = fns[0] + fns[0] = () => source + } + + if (fns.length > 1) { + // Duplex at end: use duplex sink + if (isDuplex(fns[fns.length - 1])) { + fns[fns.length - 1] = fns[fns.length - 1].sink + } + } + + if (fns.length > 2) { + // Duplex in the middle, consume source with duplex sink and return duplex source + for (let i = 1; i < fns.length - 1; i++) { + if (isDuplex(fns[i])) { + fns[i] = duplexPipelineFn(fns[i]) + } + } + } + + return rawPipe(...fns) +} + +module.exports = pipe +module.exports.pipe = pipe +module.exports.rawPipe = rawPipe +module.exports.isIterable = isIterable +module.exports.isDuplex = isDuplex + +},{}],645:[function(require,module,exports){ +'use strict'; + +const pDefer = () => { + const deferred = {}; + + deferred.promise = new Promise((resolve, reject) => { + deferred.resolve = resolve; + deferred.reject = reject; + }); + + return deferred; +}; + +module.exports = pDefer; + +},{}],646:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],647:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],648:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":650,"./_stream_writable":652,"_process":1258,"dup":38,"inherits":317}],649:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":651,"dup":39,"inherits":317}],650:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":646,"../experimentalWarning":647,"./_stream_duplex":648,"./internal/streams/async_iterator":653,"./internal/streams/buffer_list":654,"./internal/streams/destroy":655,"./internal/streams/state":658,"./internal/streams/stream":659,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":662,"util":146}],651:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":646,"./_stream_duplex":648,"dup":41,"inherits":317}],652:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":646,"./_stream_duplex":648,"./internal/streams/destroy":655,"./internal/streams/state":658,"./internal/streams/stream":659,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],653:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":656,"_process":1258,"dup":43}],654:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],655:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],656:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":646,"dup":46}],657:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":646,"./end-of-stream":656,"dup":47}],658:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":646,"dup":48}],659:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],660:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":648,"./lib/_stream_passthrough.js":649,"./lib/_stream_readable.js":650,"./lib/_stream_transform.js":651,"./lib/_stream_writable.js":652,"./lib/internal/streams/end-of-stream.js":656,"./lib/internal/streams/pipeline.js":657,"dup":50}],661:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],662:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":661}],663:[function(require,module,exports){ +(function (Buffer){ +const { Readable, Writable, Duplex } = require('stream') +const getIterator = require('get-iterator') +const Fifo = require('p-fifo') +const END_CHUNK = Buffer.alloc(0) + +module.exports = function toDuplex (duplex, options) { + options = options || {} + + let reading = false + const fifo = new Fifo() + + duplex = { + sink: duplex.sink, + source: duplex.source ? getIterator(duplex.source) : null + } + + let Stream = Duplex + if (!duplex.source) { + Stream = Writable + } else if (!duplex.sink) { + Stream = Readable + } + + Object.assign( + options, + duplex.source ? { + async read (size) { + if (reading) return + reading = true + + try { + while (true) { + const { value, done } = await duplex.source.next(size) + if (done) return this.push(null) + if (!this.push(value)) break + } + } catch (err) { + this.emit('error', err) + } finally { + reading = false + } + } + } : {}, + duplex.sink ? { + write (chunk, enc, cb) { + fifo.push(chunk).then(() => cb(), cb) + }, + final (cb) { + fifo.push(END_CHUNK).then(() => cb(), cb) + } + } : {} + ) + + const stream = new Stream(options) + + if (duplex.sink) { + duplex.sink({ + [Symbol.asyncIterator] () { + return this + }, + async next () { + const chunk = await fifo.shift() + return chunk === END_CHUNK ? { done: true } : { value: chunk } + }, + async throw (err) { + stream.destroy(err) + return { done: true } + }, + async return () { + stream.destroy() + return { done: true } + } + }) + } + + return stream +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"get-iterator":281,"p-fifo":1230,"stream":660}],664:[function(require,module,exports){ +'use strict' + +const toTransform = require('./transform') +const toDuplex = require('./duplex') + +function toReadable (source, options) { + return toDuplex({ source }, options) +} + +function toWritable (sink, options) { + return toDuplex({ sink }, options) +} + +module.exports = toReadable +module.exports.readable = toReadable +module.exports.writable = toWritable +module.exports.transform = toTransform +module.exports.duplex = toDuplex + +},{"./duplex":663,"./transform":665}],665:[function(require,module,exports){ +const toDuplex = require('./duplex') +const defer = require('p-defer') + +module.exports = function toTransform (transform, options) { + const { promise, resolve } = defer() + + const source = (async function * () { + const it = await promise + for await (const chunk of it) yield chunk + })() + + return toDuplex({ sink: s => resolve(transform(s)), source }, options) +} + +},{"./duplex":663,"p-defer":645}],666:[function(require,module,exports){ (function (process,global){ /** * [js-sha3]{@link https://github.com/emn178/js-sha3} @@ -70965,22263 +68584,7 @@ arguments[4][248][0].apply(exports,arguments) })(); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1438}],468:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],469:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const blake = require('blakejs') - -const toCallback = require('./utils').toCallback - -const minB = 0xb201 -const minS = 0xb241 - -const blake2b = { - init: blake.blake2bInit, - update: blake.blake2bUpdate, - digest: blake.blake2bFinal -} - -const blake2s = { - init: blake.blake2sInit, - update: blake.blake2sUpdate, - digest: blake.blake2sFinal -} - -const makeB2Hash = (size, hf) => toCallback((buf) => { - const ctx = hf.init(size, null) - hf.update(ctx, buf) - return Buffer.from(hf.digest(ctx)) -}) - -module.exports = (table) => { - for (let i = 0; i < 64; i++) { - table[minB + i] = makeB2Hash(i + 1, blake2b) - } - for (let i = 0; i < 32; i++) { - table[minS + i] = makeB2Hash(i + 1, blake2s) - } -} - -}).call(this,require("buffer").Buffer) -},{"./utils":473,"blakejs":168,"buffer":217}],470:[function(require,module,exports){ -(function (Buffer){ -/* global self */ - -'use strict' - -const nodeify = require('nodeify') - -const webCrypto = getWebCrypto() - -function getWebCrypto () { - if (self.crypto) { - return self.crypto.subtle || self.crypto.webkitSubtle - } - - if (self.msCrypto) { - return self.msCrypto.subtle - } -} - -function webCryptoHash (type) { - if (!webCrypto) { - throw new Error('Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context') - } - - return (data, callback) => { - const res = webCrypto.digest({ name: type }, data) - - if (typeof res.then !== 'function') { // IE11 - res.onerror = () => { - callback(new Error(`hashing data using ${type}`)) - } - res.oncomplete = (e) => { - callback(null, e.target.result) - } - return - } - - nodeify( - res.then((raw) => Buffer.from(new Uint8Array(raw))), - callback - ) - } -} - -function sha1 (buf, callback) { - webCryptoHash('SHA-1')(buf, callback) -} - -function sha2256 (buf, callback) { - webCryptoHash('SHA-256')(buf, callback) -} - -function sha2512 (buf, callback) { - webCryptoHash('SHA-512')(buf, callback) -} - -module.exports = { - sha1: sha1, - sha2256: sha2256, - sha2512: sha2512 -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"nodeify":1384}],471:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const sha3 = require('js-sha3') -const murmur3 = require('murmurhash3js') - -const utils = require('./utils') -const sha = require('./crypto-sha1-2') - -const toCallback = utils.toCallback -const toBuf = utils.toBuf -const fromString = utils.fromString -const fromNumberTo32BitBuf = utils.fromNumberTo32BitBuf - -const dblSha2256 = (buf, cb) => { - sha.sha2256(buf, (err, firstHash) => { - if (err) { - cb(err) - } - sha.sha2256((Buffer.from(firstHash)), cb) - }) -} - -module.exports = { - sha1: sha.sha1, - sha2256: sha.sha2256, - sha2512: sha.sha2512, - sha3512: toCallback(toBuf(sha3.sha3_512)), - sha3384: toCallback(toBuf(sha3.sha3_384)), - sha3256: toCallback(toBuf(sha3.sha3_256)), - sha3224: toCallback(toBuf(sha3.sha3_224)), - shake128: toCallback(toBuf(sha3.shake_128, 128)), - shake256: toCallback(toBuf(sha3.shake_256, 256)), - keccak224: toCallback(toBuf(sha3.keccak_224)), - keccak256: toCallback(toBuf(sha3.keccak_256)), - keccak384: toCallback(toBuf(sha3.keccak_384)), - keccak512: toCallback(toBuf(sha3.keccak_512)), - murmur3128: toCallback(toBuf(fromString(murmur3.x64.hash128))), - murmur332: toCallback(fromNumberTo32BitBuf(fromString(murmur3.x86.hash32))), - addBlake: require('./blake'), - dblSha2256: dblSha2256 -} - -}).call(this,require("buffer").Buffer) -},{"./blake":469,"./crypto-sha1-2":470,"./utils":473,"buffer":217,"js-sha3":467,"murmurhash3js":1354}],472:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const multihash = require('multihashes') -const crypto = require('./crypto') - -module.exports = Multihashing - -/** - * Hash the given `buf` using the algorithm specified - * by `func`. - * - * @param {Buffer} buf - The value to hash. - * @param {number|string} func - The algorithm to use. - * @param {number} [length] - Optionally trim the result to this length. - * @param {function(Error, Buffer)} callback - * @returns {undefined} - */ -function Multihashing (buf, func, length, callback) { - if (typeof length === 'function') { - callback = length - length = undefined - } - - if (!callback) { - throw new Error('Missing callback') - } - - Multihashing.digest(buf, func, length, (err, digest) => { - if (err) { - return callback(err) - } - - callback(null, multihash.encode(digest, func, length)) - }) -} - -/** - * The `buffer` module for easy use in the browser. - * - * @type {Buffer} - */ -Multihashing.Buffer = Buffer // for browser things - -/** - * Expose multihash itself, to avoid silly double requires. - */ -Multihashing.multihash = multihash - -/** - * @param {Buffer} buf - The value to hash. - * @param {number|string} func - The algorithm to use. - * @param {number} [length] - Optionally trim the result to this length. - * @param {function(Error, Buffer)} callback - * @returns {undefined} - */ -Multihashing.digest = function (buf, func, length, callback) { - if (typeof length === 'function') { - callback = length - length = undefined - } - - if (!callback) { - throw new Error('Missing callback') - } - - let cb = callback - if (length) { - cb = (err, digest) => { - if (err) { - return callback(err) - } - - callback(null, digest.slice(0, length)) - } - } - - let hash - try { - hash = Multihashing.createHash(func) - } catch (err) { - return cb(err) - } - - hash(buf, cb) -} - -/** - * @param {string|number} func - * - * @returns {function} - The to `func` corresponding hash function. - */ -Multihashing.createHash = function (func) { - func = multihash.coerceCode(func) - if (!Multihashing.functions[func]) { - throw new Error('multihash function ' + func + ' not yet supported') - } - - return Multihashing.functions[func] -} - -/** - * Mapping of multihash codes to their hashing functions. - * @type {Object} - */ -Multihashing.functions = { - // sha1 - 0x11: crypto.sha1, - // sha2-256 - 0x12: crypto.sha2256, - // sha2-512 - 0x13: crypto.sha2512, - // sha3-512 - 0x14: crypto.sha3512, - // sha3-384 - 0x15: crypto.sha3384, - // sha3-256 - 0x16: crypto.sha3256, - // sha3-224 - 0x17: crypto.sha3224, - // shake-128 - 0x18: crypto.shake128, - // shake-256 - 0x19: crypto.shake256, - // keccak-224 - 0x1A: crypto.keccak224, - // keccak-256 - 0x1B: crypto.keccak256, - // keccak-384 - 0x1C: crypto.keccak384, - // keccak-512 - 0x1D: crypto.keccak512, - // murmur3-128 - 0x22: crypto.murmur3128, - // murmur3-32 - 0x23: crypto.murmur332, - // dbl-sha2-256 - 0x56: crypto.dblSha2256 -} - -// add blake functions -crypto.addBlake(Multihashing.functions) - -}).call(this,require("buffer").Buffer) -},{"./crypto":471,"buffer":217,"multihashes":1331}],473:[function(require,module,exports){ -(function (process,Buffer){ -'use strict' - -exports.toCallback = (doWork) => { - return function (input, callback) { - let res - try { - res = doWork(input) - } catch (err) { - process.nextTick(callback, err) - return - } - - process.nextTick(callback, null, res) - } -} - -exports.toBuf = (doWork, other) => (input) => { - let result = doWork(input, other) - return Buffer.from(result, 'hex') -} - -exports.fromString = (doWork, other) => (_input) => { - const input = Buffer.isBuffer(_input) ? _input.toString() : _input - return doWork(input, other) -} - -exports.fromNumberTo32BitBuf = (doWork, other) => (input) => { - let number = doWork(input, other) - const bytes = new Array(4) - - for (let i = 0; i < 4; i++) { - bytes[i] = number & 0xff - number = number >> 8 - } - - return Buffer.from(bytes) -} - -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":1438,"buffer":217}],474:[function(require,module,exports){ -'use strict' - -const SECOND = 1000 - -module.exports = { - maxProvidersPerRequest: 3, - providerRequestTimeout: 10 * SECOND, - hasBlockTimeout: 15 * SECOND, - provideTimeout: 15 * SECOND, - kMaxPriority: Math.pow(2, 31) - 1, - rebroadcastDelay: 10 * SECOND, - maxListeners: 1000 -} - -},{}],475:[function(require,module,exports){ -'use strict' - -const each = require('async/each') -const eachSeries = require('async/eachSeries') -const waterfall = require('async/waterfall') -const nextTick = require('async/nextTick') - -const map = require('async/map') -const debounce = require('just-debounce-it') - -const Message = require('../types/message') -const Wantlist = require('../types/wantlist') -const Ledger = require('./ledger') -const { logger, groupBy, pullAllWith, uniqWith } = require('../utils') - -const MAX_MESSAGE_SIZE = 512 * 1024 - -class DecisionEngine { - constructor (peerId, blockstore, network, stats) { - this._log = logger(peerId, 'engine') - this.blockstore = blockstore - this.network = network - this._stats = stats - - // A list of of ledgers by their partner id - this.ledgerMap = new Map() - this._running = false - - // List of tasks to be processed - this._tasks = [] - - this._outbox = debounce(this._processTasks.bind(this), 100) - } - - _sendBlocks (peer, blocks, cb) { - // split into messges of max 512 * 1024 bytes - const total = blocks.reduce((acc, b) => { - return acc + b.data.byteLength - }, 0) - - if (total < MAX_MESSAGE_SIZE) { - return this._sendSafeBlocks(peer, blocks, cb) - } - - let size = 0 - let batch = [] - let outstanding = blocks.length - - eachSeries(blocks, (b, cb) => { - outstanding-- - batch.push(b) - size += b.data.byteLength - - if (size >= MAX_MESSAGE_SIZE || - // need to ensure the last remaining items get sent - outstanding === 0) { - size = 0 - const nextBatch = batch.slice() - batch = [] - this._sendSafeBlocks(peer, nextBatch, (err) => { - if (err) { - this._log('sendblock error: %s', err.message) - } - // not returning the error, so we send as much as we can - // as otherwise `eachSeries` would cancel - cb() - }) - } else { - nextTick(cb) - } - }, cb) - } - - _sendSafeBlocks (peer, blocks, cb) { - const msg = new Message(false) - blocks.forEach((b) => msg.addBlock(b)) - - this.network.sendMessage(peer, msg, cb) - } - - _processTasks () { - if (!this._running || !this._tasks.length) { - return - } - - const tasks = this._tasks - this._tasks = [] - const entries = tasks.map((t) => t.entry) - const cids = entries.map((e) => e.cid) - const uniqCids = uniqWith((a, b) => a.equals(b), cids) - const groupedTasks = groupBy(task => task.target.toB58String(), tasks) - - waterfall([ - (callback) => map(uniqCids, (cid, cb) => { - this.blockstore.get(cid, cb) - }, callback), - (blocks, callback) => each(Object.values(groupedTasks), (tasks, cb) => { - // all tasks have the same target - const peer = tasks[0].target - const blockList = cids.map((cid) => { - return blocks.find(b => b.cid.equals(cid)) - }) - - this._sendBlocks(peer, blockList, (err) => { - if (err) { - // `_sendBlocks` actually doesn't return any errors - this._log.error('should never happen: ', err) - } else { - blockList.forEach((block) => this.messageSent(peer, block)) - } - - cb() - }) - }, callback) - ], (err) => { - this._tasks = [] - - if (err) { - this._log.error(err) - } - }) - } - - wantlistForPeer (peerId) { - const peerIdStr = peerId.toB58String() - if (!this.ledgerMap.has(peerIdStr)) { - return new Map() - } - - return this.ledgerMap.get(peerIdStr).wantlist.sortedEntries() - } - - ledgerForPeer (peerId) { - const peerIdStr = peerId.toB58String() - - const ledger = this.ledgerMap.get(peerIdStr) - if (!ledger) { - return null - } - return { - peer: ledger.partner.toPrint(), - value: ledger.debtRatio(), - sent: ledger.accounting.bytesSent, - recv: ledger.accounting.bytesRecv, - exchanged: ledger.exchangeCount - } - } - - peers () { - return Array.from(this.ledgerMap.values()).map((l) => l.partner) - } - - receivedBlocks (cids) { - if (!cids.length) { - return - } - // Check all connected peers if they want the block we received - this.ledgerMap.forEach((ledger) => { - cids - .map((cid) => ledger.wantlistContains(cid)) - .filter(Boolean) - .forEach((entry) => { - this._tasks.push({ - entry: entry, - target: ledger.partner - }) - }) - }) - this._outbox() - } - - // Handle incoming messages - messageReceived (peerId, msg, cb) { - const ledger = this._findOrCreate(peerId) - - if (msg.empty) { - return nextTick(cb) - } - - // If the message was a full wantlist clear the current one - if (msg.full) { - ledger.wantlist = new Wantlist() - } - - this._processBlocks(msg.blocks, ledger) - - if (msg.wantlist.size === 0) { - return nextTick(cb) - } - - let cancels = [] - let wants = [] - msg.wantlist.forEach((entry) => { - if (entry.cancel) { - ledger.cancelWant(entry.cid) - cancels.push(entry) - } else { - ledger.wants(entry.cid, entry.priority) - wants.push(entry) - } - }) - - this._cancelWants(ledger, peerId, cancels) - this._addWants(ledger, peerId, wants, cb) - } - - _cancelWants (ledger, peerId, entries) { - const id = peerId.toB58String() - - this._tasks = pullAllWith((t, e) => { - const sameTarget = t.target.toB58String() === id - const sameCid = t.entry.cid.equals(e.cid) - return sameTarget && sameCid - }, this._tasks, entries) - } - - _addWants (ledger, peerId, entries, callback) { - each(entries, (entry, cb) => { - // If we already have the block, serve it - this.blockstore.has(entry.cid, (err, exists) => { - if (err) { - this._log.error('failed existence check') - } else if (exists) { - this._tasks.push({ - entry: entry.entry, - target: peerId - }) - } - cb() - }) - }, () => { - this._outbox() - callback() - }) - } - - _processBlocks (blocks, ledger, callback) { - const cids = [] - blocks.forEach((b, cidStr) => { - this._log('got block (%s bytes)', b.data.length) - ledger.receivedBytes(b.data.length) - cids.push(b.cid) - }) - - this.receivedBlocks(cids) - } - - // Clear up all accounting things after message was sent - messageSent (peerId, block) { - const ledger = this._findOrCreate(peerId) - ledger.sentBytes(block ? block.data.length : 0) - if (block && block.cid) { - ledger.wantlist.remove(block.cid) - } - } - - numBytesSentTo (peerId) { - return this._findOrCreate(peerId).accounting.bytesSent - } - - numBytesReceivedFrom (peerId) { - return this._findOrCreate(peerId).accounting.bytesRecv - } - - peerDisconnected (peerId) { - // if (this.ledgerMap.has(peerId.toB58String())) { - // this.ledgerMap.delete(peerId.toB58String()) - // } - // - // TODO: figure out how to remove all other references - // in the peer request queue - } - - _findOrCreate (peerId) { - const peerIdStr = peerId.toB58String() - if (this.ledgerMap.has(peerIdStr)) { - return this.ledgerMap.get(peerIdStr) - } - - const l = new Ledger(peerId) - - this.ledgerMap.set(peerIdStr, l) - if (this._stats) { - this._stats.push(peerIdStr, 'peerCount', 1) - } - - return l - } - - start (callback) { - this._running = true - nextTick(() => callback()) - } - - stop (callback) { - this._running = false - nextTick(() => callback()) - } -} - -module.exports = DecisionEngine - -},{"../types/message":483,"../types/wantlist":486,"../utils":487,"./ledger":476,"async/each":106,"async/eachSeries":111,"async/map":137,"async/nextTick":140,"async/waterfall":152,"just-debounce-it":830}],476:[function(require,module,exports){ -'use strict' - -const Wantlist = require('../types/wantlist') - -class Ledger { - constructor (peerId) { - this.partner = peerId - this.wantlist = new Wantlist() - - this.exchangeCount = 0 - this.sentToPeer = new Map() - - this.accounting = { - bytesSent: 0, - bytesRecv: 0 - } - } - - sentBytes (n) { - this.exchangeCount++ - this.lastExchange = (new Date()).getTime() - this.accounting.bytesSent += n - } - - receivedBytes (n) { - this.exchangeCount++ - this.lastExchange = (new Date()).getTime() - this.accounting.bytesRecv += n - } - - wants (cid, priority) { - this.wantlist.add(cid, priority) - } - - cancelWant (cid) { - this.wantlist.remove(cid) - } - - wantlistContains (cid) { - return this.wantlist.contains(cid) - } - - debtRatio () { - return (this.accounting.bytesSent / (this.accounting.bytesRecv + 1)) // +1 is to prevent division by zero - } -} - -module.exports = Ledger - -},{"../types/wantlist":486}],477:[function(require,module,exports){ -'use strict' - -const waterfall = require('async/waterfall') -const reject = require('async/reject') -const each = require('async/each') -const series = require('async/series') -const map = require('async/map') -const nextTick = require('async/nextTick') - -const WantManager = require('./want-manager') -const Network = require('./network') -const DecisionEngine = require('./decision-engine') -const Notifications = require('./notifications') -const logger = require('./utils').logger -const Stats = require('./stats') - -const defaultOptions = { - statsEnabled: false, - statsComputeThrottleTimeout: 1000, - statsComputeThrottleMaxQueueSize: 1000 -} -const statsKeys = [ - 'blocksReceived', - 'dataReceived', - 'dupBlksReceived', - 'dupDataReceived', - 'blocksSent', - 'dataSent', - 'providesBufferLength', - 'wantListLength', - 'peerCount' -] - -/** - * JavaScript implementation of the Bitswap 'data exchange' protocol - * used by IPFS. - * - * @param {Libp2p} libp2p - * @param {Blockstore} blockstore - */ -class Bitswap { - constructor (libp2p, blockstore, options) { - this._libp2p = libp2p - this._log = logger(this.peerInfo.id) - - this._options = Object.assign({}, defaultOptions, options) - - // stats - this._stats = new Stats(statsKeys, { - enabled: this._options.statsEnabled, - computeThrottleTimeout: this._options.statsComputeThrottleTimeout, - computeThrottleMaxQueueSize: this._options.statsComputeThrottleMaxQueueSize - }) - - // the network delivers messages - this.network = new Network(libp2p, this, {}, this._stats) - - // local database - this.blockstore = blockstore - - this.engine = new DecisionEngine(this.peerInfo.id, blockstore, this.network, this._stats) - - // handle message sending - this.wm = new WantManager(this.peerInfo.id, this.network, this._stats) - - this.notifications = new Notifications(this.peerInfo.id) - } - - get peerInfo () { - return this._libp2p.peerInfo - } - - // handle messages received through the network - _receiveMessage (peerId, incoming, callback) { - this.engine.messageReceived(peerId, incoming, (err) => { - if (err) { - // Only logging the issue to process as much as possible - // of the message. Currently `messageReceived` does not - // return any errors, but this could change in the future. - this._log('failed to receive message', incoming) - } - - if (incoming.blocks.size === 0) { - return callback() - } - - const blocks = Array.from(incoming.blocks.values()) - - // quickly send out cancels, reduces chances of duplicate block receives - const wanted = blocks - .filter((b) => this.wm.wantlist.contains(b.cid)) - .map((b) => b.cid) - - this.wm.cancelWants(wanted) - - each( - blocks, - (b, cb) => { - const wasWanted = wanted.includes(b.cid) - this._handleReceivedBlock(peerId, b, wasWanted, cb) - }, - callback - ) - }) - } - - _handleReceivedBlock (peerId, block, wasWanted, callback) { - this._log('received block') - - waterfall([ - (cb) => this.blockstore.has(block.cid, cb), - (has, cb) => { - this._updateReceiveCounters(peerId.toB58String(), block, has) - if (has || !wasWanted) { - return nextTick(cb) - } - - this._putBlock(block, cb) - } - ], callback) - } - - _updateReceiveCounters (peerId, block, exists) { - this._stats.push(peerId, 'blocksReceived', 1) - this._stats.push(peerId, 'dataReceived', block.data.length) - - if (exists) { - this._stats.push(peerId, 'dupBlksReceived', 1) - this._stats.push(peerId, 'dupDataReceived', block.data.length) - } - } - - // handle errors on the receiving channel - _receiveError (err) { - this._log.error('ReceiveError: %s', err.message) - } - - // handle new peers - _onPeerConnected (peerId) { - this.wm.connected(peerId) - } - - // handle peers being disconnected - _onPeerDisconnected (peerId) { - this.wm.disconnected(peerId) - this.engine.peerDisconnected(peerId) - this._stats.disconnected(peerId) - } - - _putBlock (block, callback) { - this.blockstore.put(block, (err) => { - if (err) { - return callback(err) - } - - this.notifications.hasBlock(block) - this.network.provide(block.cid, (err) => { - if (err) { - this._log.error('Failed to provide: %s', err.message) - } - }) - - this.engine.receivedBlocks([block.cid]) - callback() - }) - } - - enableStats () { - this._stats.enable() - } - - disableStats () { - this._stats.disable() - } - - /** - * Return the current wantlist for a given `peerId` - * - * @param {PeerId} peerId - * @returns {Wantlist} - */ - wantlistForPeer (peerId) { - return this.engine.wantlistForPeer(peerId) - } - - /** - * Return ledger information for a given `peerId` - * - * @param {PeerId} peerId - * @returns {?Object} - */ - ledgerForPeer (peerId) { - return this.engine.ledgerForPeer(peerId) - } - - /** - * Fetch a given block by cid. If the block is in the local - * blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us. - * - * @param {CID} cid - * @param {function(Error, Block)} callback - * @returns {void} - */ - get (cid, callback) { - this.getMany([cid], (err, blocks) => { - if (err) { - return callback(err) - } - - if (blocks && blocks.length > 0) { - callback(null, blocks[0]) - } else { - // when a unwant happens - callback() - } - }) - } - - /** - * Fetch a a list of blocks by cid. If the blocks are in the local - * blockstore they are returned, otherwise the blocks are added to the wantlist and returned once another node sends them to us. - * - * @param {Array} cids - * @param {function(Error, Blocks)} callback - * @returns {void} - */ - getMany (cids, callback) { - let pendingStart = cids.length - const wantList = [] - let promptedNetwork = false - - const getFromOutside = (cid, cb) => { - wantList.push(cid) - - this.notifications.wantBlock( - cid, - // called on block receive - (block) => { - this.wm.cancelWants([cid]) - cb(null, block) - }, - // called on unwant - () => { - this.wm.cancelWants([cid]) - cb(null, undefined) - } - ) - - if (!pendingStart) { - this.wm.wantBlocks(wantList) - } - } - - map(cids, (cid, cb) => { - waterfall( - [ - (cb) => this.blockstore.has(cid, cb), - (has, cb) => { - pendingStart-- - if (has) { - if (!pendingStart) { - this.wm.wantBlocks(wantList) - } - return this.blockstore.get(cid, cb) - } - - if (!promptedNetwork) { - promptedNetwork = true - this.network.findAndConnect(cids[0], (err) => { - if (err) { - this._log.error(err) - } - }) - } - - // we don't have the block here - getFromOutside(cid, cb) - } - ], - cb) - }, callback) - } - - // removes the given cids from the wantlist independent of any ref counts - unwant (cids) { - if (!Array.isArray(cids)) { - cids = [cids] - } - - this.wm.unwantBlocks(cids) - cids.forEach((cid) => this.notifications.unwantBlock(cid)) - } - - // removes the given keys from the want list - cancelWants (cids) { - if (!Array.isArray(cids)) { - cids = [cids] - } - this.wm.cancelWants(cids) - } - - /** - * Put the given block to the underlying blockstore and - * send it to nodes that have it in their wantlist. - * - * @param {Block} block - * @param {function(Error)} callback - * @returns {void} - */ - put (block, callback) { - this._log('putting block') - - waterfall([ - (cb) => this.blockstore.has(block.cid, cb), - (has, cb) => { - if (has) { - return nextTick(cb) - } - - this._putBlock(block, cb) - } - ], callback) - } - - /** - * Put the given blocks to the underlying blockstore and - * send it to nodes that have it them their wantlist. - * - * @param {Array} blocks - * @param {function(Error)} callback - * @returns {void} - */ - putMany (blocks, callback) { - waterfall([ - (cb) => reject(blocks, (b, cb) => { - this.blockstore.has(b.cid, cb) - }, cb), - (newBlocks, cb) => this.blockstore.putMany(newBlocks, (err) => { - if (err) { - return cb(err) - } - - newBlocks.forEach((block) => { - this.notifications.hasBlock(block) - this.engine.receivedBlocks([block.cid]) - this.network.provide(block.cid, (err) => { - if (err) { - this._log.error('Failed to provide: %s', err.message) - } - }) - }) - cb() - }) - ], callback) - } - - /** - * Get the current list of wants. - * - * @returns {Iterator} - */ - getWantlist () { - return this.wm.wantlist.entries() - } - - /** - * Get the current list of partners. - * - * @returns {Array} - */ - peers () { - return this.engine.peers() - } - - /** - * Get stats about the bitswap node. - * - * @returns {Object} - */ - stat () { - return this._stats - } - - /** - * Start the bitswap node. - * - * @param {function(Error)} callback - * - * @returns {void} - */ - start (callback) { - series([ - (cb) => this.wm.start(cb), - (cb) => this.network.start(cb), - (cb) => this.engine.start(cb) - ], callback) - } - - /** - * Stop the bitswap node. - * - * @param {function(Error)} callback - * - * @returns {void} - */ - stop (callback) { - this._stats.stop() - series([ - (cb) => this.wm.stop(cb), - (cb) => this.network.stop(cb), - (cb) => this.engine.stop(cb) - ], callback) - } -} - -module.exports = Bitswap - -},{"./decision-engine":475,"./network":478,"./notifications":479,"./stats":480,"./utils":487,"./want-manager":488,"async/each":106,"async/map":137,"async/nextTick":140,"async/reject":143,"async/series":145,"async/waterfall":152}],478:[function(require,module,exports){ -'use strict' - -const lp = require('pull-length-prefixed') -const pull = require('pull-stream') -const waterfall = require('async/waterfall') -const each = require('async/each') -const nextTick = require('async/nextTick') - -const Message = require('./types/message') -const CONSTANTS = require('./constants') -const logger = require('./utils').logger - -const BITSWAP100 = '/ipfs/bitswap/1.0.0' -const BITSWAP110 = '/ipfs/bitswap/1.1.0' - -class Network { - constructor (libp2p, bitswap, options, stats) { - this._log = logger(libp2p.peerInfo.id, 'network') - options = options || {} - this.libp2p = libp2p - this.bitswap = bitswap - this.b100Only = options.b100Only || false - - this._stats = stats - this._running = false - } - - start (callback) { - this._running = true - // bind event listeners - this._onPeerConnect = this._onPeerConnect.bind(this) - this._onPeerDisconnect = this._onPeerDisconnect.bind(this) - - this._onConnection = this._onConnection.bind(this) - this.libp2p.handle(BITSWAP100, this._onConnection) - if (!this.b100Only) { this.libp2p.handle(BITSWAP110, this._onConnection) } - - this.libp2p.on('peer:connect', this._onPeerConnect) - this.libp2p.on('peer:disconnect', this._onPeerDisconnect) - - // All existing connections are like new ones for us - this.libp2p.peerBook - .getAllArray() - .filter((peer) => peer.isConnected()) - .forEach((peer) => this._onPeerConnect((peer))) - - nextTick(() => callback()) - } - - stop (callback) { - this._running = false - - this.libp2p.unhandle(BITSWAP100) - if (!this.b100Only) { this.libp2p.unhandle(BITSWAP110) } - - this.libp2p.removeListener('peer:connect', this._onPeerConnect) - this.libp2p.removeListener('peer:disconnect', this._onPeerDisconnect) - - nextTick(() => callback()) - } - - // Handles both types of bitswap messgages - _onConnection (protocol, conn) { - if (!this._running) { return } - this._log('incomming new bitswap connection: %s', protocol) - - pull( - conn, - lp.decode(), - pull.asyncMap((data, cb) => Message.deserialize(data, cb)), - pull.asyncMap((msg, cb) => { - conn.getPeerInfo((err, peerInfo) => { - if (err) { return cb(err) } - - // this._log('data from', peerInfo.id.toB58String()) - this.bitswap._receiveMessage(peerInfo.id, msg, cb) - }) - }), - pull.onEnd((err) => { - this._log('ending connection') - if (err) { - this.bitswap._receiveError(err) - } - }) - ) - } - - _onPeerConnect (peerInfo) { - if (!this._running) { return } - - this.bitswap._onPeerConnected(peerInfo.id) - } - - _onPeerDisconnect (peerInfo) { - if (!this._running) { return } - - this.bitswap._onPeerDisconnected(peerInfo.id) - } - - findProviders (cid, maxProviders, callback) { - this.libp2p.contentRouting.findProviders(cid, { - maxTimeout: CONSTANTS.providerRequestTimeout, - maxNumProviders: maxProviders - }, callback) - } - - findAndConnect (cid, callback) { - waterfall([ - (cb) => this.findProviders(cid, CONSTANTS.maxProvidersPerRequest, cb), - (provs, cb) => { - this._log('connecting to providers', provs.map((p) => p.id.toB58String())) - each(provs, (p, cb) => this.connectTo(p, cb)) - } - ], callback) - } - - provide (cid, callback) { - this.libp2p.contentRouting.provide(cid, callback) - } - - // Connect to the given peer - // Send the given msg (instance of Message) to the given peer - sendMessage (peer, msg, callback) { - if (!this._running) { return callback(new Error(`network isn't running`)) } - - const stringId = peer.toB58String() ? peer.toB58String() : peer.id.toB58String() - this._log('sendMessage to %s', stringId, msg) - - this._dialPeer(peer, (err, conn, protocol) => { - if (err) { - return callback(err) - } - - let serialized - switch (protocol) { - case BITSWAP100: - serialized = msg.serializeToBitswap100() - break - case BITSWAP110: - serialized = msg.serializeToBitswap110() - break - default: - return callback(new Error('Unkown protocol: ' + protocol)) - } - // TODO: why doesn't the error get propageted back?? - writeMessage(conn, serialized, (err) => { - if (err) { - this._log.error(err) - } - }) - callback() - this._updateSentStats(peer, msg.blocks) - }) - } - - connectTo (peer, callback) { - if (!this._running) { return callback(new Error(`network isn't running`)) } - - this.libp2p.dial(peer, callback) - } - - // Dial to the peer and try to use the most recent Bitswap - _dialPeer (peer, callback) { - // Attempt Bitswap 1.1.0 - this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => { - if (err) { - // Attempt Bitswap 1.0.0 - this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => { - if (err) { return callback(err) } - - callback(null, conn, BITSWAP100) - }) - - return - } - - callback(null, conn, BITSWAP110) - }) - } - - _updateSentStats (peer, blocks) { - const peerId = peer.toB58String() - if (this._stats) { - blocks.forEach((block) => this._stats.push(peerId, 'dataSent', block.data.length)) - this._stats.push(peerId, 'blocksSent', blocks.size) - } - } -} - -function writeMessage (conn, msg, callback) { - pull( - pull.values([msg]), - lp.encode(), - conn, - pull.onEnd(callback) - ) -} - -module.exports = Network - -},{"./constants":474,"./types/message":483,"./utils":487,"async/each":106,"async/nextTick":140,"async/waterfall":152,"pull-length-prefixed":1475,"pull-stream":1495}],479:[function(require,module,exports){ -'use strict' - -const EventEmitter = require('events').EventEmitter - -const CONSTANTS = require('./constants') -const logger = require('./utils').logger - -const unwantEvent = (c) => `unwant:${c}` -const blockEvent = (c) => `block:${c}` - -/** - * Internal module used to track events about incoming blocks, - * wants and unwants. - * - * @param {PeerId} peerId - * @private - */ -class Notifications extends EventEmitter { - constructor (peerId) { - super() - - this.setMaxListeners(CONSTANTS.maxListeners) - - this._log = logger(peerId, 'notif') - - this._unwantListeners = {} - this._blockListeners = {} - } - - /** - * Signal the system that we received `block`. - * - * @param {Block} block - * @return {void} - */ - hasBlock (block) { - const cidStr = block.cid.toString('base58btc') - const str = `block:${cidStr}` - this._log(str) - this.emit(str, block) - } - - /** - * Signal the system that we are waiting to receive the - * block associated with the given `cid`. - * - * @param {CID} cid - * @param {function(Block)} onBlock - called when the block is received - * @param {function()} onUnwant - called when the block is unwanted - * @returns {void} - */ - wantBlock (cid, onBlock, onUnwant) { - const cidStr = cid.toString('base58btc') - this._log(`wantBlock:${cidStr}`) - - this._unwantListeners[cidStr] = () => { - this._log(`manual unwant: ${cidStr}`) - this._cleanup(cidStr) - onUnwant() - } - - this._blockListeners[cidStr] = (block) => { - this._cleanup(cidStr) - onBlock(block) - } - - this.once( - unwantEvent(cidStr), - this._unwantListeners[cidStr] - ) - this.once( - blockEvent(cidStr), - this._blockListeners[cidStr] - ) - } - - /** - * Signal that the block is not wanted anymore. - * - * @param {CID} cid - the CID of the block that is not wanted anymore. - * @returns {void} - */ - unwantBlock (cid) { - const str = `unwant:${cid.toString('base58btc')}` - this._log(str) - this.emit(str) - } - - /** - * Internal method to clean up once a block was received or unwanted. - * - * @private - * @param {string} cidStr - * @returns {void} - */ - _cleanup (cidStr) { - if (this._unwantListeners[cidStr]) { - this.removeListener( - unwantEvent(cidStr), - this._unwantListeners[cidStr] - ) - delete this._unwantListeners[cidStr] - } - - if (this._blockListeners[cidStr]) { - this.removeListener( - blockEvent(cidStr), - this._blockListeners[cidStr] - ) - delete this._blockListeners[cidStr] - } - } -} - -module.exports = Notifications - -},{"./constants":474,"./utils":487,"events":370}],480:[function(require,module,exports){ -'use strict' - -const EventEmitter = require('events') -const Stat = require('./stat') - -const defaultOptions = { - movingAverageIntervals: [ - 60 * 1000, // 1 minute - 5 * 60 * 1000, // 5 minutes - 15 * 60 * 1000 // 15 minutes - ] -} - -class Stats extends EventEmitter { - constructor (initialCounters, _options) { - super() - - const options = Object.assign({}, defaultOptions, _options) - - if (typeof options.computeThrottleTimeout !== 'number') { - throw new Error('need computeThrottleTimeout') - } - - if (typeof options.computeThrottleMaxQueueSize !== 'number') { - throw new Error('need computeThrottleMaxQueueSize') - } - - this._initialCounters = initialCounters - this._options = options - this._enabled = this._options.enabled - - this._global = new Stat(initialCounters, options) - this._global.on('update', (stats) => this.emit('update', stats)) - - this._peers = new Map() - } - - enable () { - this._enabled = true - this._options.enabled = true - this._global.enable() - } - - disable () { - this._enabled = false - this._options.enabled = false - this._global.disable() - } - - stop () { - this._enabled = false - this._global.stop() - for (let peerStat of this._peers) { - peerStat[1].stop() - } - } - - get snapshot () { - return this._global.snapshot - } - - get movingAverages () { - return this._global.movingAverages - } - - forPeer (peerId) { - if (peerId.toB58String) { - peerId = peerId.toB58String() - } - return this._peers.get(peerId) - } - - push (peer, counter, inc) { - if (this._enabled) { - this._global.push(counter, inc) - - if (peer) { - let peerStats = this._peers.get(peer) - if (!peerStats) { - peerStats = new Stat(this._initialCounters, this._options) - this._peers.set(peer, peerStats) - } - - peerStats.push(counter, inc) - } - } - } - - disconnected (peer) { - const peerId = peer.toB58String() - const peerStats = this._peers.get(peerId) - if (peerStats) { - peerStats.stop() - this._peers.delete(peerId) - } - } -} - -module.exports = Stats - -},{"./stat":481,"events":370}],481:[function(require,module,exports){ -'use strict' - -const EventEmitter = require('events') -const Big = require('bignumber.js') -const MovingAverage = require('moving-average') - -class Stats extends EventEmitter { - constructor (initialCounters, options) { - super() - - this._options = options - this._queue = [] - this._stats = {} - - this._frequencyLastTime = Date.now() - this._frequencyAccumulators = {} - this._movingAverages = {} - - this._update = this._update.bind(this) - - initialCounters.forEach((key) => { - this._stats[key] = Big(0) - this._movingAverages[key] = {} - this._options.movingAverageIntervals.forEach((interval) => { - const ma = this._movingAverages[key][interval] = MovingAverage(interval) - ma.push(this._frequencyLastTime, 0) - }) - }) - - this._enabled = this._options.enabled - } - - enable () { - this._enabled = true - } - - disable () { - this._disabled = true - } - - stop () { - if (this._timeout) { - clearTimeout(this._timeout) - } - } - - get snapshot () { - return Object.assign({}, this._stats) - } - - get movingAverages () { - return Object.assign({}, this._movingAverages) - } - - push (counter, inc) { - if (this._enabled) { - this._queue.push([counter, inc, Date.now()]) - this._resetComputeTimeout() - } - } - - _resetComputeTimeout () { - if (this._timeout) { - clearTimeout(this._timeout) - } - this._timeout = setTimeout(this._update, this._nextTimeout()) - } - - _nextTimeout () { - // calculate the need for an update, depending on the queue length - const urgency = this._queue.length / this._options.computeThrottleMaxQueueSize - return Math.max(this._options.computeThrottleTimeout * (1 - urgency), 0) - } - - _update () { - this._timeout = null - if (this._queue.length) { - let last - while (this._queue.length) { - const op = last = this._queue.shift() - this._applyOp(op) - } - - this._updateFrequency(last[2]) // contains timestamp of last op - - this.emit('update', this._stats) - } - } - - _updateFrequency (latestTime) { - const timeDiff = latestTime - this._frequencyLastTime - - Object.keys(this._stats).forEach((key) => { - this._updateFrequencyFor(key, timeDiff, latestTime) - }) - - this._frequencyLastTime = latestTime - } - - _updateFrequencyFor (key, timeDiffMS, latestTime) { - const count = this._frequencyAccumulators[key] || 0 - this._frequencyAccumulators[key] = 0 - const hz = (count / timeDiffMS) * 1000 - - let movingAverages = this._movingAverages[key] - if (!movingAverages) { - movingAverages = this._movingAverages[key] = {} - } - this._options.movingAverageIntervals.forEach((movingAverageInterval) => { - let movingAverage = movingAverages[movingAverageInterval] - if (!movingAverage) { - movingAverage = movingAverages[movingAverageInterval] = MovingAverage(movingAverageInterval) - } - movingAverage.push(latestTime, hz) - }) - } - - _applyOp (op) { - const key = op[0] - const inc = op[1] - - if (typeof inc !== 'number') { - throw new Error('invalid increment number:', inc) - } - - let n - - if (!this._stats.hasOwnProperty(key)) { - n = this._stats[key] = Big(0) - } else { - n = this._stats[key] - } - this._stats[key] = n.plus(inc) - - if (!this._frequencyAccumulators[key]) { - this._frequencyAccumulators[key] = 0 - } - this._frequencyAccumulators[key] += inc - } -} - -module.exports = Stats - -},{"bignumber.js":464,"events":370,"moving-average":1309}],482:[function(require,module,exports){ -'use strict' - -const WantlistEntry = require('../wantlist').Entry -const CID = require('cids') -const assert = require('assert') - -module.exports = class BitswapMessageEntry { - constructor (cid, priority, cancel) { - assert(CID.isCID(cid), 'needs valid cid') - this.entry = new WantlistEntry(cid, priority) - this.cancel = Boolean(cancel) - } - - get cid () { - return this.entry.cid - } - - set cid (cid) { - this.entry.cid = cid - } - - get priority () { - return this.entry.priority - } - - set priority (val) { - this.entry.priority = val - } - - get [Symbol.toStringTag] () { - const cidStr = this.cid.toString('base58btc') - return `BitswapMessageEntry ${cidStr} ` - } - - equals (other) { - return (this.cancel === other.cancel) && - this.entry.equals(other.entry) - } -} - -},{"../wantlist":486,"assert":78,"cids":222}],483:[function(require,module,exports){ -'use strict' - -const protons = require('protons') -const Block = require('ipfs-block') -const isEqualWith = require('lodash.isequalwith') -const assert = require('assert') -const each = require('async/each') -const nextTick = require('async/nextTick') -const CID = require('cids') -const codecName = require('multicodec/src/name-table') -const vd = require('varint-decoder') -const multihashing = require('multihashing-async') - -const pbm = protons(require('./message.proto')) -const Entry = require('./entry') - -class BitswapMessage { - constructor (full) { - this.full = full - this.wantlist = new Map() - this.blocks = new Map() - } - - get empty () { - return this.blocks.size === 0 && - this.wantlist.size === 0 - } - - addEntry (cid, priority, cancel) { - assert(cid && CID.isCID(cid), 'must be a valid cid') - const cidStr = cid.toString('base58btc') - - const entry = this.wantlist.get(cidStr) - - if (entry) { - entry.priority = priority - entry.cancel = Boolean(cancel) - } else { - this.wantlist.set(cidStr, new Entry(cid, priority, cancel)) - } - } - - addBlock (block) { - assert(Block.isBlock(block), 'must be a valid cid') - const cidStr = block.cid.toString('base58btc') - this.blocks.set(cidStr, block) - } - - cancel (cid) { - assert(CID.isCID(cid), 'must be a valid cid') - const cidStr = cid.toString('base58btc') - this.wantlist.delete(cidStr) - this.addEntry(cid, 0, true) - } - - /* - * Serializes to Bitswap Message protobuf of - * version 1.0.0 - */ - serializeToBitswap100 () { - const msg = { - wantlist: { - entries: Array.from(this.wantlist.values()).map((entry) => { - return { - block: entry.cid.buffer, // cid - priority: Number(entry.priority), - cancel: Boolean(entry.cancel) - } - }) - }, - blocks: Array.from(this.blocks.values()) - .map((block) => block.data) - } - - if (this.full) { - msg.wantlist.full = true - } - - return pbm.Message.encode(msg) - } - - /* - * Serializes to Bitswap Message protobuf of - * version 1.1.0 - */ - serializeToBitswap110 () { - const msg = { - wantlist: { - entries: Array.from(this.wantlist.values()).map((entry) => { - return { - block: entry.cid.buffer, // cid - priority: Number(entry.priority), - cancel: Boolean(entry.cancel) - } - }) - }, - payload: [] - } - - if (this.full) { - msg.wantlist.full = true - } - - this.blocks.forEach((block) => { - msg.payload.push({ - prefix: block.cid.prefix, - data: block.data - }) - }) - - return pbm.Message.encode(msg) - } - - equals (other) { - const cmp = (a, b) => { - if (a.equals && typeof a.equals === 'function') { - return a.equals(b) - } - } - - if (this.full !== other.full || - !isEqualWith(this.wantlist, other.wantlist, cmp) || - !isEqualWith(this.blocks, other.blocks, cmp) - ) { - return false - } - - return true - } - - get [Symbol.toStringTag] () { - const list = Array.from(this.wantlist.keys()) - const blocks = Array.from(this.blocks.keys()) - return `BitswapMessage ` - } -} - -BitswapMessage.deserialize = (raw, callback) => { - let decoded - try { - decoded = pbm.Message.decode(raw) - } catch (err) { - return nextTick(() => callback(err)) - } - - const isFull = (decoded.wantlist && decoded.wantlist.full) || false - const msg = new BitswapMessage(isFull) - - if (decoded.wantlist) { - decoded.wantlist.entries.forEach((entry) => { - // note: entry.block is the CID here - let cid - try { - cid = new CID(entry.block) - } catch (err) { - return callback(err) - } - msg.addEntry(cid, entry.priority, entry.cancel) - }) - } - - // Bitswap 1.0.0 - // decoded.blocks are just the byte arrays - if (decoded.blocks.length > 0) { - return each(decoded.blocks, (b, cb) => { - multihashing(b, 'sha2-256', (err, hash) => { - if (err) { - return cb(err) - } - let cid - try { - cid = new CID(hash) - } catch (err) { - return callback(err) - } - msg.addBlock(new Block(b, cid)) - cb() - }) - }, (err) => { - if (err) { - return callback(err) - } - callback(null, msg) - }) - } - - // Bitswap 1.1.0 - if (decoded.payload.length > 0) { - return each(decoded.payload, (p, cb) => { - if (!p.prefix || !p.data) { - return nextTick(cb) - } - const values = vd(p.prefix) - const cidVersion = values[0] - const multicodec = values[1] - const hashAlg = values[2] - // const hashLen = values[3] // We haven't need to use this so far - multihashing(p.data, hashAlg, (err, hash) => { - if (err) { - return cb(err) - } - - let cid - try { - cid = new CID(cidVersion, codecName[multicodec.toString('16')], hash) - } catch (err) { - return cb(err) - } - - msg.addBlock(new Block(p.data, cid)) - cb() - }) - }, (err) => { - if (err) { - return callback(err) - } - callback(null, msg) - }) - } - - callback(null, msg) -} - -BitswapMessage.Entry = Entry -module.exports = BitswapMessage - -},{"./entry":482,"./message.proto":484,"assert":78,"async/each":106,"async/nextTick":140,"cids":222,"ipfs-block":491,"lodash.isequalwith":1214,"multicodec/src/name-table":1326,"multihashing-async":472,"protons":1454,"varint-decoder":1782}],484:[function(require,module,exports){ -'use strict' - -// from: https://github.com/ipfs/go-ipfs/blob/master/exchange/bitswap/message/pb/message.proto - -module.exports = ` - message Message { - message Wantlist { - message Entry { - // changed from string to bytes, it makes a difference in JavaScript - optional bytes block = 1; // the block cid (cidV0 in bitswap 1.0.0, cidV1 in bitswap 1.1.0) - optional int32 priority = 2; // the priority (normalized). default to 1 - optional bool cancel = 3; // whether this revokes an entry - } - - repeated Entry entries = 1; // a list of wantlist entries - optional bool full = 2; // whether this is the full wantlist. default to false - } - - message Block { - optional bytes prefix = 1; // CID prefix (cid version, multicodec and multihash prefix (type + length) - optional bytes data = 2; - } - - optional Wantlist wantlist = 1; - repeated bytes blocks = 2; // used to send Blocks in bitswap 1.0.0 - repeated Block payload = 3; // used to send Blocks in bitswap 1.1.0 - } -` - -},{}],485:[function(require,module,exports){ -'use strict' - -const assert = require('assert') -const CID = require('cids') - -class WantListEntry { - constructor (cid, priority) { - assert(CID.isCID(cid), 'must be valid CID') - - // Keep track of how many requests we have for this key - this._refCounter = 1 - - this.cid = cid - this.priority = priority || 1 - } - - inc () { - this._refCounter += 1 - } - - dec () { - this._refCounter = Math.max(0, this._refCounter - 1) - } - - hasRefs () { - return this._refCounter > 0 - } - - // So that console.log prints a nice description of this object - get [Symbol.toStringTag] () { - const cidStr = this.cid.toString('base58btc') - return `WantlistEntry ` - } - - equals (other) { - return (this._refCounter === other._refCounter) && - this.cid.equals(other.cid) && - this.priority === other.priority - } -} - -module.exports = WantListEntry - -},{"assert":78,"cids":222}],486:[function(require,module,exports){ -'use strict' - -const { sortBy } = require('../../utils') -const Entry = require('./entry') - -class Wantlist { - constructor (stats) { - this.set = new Map() - this._stats = stats - } - - get length () { - return this.set.size - } - - add (cid, priority) { - const cidStr = cid.toString('base58btc') - const entry = this.set.get(cidStr) - - if (entry) { - entry.inc() - entry.priority = priority - } else { - this.set.set(cidStr, new Entry(cid, priority)) - if (this._stats) { - this._stats.push(null, 'wantListSize', 1) - } - } - } - - remove (cid) { - const cidStr = cid.toString('base58btc') - const entry = this.set.get(cidStr) - - if (!entry) { - return - } - - entry.dec() - - // only delete when no refs are held - if (entry.hasRefs()) { - return - } - - this.set.delete(cidStr) - if (this._stats) { - this._stats.push(null, 'wantListSize', -1) - } - } - - removeForce (cidStr) { - if (this.set.has(cidStr)) { - this.set.delete(cidStr) - } - } - - forEach (fn) { - return this.set.forEach(fn) - } - - entries () { - return this.set.entries() - } - - sortedEntries () { - return new Map(sortBy(o => o[1].key, Array.from(this.set.entries()))) - } - - contains (cid) { - const cidStr = cid.toString('base58btc') - return this.set.get(cidStr) - } -} - -Wantlist.Entry = Entry -module.exports = Wantlist - -},{"../../utils":487,"./entry":485}],487:[function(require,module,exports){ -'use strict' - -const debug = require('debug') - -/** - * Creates a logger for the given subsystem - * - * @param {PeerId} [id] - * @param {string} [subsystem] - * @returns {debug} - * - * @private - */ -const logger = (id, subsystem) => { - const name = ['bitswap'] - if (subsystem) { - name.push(subsystem) - } - if (id) { - name.push(`${id.toB58String().slice(0, 8)}`) - } - const logger = debug(name.join(':')) - logger.error = debug(name.concat(['error']).join(':')) - - return logger -} - -const includesWith = (pred, x, list) => { - let idx = 0 - const len = list.length - while (idx < len) { - if (pred(x, list[idx])) { - return true - } - idx += 1 - } - return false -} - -const uniqWith = (pred, list) => { - let idx = 0 - const len = list.length - const result = [] - let item - - while (idx < len) { - item = list[idx] - if (!includesWith(pred, item, result)) { - result[result.length] = item - } - idx += 1 - } - return result -} - -const groupBy = (pred, list) => { - return list.reduce((acc, v) => { - const k = pred(v) - - if (acc[k]) { - acc[k].push(v) - } else { - acc[k] = [v] - } - return acc - }, {}) -} - -const pullAllWith = (pred, list, values) => { - return list.filter(i => { - return !includesWith(pred, i, values) - }) -} - -const sortBy = (fn, list) => { - return Array.prototype.slice.call(list, 0).sort((a, b) => { - const aa = fn(a) - const bb = fn(b) - return aa < bb ? -1 : aa > bb ? 1 : 0 - }) -} - -module.exports = { - logger, - includesWith, - uniqWith, - groupBy, - pullAllWith, - sortBy -} - -},{"debug":465}],488:[function(require,module,exports){ -'use strict' - -const nextTick = require('async/nextTick') -const Message = require('../types/message') -const Wantlist = require('../types/wantlist') -const CONSTANTS = require('../constants') -const MsgQueue = require('./msg-queue') -const logger = require('../utils').logger - -module.exports = class WantManager { - constructor (peerId, network, stats) { - this.peers = new Map() - this.wantlist = new Wantlist(stats) - - this.network = network - this._stats = stats - - this._peerId = peerId - this._log = logger(peerId, 'want') - } - - _addEntries (cids, cancel, force) { - const entries = cids.map((cid, i) => { - return new Message.Entry(cid, CONSTANTS.kMaxPriority - i, cancel) - }) - - entries.forEach((e) => { - // add changes to our wantlist - if (e.cancel) { - if (force) { - this.wantlist.removeForce(e.cid) - } else { - this.wantlist.remove(e.cid) - } - } else { - this._log('adding to wl') - this.wantlist.add(e.cid, e.priority) - } - }) - - // broadcast changes - for (let p of this.peers.values()) { - p.addEntries(entries) - } - } - - _startPeerHandler (peerId) { - let mq = this.peers.get(peerId.toB58String()) - - if (mq) { - mq.refcnt++ - return - } - - mq = new MsgQueue(this._peerId, peerId, this.network) - - // new peer, give them the full wantlist - const fullwantlist = new Message(true) - - for (let entry of this.wantlist.entries()) { - fullwantlist.addEntry(entry[1].cid, entry[1].priority) - } - - mq.addMessage(fullwantlist) - - this.peers.set(peerId.toB58String(), mq) - return mq - } - - _stopPeerHandler (peerId) { - const mq = this.peers.get(peerId.toB58String()) - - if (!mq) { - return - } - - mq.refcnt-- - if (mq.refcnt > 0) { - return - } - - this.peers.delete(peerId.toB58String()) - } - - // add all the cids to the wantlist - wantBlocks (cids) { - this._addEntries(cids, false) - } - - // remove blocks of all the given keys without respecting refcounts - unwantBlocks (cids) { - this._log('unwant blocks: %s', cids.length) - this._addEntries(cids, true, true) - } - - // cancel wanting all of the given keys - cancelWants (cids) { - this._log('cancel wants: %s', cids.length) - this._addEntries(cids, true) - } - - // Returns a list of all currently connected peers - connectedPeers () { - return Array.from(this.peers.keys()) - } - - connected (peerId) { - this._startPeerHandler(peerId) - } - - disconnected (peerId) { - this._stopPeerHandler(peerId) - } - - start (callback) { - // resend entire wantlist every so often - this.timer = setInterval(() => { - this._log('resend full-wantlist') - const fullwantlist = new Message(true) - this.wantlist.forEach((entry) => { - fullwantlist.addEntry(entry.cid, entry.priority) - }) - - this.peers.forEach((p) => p.addMessage(fullwantlist)) - }, 60 * 1000) - - nextTick(() => callback()) - } - - stop (callback) { - this.peers.forEach((mq) => this.disconnected(mq.peerId)) - - clearInterval(this.timer) - nextTick(() => callback()) - } -} - -},{"../constants":474,"../types/message":483,"../types/wantlist":486,"../utils":487,"./msg-queue":489,"async/nextTick":140}],489:[function(require,module,exports){ -'use strict' - -const debounce = require('just-debounce-it') - -const Message = require('../types/message') -const logger = require('../utils').logger - -module.exports = class MsgQueue { - constructor (selfPeerId, otherPeerId, network) { - this.peerId = otherPeerId - this.network = network - this.refcnt = 1 - - this._entries = [] - this._log = logger(selfPeerId, 'msgqueue', otherPeerId.toB58String().slice(0, 8)) - this.sendEntries = debounce(this._sendEntries.bind(this), 200) - } - - addMessage (msg) { - if (msg.empty) { - return - } - - this.send(msg) - } - - addEntries (entries) { - this._entries = this._entries.concat(entries) - this.sendEntries() - } - - _sendEntries () { - if (!this._entries.length) { - return - } - - const msg = new Message(false) - this._entries.forEach((entry) => { - if (entry.cancel) { - msg.cancel(entry.cid) - } else { - msg.addEntry(entry.cid, entry.priority) - } - }) - this._entries = [] - this.addMessage(msg) - } - - send (msg) { - this.network.connectTo(this.peerId, (err) => { - if (err) { - this._log.error('cant connect to peer %s: %s', this.peerId.toB58String(), err.message) - return - } - - this._log('sending message') - this.network.sendMessage(this.peerId, msg, (err) => { - if (err) { - this._log.error('send error: %s', err.message) - } - }) - }) - } -} - -},{"../types/message":483,"../utils":487,"just-debounce-it":830}],490:[function(require,module,exports){ -'use strict' - -const asyncMap = require('async/map') - -/** - * BlockService is a hybrid block datastore. It stores data in a local - * datastore and may retrieve data from a remote Exchange. - * It uses an internal `datastore.Datastore` instance to store values. - */ -class BlockService { - /** - * Create a new BlockService - * - * @param {IPFSRepo} ipfsRepo - */ - constructor (ipfsRepo) { - this._repo = ipfsRepo - this._bitswap = null - } - - /** - * Add a bitswap instance that communicates with the - * network to retreive blocks that are not in the local store. - * - * If the node is online all requests for blocks first - * check locally and afterwards ask the network for the blocks. - * - * @param {Bitswap} bitswap - * @returns {void} - */ - setExchange (bitswap) { - this._bitswap = bitswap - } - - /** - * Go offline, i.e. drop the reference to bitswap. - * - * @returns {void} - */ - unsetExchange () { - this._bitswap = null - } - - /** - * Is the blockservice online, i.e. is bitswap present. - * - * @returns {bool} - */ - hasExchange () { - return this._bitswap != null - } - - /** - * Put a block to the underlying datastore. - * - * @param {Block} block - * @param {function(Error)} callback - * @returns {void} - */ - put (block, callback) { - if (this.hasExchange()) { - this._bitswap.put(block, callback) - } else { - this._repo.blocks.put(block, callback) - } - } - - /** - * Put a multiple blocks to the underlying datastore. - * - * @param {Array} blocks - * @param {function(Error)} callback - * @returns {void} - */ - putMany (blocks, callback) { - if (this.hasExchange()) { - this._bitswap.putMany(blocks, callback) - } else { - this._repo.blocks.putMany(blocks, callback) - } - } - - /** - * Get a block by cid. - * - * @param {CID} cid - * @param {function(Error, Block)} callback - * @returns {void} - */ - get (cid, callback) { - if (this.hasExchange()) { - this._bitswap.get(cid, callback) - } else { - this._repo.blocks.get(cid, callback) - } - } - - /** - * Get multiple blocks back from an array of cids. - * - * @param {Array} cids - * @param {function(Error, Block)} callback - * @returns {void} - */ - getMany (cids, callback) { - if (!Array.isArray(cids)) { - callback(new Error('first arg must be an array of cids')) - } else if (this.hasExchange()) { - this._bitswap.getMany(cids, callback) - } else { - asyncMap(cids, (cid, cb) => this._repo.blocks.get(cid, cb), callback) - } - } - - /** - * Delete a block from the blockstore. - * - * @param {CID} cid - * @param {function(Error)} callback - * @return {void} - */ - delete (cid, callback) { - this._repo.blocks.delete(cid, callback) - } -} - -module.exports = BlockService - -},{"async/map":137}],491:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') -const withIs = require('class-is') - -/** - * Represents an immutable block of data that is uniquely referenced with a cid. - * - * @constructor - * @param {Buffer} data - The data to be stored in the block as a buffer. - * @param {CID} cid - The cid of the data - * - * @example - * const block = new Block(new Buffer('a012d83b20f9371...')) - */ -class Block { - constructor (data, cid) { - if (!data || !Buffer.isBuffer(data)) { - throw new Error('first argument must be a buffer') - } - - if (!cid || !CID.isCID(cid)) { - throw new Error('second argument must be a CID') - } - - this._data = data - this._cid = cid - } - - /** - * The data of this block. - * - * @type {Buffer} - */ - get data () { - return this._data - } - - set data (val) { - throw new Error('Tried to change an immutable block') - } - - /** - * The cid of the data this block represents. - * - * @type {CID} - */ - get cid () { - return this._cid - } - - set cid (val) { - throw new Error('Tried to change an immutable block') - } -} - -module.exports = withIs(Block, { className: 'Block', symbolName: '@ipfs/js-ipfs-block/block' }) - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"cids":222,"class-is":224}],492:[function(require,module,exports){ -'use strict' - -module.exports = require('./src/core') - -},{"./src/core":499}],493:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":494,"_process":1438,"dup":247}],494:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":496}],495:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],496:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],497:[function(require,module,exports){ -'use strict' - -const mkdir = require('./mkdir') -const stat = require('./stat') -const log = require('debug')('ipfs:mfs:cp') -const errCode = require('err-code') -const updateTree = require('./utils/update-tree') -const updateMfsRoot = require('./utils/update-mfs-root') -const addLink = require('./utils/add-link') -const applyDefaultOptions = require('./utils/apply-default-options') -const toMfsPath = require('./utils/to-mfs-path') -const toSourcesAndDestination = require('./utils/to-sources-and-destination') -const toTrail = require('./utils/to-trail') - -const defaultOptions = { - parents: false, - flush: true, - format: 'dag-pb', - hashAlg: 'sha2-256', - cidVersion: 0, - shardSplitThreshold: 1000 -} - -module.exports = (context) => { - return async function mfsCp (...args) { - const options = applyDefaultOptions(args, defaultOptions) - let { - sources, destination - } = await toSourcesAndDestination(context, args) - - if (!sources.length) { - throw errCode(new Error('Please supply at least one source'), 'ERR_INVALID_PARAMS') - } - - if (!destination) { - throw errCode(new Error('Please supply a destination'), 'ERR_INVALID_PARAMS') - } - - options.parents = options.p || options.parents - - // make sure all sources exist - const missing = sources.find(source => !source.exists) - - if (missing) { - throw errCode(new Error(`${missing.path} does not exist`), 'ERR_INVALID_PARAMS') - } - - const destinationIsDirectory = isDirectory(destination) - - if (destination.exists) { - log('Destination exists') - - if (sources.length === 1 && !destinationIsDirectory) { - throw errCode(new Error('directory already has entry by that name'), 'ERR_ALREADY_EXISTS') - } - } else { - log('Destination does not exist') - - if (sources.length > 1) { - // copying multiple files to one location, destination will be a directory - if (!options.parents) { - throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS') - } - - await mkdir(context)(destination.path, options) - destination = await toMfsPath(context, destination.path) - } else if (destination.parts.length > 1) { - // copying to a folder, create it if necessary - const parentFolder = `/${destination.parts.slice(0, -1).join('/')}` - - try { - await stat(context)(parentFolder, options) - } catch (err) { - if (err.code !== 'ERR_NOT_FOUND') { - throw err - } - - if (!options.parents) { - throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS') - } - - await mkdir(context)(parentFolder, options) - destination = await toMfsPath(context, destination.path) - } - } - } - - const destinationPath = isDirectory(destination) ? destination.mfsPath : destination.mfsDirectory - const trail = await toTrail(context, destinationPath, options) - - if (sources.length === 1) { - const source = sources.pop() - const destinationName = destinationIsDirectory ? source.name : destination.name - - log(`Only one source, copying to destination ${destinationIsDirectory ? 'directory' : 'file'} ${destinationName}`) - - return copyToFile(context, source, destinationName, trail, options) - } - - log('Multiple sources, wrapping in a directory') - return copyToDirectory(context, sources, destination, trail, options) - } -} - -const isDirectory = (destination) => { - return destination.unixfs && - destination.unixfs.type && - destination.unixfs.type.includes('directory') -} - -const copyToFile = async (context, source, destination, destinationTrail, options) => { - let parent = destinationTrail.pop() - - parent = await addSourceToParent(context, source, destination, parent, options) - - // update the tree with the new containg directory - destinationTrail.push(parent) - - const newRootCid = await updateTree(context, destinationTrail, options) - - // Update the MFS record with the new CID for the root of the tree - await updateMfsRoot(context, newRootCid) -} - -const copyToDirectory = async (context, sources, destination, destinationTrail, options) => { - // copy all the sources to the destination - for (let i = 0; i < sources.length; i++) { - const source = sources[i] - - destination = await addSourceToParent(context, source, source.name, destination, options) - } - - // update the tree with the new containg directory - destinationTrail[destinationTrail.length - 1] = destination - - const newRootCid = await updateTree(context, destinationTrail, options) - - // Update the MFS record with the new CID for the root of the tree - await updateMfsRoot(context, newRootCid) -} - -const addSourceToParent = async (context, source, childName, parent, options) => { - const sourceBlock = await context.repo.blocks.get(source.cid) - - const { - node, - cid - } = await addLink(context, { - parentCid: parent.cid, - size: sourceBlock.data.length, - cid: source.cid, - name: childName, - format: options.format, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion - }) - - parent.node = node - parent.cid = cid - parent.size = node.size - - return parent -} - -},{"./mkdir":501,"./stat":505,"./utils/add-link":506,"./utils/apply-default-options":507,"./utils/to-mfs-path":514,"./utils/to-sources-and-destination":516,"./utils/to-trail":518,"./utils/update-mfs-root":519,"./utils/update-tree":520,"debug":493,"err-code":495}],498:[function(require,module,exports){ -'use strict' - -const applyDefaultOptions = require('./utils/apply-default-options') -const stat = require('./stat') -const { - FILE_SEPARATOR -} = require('./utils/constants') - -const defaultOptions = {} - -module.exports = (context) => { - return async function mfsFlush (path = FILE_SEPARATOR, options = defaultOptions) { - options = applyDefaultOptions(options, defaultOptions) - - await stat(context)(path, options) - } -} - -},{"./stat":505,"./utils/apply-default-options":507,"./utils/constants":508}],499:[function(require,module,exports){ -'use strict' - -const assert = require('assert') -const promisify = require('promisify-es6') -const createLock = require('./utils/create-lock') - -// These operations are read-locked at the function level and will execute simultaneously -const readOperations = { - stat: require('./stat') -} - -// These operations are locked at the function level and will execute in series -const writeOperations = { - cp: require('./cp'), - flush: require('./flush'), - mkdir: require('./mkdir'), - mv: require('./mv'), - rm: require('./rm') -} - -// These operations are asynchronous and manage their own locking -const unwrappedOperations = { - write: require('./write'), - read: require('./read'), - ls: require('./ls') -} - -const wrap = ({ - options, mfs, operations, lock -}) => { - Object.keys(operations).forEach(key => { - mfs[key] = lock(operations[key](options)) - }) -} - -const defaultOptions = { - repoOwner: true, - ipld: null, - repo: null -} - -module.exports = (options) => { - const { - repoOwner - } = Object.assign({}, defaultOptions || {}, options) - - assert(options.ipld, 'MFS requires an IPLD instance') - assert(options.blocks, 'MFS requires an BlockStore instance') - assert(options.datastore, 'MFS requires a DataStore instance') - - // should be able to remove this when async/await PRs are in for datastore, blockstore & repo - options.repo = { - blocks: { - get: promisify(options.blocks.get, { - context: options.blocks - }) - }, - datastore: { - open: promisify(options.datastore.open, { - context: options.datastore - }), - get: promisify(options.datastore.get, { - context: options.datastore - }), - put: promisify(options.datastore.put, { - context: options.datastore - }) - } - } - - const lock = createLock(repoOwner) - - const readLock = (operation) => { - return lock.readLock(operation) - } - - const writeLock = (operation) => { - return lock.writeLock(operation) - } - - const mfs = {} - - wrap({ - options, mfs, operations: readOperations, lock: readLock - }) - wrap({ - options, mfs, operations: writeOperations, lock: writeLock - }) - - Object.keys(unwrappedOperations).forEach(key => { - mfs[key] = unwrappedOperations[key](options) - }) - - return mfs -} - -},{"./cp":497,"./flush":498,"./ls":500,"./mkdir":501,"./mv":502,"./read":503,"./rm":504,"./stat":505,"./utils/create-lock":509,"./write":522,"assert":78,"promisify-es6":1443}],500:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const applyDefaultOptions = require('./utils/apply-default-options') -const toMfsPath = require('./utils/to-mfs-path') -const { - FILE_SEPARATOR, - FILE_TYPES -} = require('./utils/constants') - -const defaultOptions = { - -} - -const toOutput = (fsEntry) => { - let type = 0 - let size = fsEntry.node.size || fsEntry.node.length - - if (fsEntry.unixfs) { - size = fsEntry.unixfs.fileSize() - type = FILE_TYPES[fsEntry.unixfs.type] - } - - return { - cid: fsEntry.cid, - name: fsEntry.name, - type, - size - } -} - -module.exports = (context) => { - return async function * mfsLs (path = FILE_SEPARATOR, options = {}) { - if (typeof path === 'object' && !(path instanceof String)) { - options = path - path = FILE_SEPARATOR - } - - options = applyDefaultOptions(options, defaultOptions) - - const mfsPath = await toMfsPath(context, path) - const fsDir = await exporter(mfsPath.mfsPath, context.ipld) - - // single file/node - if (!fsDir.unixfs || !fsDir.unixfs.type.includes('directory')) { - yield toOutput(fsDir) - - return - } - - // directory, perhaps sharded - for await (const fsEntry of fsDir.content(options)) { - yield toOutput(fsEntry) - } - } -} - -},{"./utils/apply-default-options":507,"./utils/constants":508,"./utils/to-mfs-path":514,"ipfs-unixfs-exporter":540}],501:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const log = require('debug')('ipfs:mfs:mkdir') -const exporter = require('ipfs-unixfs-exporter') -const createNode = require('./utils/create-node') -const toPathComponents = require('./utils/to-path-components') -const updateMfsRoot = require('./utils/update-mfs-root') -const updateTree = require('./utils/update-tree') -const addLink = require('./utils/add-link') -const withMfsRoot = require('./utils/with-mfs-root') -const applyDefaultOptions = require('./utils/apply-default-options') -const { - FILE_SEPARATOR -} = require('./utils/constants') - -const defaultOptions = { - parents: false, - hashAlg: 'sha2-256', - cidVersion: 0, - shardSplitThreshold: 1000, - format: 'dag-pb', - flush: true -} - -module.exports = (context) => { - return async function mfsMkdir (path, options) { - options = applyDefaultOptions(options, defaultOptions) - - if (!path) { - throw new Error('no path given to Mkdir') - } - - path = path.trim() - - if (path === FILE_SEPARATOR) { - if (options.parents) { - return - } - - throw errCode(new Error(`cannot create directory '${FILE_SEPARATOR}': Already exists`), 'ERR_INVALID_PATH') - } - - if (path.substring(0, 1) !== FILE_SEPARATOR) { - throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH') - } - - log(`Creating ${path}`) - - const pathComponents = toPathComponents(path) - - if (pathComponents[0] === 'ipfs') { - throw errCode(new Error("path cannot have the prefix 'ipfs'"), 'ERR_INVALID_PATH') - } - - let root = await withMfsRoot(context) - let parent - let trail = [] - const emptyDir = await createNode(context, 'directory', options) - - // make sure the containing folder exists, creating it if necessary - for (let i = 0; i <= pathComponents.length; i++) { - const subPathComponents = pathComponents.slice(0, i) - const subPath = `/ipfs/${root}/${subPathComponents.join('/')}` - - try { - parent = await exporter(subPath, context.ipld) - log(`${subPath} existed`) - log(`${subPath} had children ${parent.node.Links.map(link => link.Name)}`) - - if (i === pathComponents.length) { - if (options.parents) { - return - } - - throw errCode(new Error('file already exists'), 'ERR_ALREADY_EXISTS') - } - - trail.push({ - name: parent.name, - cid: parent.cid - }) - } catch (err) { - if (err.code === 'ERR_NOT_FOUND') { - if (i < pathComponents.length && !options.parents) { - throw errCode(new Error(`Intermediate directory path ${subPath} does not exist, use the -p flag to create it`), 'ERR_NOT_FOUND') - } - - // add the intermediate directory - await addEmptyDir(context, subPathComponents[subPathComponents.length - 1], emptyDir, trail[trail.length - 1], trail, options) - } else { - throw err - } - } - } - - // add an empty dir to the last path component - // await addEmptyDir(context, pathComponents[pathComponents.length - 1], emptyDir, parent, trail) - - // update the tree from the leaf to the root - const newRootCid = await updateTree(context, trail, options) - - // Update the MFS record with the new CID for the root of the tree - await updateMfsRoot(context, newRootCid) - } -} - -const addEmptyDir = async (context, childName, emptyDir, parent, trail, options) => { - log(`Adding empty dir called ${childName} to ${parent.cid}`) - - const result = await addLink(context, { - parent: parent.node, - parentCid: parent.cid, - size: emptyDir.node.size, - cid: emptyDir.cid, - name: childName, - format: options.format, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion - }) - - trail[trail.length - 1].cid = result.cid - - trail.push({ - name: childName, - cid: emptyDir.cid - }) -} - -},{"./utils/add-link":506,"./utils/apply-default-options":507,"./utils/constants":508,"./utils/create-node":510,"./utils/to-path-components":515,"./utils/update-mfs-root":519,"./utils/update-tree":520,"./utils/with-mfs-root":521,"debug":493,"err-code":495,"ipfs-unixfs-exporter":540}],502:[function(require,module,exports){ -'use strict' - -const applyDefaultOptions = require('./utils/apply-default-options') -const toSources = require('./utils/to-sources') -const cp = require('./cp') -const rm = require('./rm') - -const defaultOptions = { - parents: false, - recursive: false, - flush: true, - format: 'dag-pb', - hashAlg: 'sha2-256', - shardSplitThreshold: 1000 -} - -module.exports = (context) => { - return async function mfsMv (...args) { - if (Array.isArray(args[0])) { - args = args[0].concat(args.slice(1)) - } - - const { - sources - } = await toSources(context, args) - const options = applyDefaultOptions(args, defaultOptions) - - const cpArgs = sources - .map(source => source.path).concat(options) - - // remove the last source as it'll be the destination - const rmArgs = sources - .slice(0, -1) - .map(source => source.path) - .concat(Object.assign(options, { - recursive: true - })) - - await cp(context).apply(null, cpArgs) - await rm(context).apply(null, rmArgs) - } -} - -},{"./cp":497,"./rm":504,"./utils/apply-default-options":507,"./utils/to-sources":517}],503:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const applyDefaultOptions = require('./utils/apply-default-options') -const toMfsPath = require('./utils/to-mfs-path') -const errCode = require('err-code') - -const defaultOptions = { - offset: 0, - length: Infinity -} - -module.exports = (context) => { - return function mfsRead (path, options = {}) { - options = applyDefaultOptions(options, defaultOptions) - - return { - [Symbol.asyncIterator]: async function * read () { - const mfsPath = await toMfsPath(context, path) - const result = await exporter(mfsPath.mfsPath, context.ipld) - - if (result.unixfs.type !== 'file') { - throw errCode(new Error(`${path} was not a file`), 'ERR_NOT_FILE') - } - - if (!result.content) { - throw errCode(new Error(`Could not load content stream from ${path}`), 'ERR_NO_CONTENT') - } - - for await (const buf of result.content({ - offset: options.offset, - length: options.length - })) { - yield buf - } - } - } - } -} - -},{"./utils/apply-default-options":507,"./utils/to-mfs-path":514,"err-code":495,"ipfs-unixfs-exporter":540}],504:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const updateTree = require('./utils/update-tree') -const updateMfsRoot = require('./utils/update-mfs-root') -const toSources = require('./utils/to-sources') -const removeLink = require('./utils/remove-link') -const toMfsPath = require('./utils/to-mfs-path') -const toTrail = require('./utils/to-trail') -const applyDefaultOptions = require('./utils/apply-default-options') -const { - FILE_SEPARATOR -} = require('./utils/constants') - -const defaultOptions = { - recursive: false, - cidVersion: 0, - hashAlg: 'sha2-256', - format: 'dag-pb', - flush: true -} - -module.exports = (context) => { - return async function mfsRm () { - const args = Array.from(arguments) - - const { - sources - } = await toSources(context, args, defaultOptions) - const options = applyDefaultOptions(args, defaultOptions) - - if (!sources.length) { - throw errCode(new Error('Please supply at least one path to remove'), 'ERR_INVALID_PARAMS') - } - - sources.forEach(source => { - if (source.path === FILE_SEPARATOR) { - throw errCode(new Error('Cannot delete root'), 'ERR_INVALID_PARAMS') - } - }) - - for (const source of sources) { - await removePath(context, source.path, options) - } - } -} - -const removePath = async (context, path, options) => { - const mfsPath = await toMfsPath(context, path) - const trail = await toTrail(context, mfsPath.mfsPath, options) - const child = trail.pop() - const parent = trail[trail.length - 1] - - if (!parent) { - throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND') - } - - if (child.type === 'directory' && !options.recursive) { - throw errCode(new Error(`${path} is a directory, use -r to remove directories`), 'ERR_WAS_DIR') - } - - const { - cid - } = await removeLink(context, { - parentCid: parent.cid, - name: child.name, - format: options.format, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion, - flush: options.flush - }) - - parent.cid = cid - - // update the tree with the new child - const newRootCid = await updateTree(context, trail, options) - - // Update the MFS record with the new CID for the root of the tree - await updateMfsRoot(context, newRootCid) -} - -},{"./utils/apply-default-options":507,"./utils/constants":508,"./utils/remove-link":512,"./utils/to-mfs-path":514,"./utils/to-sources":517,"./utils/to-trail":518,"./utils/update-mfs-root":519,"./utils/update-tree":520,"err-code":495}],505:[function(require,module,exports){ -'use strict' - -const applyDefaultOptions = require('./utils/apply-default-options') -const toMfsPath = require('./utils/to-mfs-path') -const exporter = require('ipfs-unixfs-exporter') -const log = require('debug')('ipfs:mfs:stat') -const errCode = require('err-code') - -const defaultOptions = { - withLocal: false -} - -module.exports = (context) => { - return async function mfsStat (path, options) { - options = applyDefaultOptions(options, defaultOptions) - - log(`Fetching stats for ${path}`) - - const { - type, - cid, - mfsPath - } = await toMfsPath(context, path) - - let exportPath = type === 'ipfs' && cid ? cid : mfsPath - let file - - try { - file = await exporter(exportPath, context.ipld) - } catch (err) { - if (err.code === 'ERR_NOT_FOUND') { - throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND') - } - - throw err - } - - if (!statters[file.cid.codec]) { - throw new Error(`Cannot stat codec ${file.cid.codec}`) - } - - return statters[file.cid.codec](file, options) - } -} - -const statters = { - raw: (file) => { - return { - cid: file.cid, - size: file.node.length, - cumulativeSize: file.node.length, - blocks: 0, - type: 'file', // for go compatibility - local: undefined, - sizeLocal: undefined, - withLocality: false - } - }, - 'dag-pb': (file) => { - let blocks = file.node.Links.length - let size = file.node.size - let cumulativeSize = file.node.size - let nodeType = null - - if (file.unixfs) { - size = file.unixfs.fileSize() - nodeType = file.unixfs.type - - if (nodeType.includes('directory')) { - size = 0 - cumulativeSize = file.node.size - } - - if (nodeType === 'file') { - blocks = file.unixfs.blockSizes.length - } - } - - return { - cid: file.cid, - size: size, - cumulativeSize: cumulativeSize, - blocks: blocks, - type: nodeType, - local: undefined, - sizeLocal: undefined, - withLocality: false - } - }, - 'dag-cbor': (file) => { - return { - cid: file.cid, - local: undefined, - sizeLocal: undefined, - withLocality: false - } - } -} - -},{"./utils/apply-default-options":507,"./utils/to-mfs-path":514,"debug":493,"err-code":495,"ipfs-unixfs-exporter":540}],506:[function(require,module,exports){ -'use strict' - -const { - DAGNode, - DAGLink -} = require('ipld-dag-pb') -const CID = require('cids') -const log = require('debug')('ipfs:mfs:core:utils:add-link') -const UnixFS = require('ipfs-unixfs') -const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') -const { - updateHamtDirectory, - recreateHamtLevel, - createShard, - toPrefix, - addLinksToHamtBucket -} = require('./hamt-utils') -const errCode = require('err-code') -const mc = require('multicodec') -const mh = require('multihashes') -const last = require('async-iterator-last') - -const addLink = async (context, options) => { - if (!options.parentCid && !options.parent) { - throw errCode(new Error('No parent node or CID passed to addLink'), 'EINVALIDPARENT') - } - - if (options.parentCid && !CID.isCID(options.parentCid)) { - throw errCode(new Error('Invalid CID passed to addLink'), 'EINVALIDPARENTCID') - } - - if (!options.parent) { - log(`Loading parent node ${options.parentCid}`) - - options.parent = await context.ipld.get(options.parentCid) - } - - if (!options.cid) { - throw errCode(new Error('No child cid passed to addLink'), 'EINVALIDCHILDCID') - } - - if (!options.name) { - throw errCode(new Error('No child name passed to addLink'), 'EINVALIDCHILDNAME') - } - - if (!CID.isCID(options.cid)) { - options.cid = new CID(options.cid) - } - - if (!options.size && options.size !== 0) { - throw errCode(new Error('No child size passed to addLink'), 'EINVALIDCHILDSIZE') - } - - const meta = UnixFS.unmarshal(options.parent.Data) - - if (meta.type === 'hamt-sharded-directory') { - log('Adding link to sharded directory') - - return addToShardedDirectory(context, options) - } - - if (options.parent.Links.length >= options.shardSplitThreshold) { - log('Converting directory to sharded directory') - - return convertToShardedDirectory(context, options) - } - - log(`Adding ${options.name} (${options.cid}) to regular directory`) - - return addToDirectory(context, options) -} - -const convertToShardedDirectory = async (context, options) => { - const result = await createShard(context, options.parent.Links.map(link => ({ - name: link.Name, - size: link.Tsize, - cid: link.Hash - })).concat({ - name: options.name, - size: options.size, - cid: options.cid - }), options) - - log(`Converted directory to sharded directory ${result.cid}`) - - return result -} - -const addToDirectory = async (context, options) => { - let parent = await DAGNode.rmLink(options.parent, options.name) - parent = await DAGNode.addLink(parent, new DAGLink(options.name, options.size, options.cid)) - - const format = mc[options.format.toUpperCase().replace(/-/g, '_')] - const hashAlg = mh.names[options.hashAlg] - - // Persist the new parent DAGNode - const cid = await context.ipld.put(parent, format, { - cidVersion: options.cidVersion, - hashAlg, - hashOnly: !options.flush - }) - - return { - node: parent, - cid - } -} - -const addToShardedDirectory = async (context, options) => { - const { - shard, path - } = await addFileToShardedDirectory(context, options) - - const result = await last(shard.flush('', context.ipld)) - - // we have written out the shard, but only one sub-shard will have been written so replace it in the original shard - const oldLink = options.parent.Links - .find(link => link.Name.substring(0, 2) === path[0].prefix) - - const newLink = result.node.Links - .find(link => link.Name.substring(0, 2) === path[0].prefix) - - let parent = options.parent - - if (oldLink) { - parent = await DAGNode.rmLink(options.parent, oldLink.Name) - } - - parent = await DAGNode.addLink(parent, newLink) - - return updateHamtDirectory(context, parent.Links, path[0].bucket, options) -} - -const addFileToShardedDirectory = async (context, options) => { - const file = { - name: options.name, - cid: options.cid, - size: options.size - } - - // start at the root bucket and descend, loading nodes as we go - const rootBucket = await recreateHamtLevel(options.parent.Links) - - const shard = new DirSharded({ - root: true, - dir: true, - parent: null, - parentKey: null, - path: '', - dirty: true, - flat: false - }, options) - shard._bucket = rootBucket - - // load subshards until the bucket & position no longer changes - const position = await rootBucket._findNewBucketAndPos(file.name) - const path = toBucketPath(position) - path[0].node = options.parent - let index = 0 - - while (index < path.length) { - let segment = path[index] - index++ - let node = segment.node - - let link = node.Links - .find(link => link.Name.substring(0, 2) === segment.prefix) - - if (!link) { - // prefix is new, file will be added to the current bucket - log(`Link ${segment.prefix}${file.name} will be added`) - index = path.length - - break - } - - if (link.Name === `${segment.prefix}${file.name}`) { - // file already existed, file will be added to the current bucket - log(`Link ${segment.prefix}${file.name} will be replaced`) - index = path.length - - break - } - - if (link.Name.length > 2) { - // another file had the same prefix, will be replaced with a subshard - log(`Link ${link.Name} will be replaced with a subshard`) - index = path.length - - break - } - - // load sub-shard - log(`Found subshard ${segment.prefix}`) - const subShard = await context.ipld.get(link.Hash) - - // subshard hasn't been loaded, descend to the next level of the HAMT - if (!path[index]) { - log(`Loaded new subshard ${segment.prefix}`) - await recreateHamtLevel(subShard.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16)) - - const position = await rootBucket._findNewBucketAndPos(file.name) - - path.push({ - bucket: position.bucket, - prefix: toPrefix(position.pos), - node: subShard - }) - - break - } - - const nextSegment = path[index] - - // add next level's worth of links to bucket - await addLinksToHamtBucket(subShard.Links, nextSegment.bucket, rootBucket) - - nextSegment.node = subShard - } - - // finally add the new file into the shard - await shard._bucket.put(file.name, { - size: file.size, - cid: file.cid - }) - - return { - shard, path - } -} - -const toBucketPath = (position) => { - let bucket = position.bucket - let positionInBucket = position.pos - let path = [{ - bucket, - prefix: toPrefix(positionInBucket) - }] - - bucket = position.bucket._parent - positionInBucket = position.bucket._posAtParent - - while (bucket) { - path.push({ - bucket, - prefix: toPrefix(positionInBucket) - }) - - positionInBucket = bucket._posAtParent - bucket = bucket._parent - } - - path.reverse() - - return path -} - -module.exports = addLink - -},{"./hamt-utils":511,"async-iterator-last":85,"cids":222,"debug":493,"err-code":495,"ipfs-unixfs":592,"ipfs-unixfs-importer/src/dir-sharded":585,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331}],507:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') - -module.exports = (options = {}, defaults) => { - if (Array.isArray(options)) { - options = options.filter(arg => typeof arg === 'object').pop() || {} - } - - const output = {} - - for (let key in defaults) { - if (options[key] !== null && options[key] !== undefined) { - output[key] = options[key] - } else { - output[key] = defaults[key] - } - } - - const format = output.format || output.codec - - if (format && isNaN(format)) { - output.format = format - delete output.codec - } - - // support legacy go arguments - if (options.count !== undefined) { - output.length = options.count - } - - if (options.p !== undefined) { - output.parents = options.p - } - - if (options.l !== undefined) { - output.long = options.l - } - - if (!output.length && output.length !== 0) { - output.length = Infinity - } - - if (output.offset < 0) { - throw errCode(new Error('cannot have negative write offset'), 'ERR_INVALID_PARAMS') - } - - if (output.length < 0) { - throw errCode(new Error('cannot have negative byte count'), 'ERR_INVALID_PARAMS') - } - - return output -} - -},{"err-code":495}],508:[function(require,module,exports){ -'use strict' - -const Key = require('interface-datastore').Key - -const FILE_TYPES = { - file: 0, - directory: 1, - 'hamt-sharded-directory': 1 -} - -module.exports = { - FILE_SEPARATOR: '/', - MFS_ROOT_KEY: new Key('/local/filesroot'), - MAX_CHUNK_SIZE: 262144, - MAX_LINKS: 174, - FILE_TYPES -} - -},{"interface-datastore":458}],509:[function(require,module,exports){ -'use strict' - -const mortice = require('mortice') - -let lock - -module.exports = (repoOwner) => { - if (lock) { - return lock - } - - const mutex = mortice({ - // ordinarily the main thread would store the read/write lock but - // if we are the thread that owns the repo, we can store the lock - // on this process even if we are a worker thread - singleProcess: repoOwner - }) - - lock = { - readLock: (func) => { - return async (...args) => { - const releaseLock = await mutex.readLock() - - try { - return await func.apply(null, args) - } finally { - releaseLock() - } - } - }, - - writeLock: (func) => { - return async (...args) => { - const releaseLock = await mutex.writeLock() - - try { - return await func.apply(null, args) - } finally { - releaseLock() - } - } - } - } - - return lock -} - -},{"mortice":1307}],510:[function(require,module,exports){ -'use strict' - -const UnixFS = require('ipfs-unixfs') -const { - DAGNode -} = require('ipld-dag-pb') -const mc = require('multicodec') -const mh = require('multihashes') - -const createNode = async (context, type, options) => { - const format = mc[options.format.toUpperCase().replace(/-/g, '_')] - const hashAlg = mh.names[options.hashAlg] - - const node = DAGNode.create(new UnixFS(type).marshal()) - const cid = await context.ipld.put(node, format, { - cidVersion: options.cidVersion, - hashAlg - }) - - return { - cid, - node - } -} - -module.exports = createNode - -},{"ipfs-unixfs":592,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331}],511:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const { - DAGNode -} = require('ipld-dag-pb') -const Bucket = require('hamt-sharding/src/bucket') -const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') -const log = require('debug')('ipfs:mfs:core:utils:hamt-utils') -const UnixFS = require('ipfs-unixfs') -const mc = require('multicodec') -const mh = require('multihashes') -const last = require('async-iterator-last') - -const updateHamtDirectory = async (context, links, bucket, options) => { - // update parent with new bit field - const data = Buffer.from(bucket._children.bitField().reverse()) - const dir = new UnixFS('hamt-sharded-directory', data) - dir.fanout = bucket.tableSize() - dir.hashType = DirSharded.hashFn.code - - const format = mc[options.format.toUpperCase().replace(/-/g, '_')] - const hashAlg = mh.names[options.hashAlg] - - const parent = DAGNode.create(dir.marshal(), links) - const cid = await context.ipld.put(parent, format, { - cidVersion: options.cidVersion, - hashAlg, - hashOnly: !options.flush - }) - - return { - node: parent, - cid - } -} - -const recreateHamtLevel = async (links, rootBucket, parentBucket, positionAtParent) => { - // recreate this level of the HAMT - const bucket = new Bucket({ - hashFn: DirSharded.hashFn, - hash: parentBucket ? parentBucket._options.hash : undefined - }, parentBucket, positionAtParent) - - if (parentBucket) { - parentBucket._putObjectAt(positionAtParent, bucket) - } - - await addLinksToHamtBucket(links, bucket, rootBucket) - - return bucket -} - -const addLinksToHamtBucket = async (links, bucket, rootBucket) => { - await Promise.all( - links.map(link => { - if (link.Name.length === 2) { - const pos = parseInt(link.Name, 16) - - bucket._putObjectAt(pos, new Bucket({ - hashFn: DirSharded.hashFn - }, bucket, pos)) - - return Promise.resolve() - } - - return (rootBucket || bucket).put(link.Name.substring(2), { - size: link.TSize, - cid: link.Hash - }) - }) - ) -} - -const toPrefix = (position) => { - return position - .toString('16') - .toUpperCase() - .padStart(2, '0') - .substring(0, 2) -} - -const generatePath = async (context, fileName, rootNode) => { - // start at the root bucket and descend, loading nodes as we go - const rootBucket = await recreateHamtLevel(rootNode.Links, null, null, null) - const position = await rootBucket._findNewBucketAndPos(fileName) - - // the path to the root bucket - let path = [{ - bucket: position.bucket, - prefix: toPrefix(position.pos) - }] - let currentBucket = position.bucket - - while (currentBucket !== rootBucket) { - path.push({ - bucket: currentBucket, - prefix: toPrefix(currentBucket._posAtParent) - }) - - currentBucket = currentBucket._parent - } - - path.reverse() - path[0].node = rootNode - - // load DAGNode for each path segment - for (let i = 0; i < path.length; i++) { - const segment = path[i] - - // find prefix in links - const link = segment.node.Links - .filter(link => link.Name.substring(0, 2) === segment.prefix) - .pop() - - // entry was not in shard - if (!link) { - // reached bottom of tree, file will be added to the current bucket - log(`Link ${segment.prefix}${fileName} will be added`) - // return path - continue - } - - // found entry - if (link.Name === `${segment.prefix}${fileName}`) { - log(`Link ${segment.prefix}${fileName} will be replaced`) - // file already existed, file will be added to the current bucket - // return path - continue - } - - // found subshard - log(`Found subshard ${segment.prefix}`) - const node = await context.ipld.get(link.Hash) - - // subshard hasn't been loaded, descend to the next level of the HAMT - if (!path[i + 1]) { - log(`Loaded new subshard ${segment.prefix}`) - - await recreateHamtLevel(node.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16)) - const position = await rootBucket._findNewBucketAndPos(fileName) - - // i-- - path.push({ - bucket: position.bucket, - prefix: toPrefix(position.pos), - node: node - }) - - continue - } - - const nextSegment = path[i + 1] - - // add intermediate links to bucket - await addLinksToHamtBucket(node.Links, nextSegment.bucket, rootBucket) - - nextSegment.node = node - } - - await rootBucket.put(fileName, true) - - path.reverse() - - return { - rootBucket, - path - } -} - -const createShard = async (context, contents, options) => { - const shard = new DirSharded({ - root: true, - dir: true, - parent: null, - parentKey: null, - path: '', - dirty: true, - flat: false - }, options) - - for (let i = 0; i < contents.length; i++) { - await shard._bucket.put(contents[i].name, { - size: contents[i].size, - cid: contents[i].cid - }) - } - - return last(shard.flush('', context.ipld, null)) -} - -module.exports = { - generatePath, - updateHamtDirectory, - recreateHamtLevel, - addLinksToHamtBucket, - toPrefix, - createShard -} - -}).call(this,require("buffer").Buffer) -},{"async-iterator-last":85,"buffer":217,"debug":493,"hamt-sharding/src/bucket":394,"ipfs-unixfs":592,"ipfs-unixfs-importer/src/dir-sharded":585,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331}],512:[function(require,module,exports){ -'use strict' - -const { - DAGNode, - DAGLink -} = require('ipld-dag-pb') -const CID = require('cids') -const log = require('debug')('ipfs:mfs:core:utils:remove-link') -const UnixFS = require('ipfs-unixfs') -const { - generatePath, - updateHamtDirectory -} = require('./hamt-utils') -const errCode = require('err-code') -const mc = require('multicodec') -const mh = require('multihashes') - -const removeLink = async (context, options) => { - if (!options.parentCid && !options.parent) { - throw errCode(new Error('No parent node or CID passed to removeLink'), 'EINVALIDPARENT') - } - - if (options.parentCid && !CID.isCID(options.parentCid)) { - throw errCode(new Error('Invalid CID passed to removeLink'), 'EINVALIDPARENTCID') - } - - if (!options.parent) { - log(`Loading parent node ${options.parentCid}`) - - options.parent = await context.ipld.get(options.parentCid) - } - - if (!options.name) { - throw errCode(new Error('No child name passed to removeLink'), 'EINVALIDCHILDNAME') - } - - const meta = UnixFS.unmarshal(options.parent.Data) - - if (meta.type === 'hamt-sharded-directory') { - log(`Removing ${options.name} from sharded directory`) - - return removeFromShardedDirectory(context, options) - } - - log(`Removing link ${options.name} regular directory`) - - return removeFromDirectory(context, options) -} - -const removeFromDirectory = async (context, options) => { - const format = mc[options.format.toUpperCase().replace(/-/g, '_')] - const hashAlg = mh.names[options.hashAlg] - - const newParentNode = await DAGNode.rmLink(options.parent, options.name) - const cid = await context.ipld.put(newParentNode, format, { - cidVersion: options.cidVersion, - hashAlg - }) - - log(`Updated regular directory ${cid}`) - - return { - node: newParentNode, - cid - } -} - -const removeFromShardedDirectory = async (context, options) => { - const { - rootBucket, path - } = await generatePath(context, options.name, options.parent) - - await rootBucket.del(options.name) - - const { - node - } = await updateShard(context, path, { - name: options.name, - cid: options.cid, - size: options.size, - hashAlg: options.hashAlg, - format: options.format, - cidVersion: options.cidVersion, - flush: options.flush - }, options) - - return updateHamtDirectory(context, node.Links, rootBucket, options) -} - -const updateShard = async (context, positions, child, options) => { - const { - bucket, - prefix, - node - } = positions.pop() - - const link = node.Links - .find(link => link.Name.substring(0, 2) === prefix) - - if (!link) { - throw errCode(new Error(`No link found with prefix ${prefix} for file ${child.name}`), 'ERR_NOT_FOUND') - } - - if (link.Name === `${prefix}${child.name}`) { - log(`Removing existing link ${link.Name}`) - - const newNode = await DAGNode.rmLink(node, link.Name) - - await bucket.del(child.name) - - return updateHamtDirectory(context, newNode.Links, bucket, options) - } - - log(`Descending into sub-shard ${link.Name} for ${prefix}${child.name}`) - - const result = await updateShard(context, positions, child, options) - - let newName = prefix - - if (result.node.Links.length === 1) { - log(`Removing subshard for ${prefix}`) - - // convert shard back to normal dir - result.cid = result.node.Links[0].Hash - result.node = result.node.Links[0] - - newName = `${prefix}${result.node.Name.substring(2)}` - } - - log(`Updating shard ${prefix} with name ${newName}`) - - const size = DAGNode.isDAGNode(result.node) ? result.node.size : result.node.Tsize - - return updateShardParent(context, bucket, node, prefix, newName, size, result.cid, options) -} - -const updateShardParent = async (context, bucket, parent, oldName, newName, size, cid, options) => { - parent = await DAGNode.rmLink(parent, oldName) - parent = await DAGNode.addLink(parent, new DAGLink(newName, size, cid)) - - return updateHamtDirectory(context, parent.Links, bucket, options) -} - -module.exports = removeLink - -},{"./hamt-utils":511,"cids":222,"debug":493,"err-code":495,"ipfs-unixfs":592,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331}],513:[function(require,module,exports){ -(function (global,Buffer){ -'use strict' - -const errCode = require('err-code') -const fs = require('fs') -const log = require('debug')('ipfs:mfs:utils:to-async-iterator') -const { - MAX_CHUNK_SIZE -} = require('./constants') - -const toAsyncIterator = async (content) => { - if (!content) { - throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH') - } - - if (typeof content === 'string' || content instanceof String) { - // Paths, node only - log('Content was a path') - - return fs.createReadStream(content) - } - - if (content.length) { - log('Content was array-like') - - return { - [Symbol.asyncIterator]: async function * bufferContent () { - yield content - } - } - } - - if (content[Symbol.asyncIterator]) { - log('Content was an async iterator') - return content - } - - if (content[Symbol.iterator]) { - log('Content was an iterator') - return content - } - - if (global.Blob && content instanceof global.Blob) { - // HTML5 Blob objects (including Files) - log('Content was an HTML5 Blob') - - let index = 0 - - const iterator = { - next: async () => { - if (index > content.size) { - return { - done: true - } - } - - return new Promise((resolve, reject) => { - const chunk = content.slice(index, MAX_CHUNK_SIZE) - index += MAX_CHUNK_SIZE - - const reader = new global.FileReader() - - const handleLoad = (ev) => { - reader.removeEventListener('loadend', handleLoad, false) - - if (ev.error) { - return reject(ev.error) - } - - resolve({ - done: false, - value: Buffer.from(reader.result) - }) - } - - reader.addEventListener('loadend', handleLoad) - reader.readAsArrayBuffer(chunk) - }) - } - } - - return { - [Symbol.asyncIterator]: () => { - return iterator - } - } - } - - throw errCode(new Error(`Don't know how to convert ${content} into an async iterator`), 'ERR_INVALID_PARAMS') -} - -module.exports = toAsyncIterator - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./constants":508,"buffer":217,"debug":493,"err-code":495,"fs":182}],514:[function(require,module,exports){ -'use strict' - -const { - FILE_SEPARATOR -} = require('./constants') -const loadMfsRoot = require('./with-mfs-root') -const toPathComponents = require('./to-path-components') -const exporter = require('ipfs-unixfs-exporter') -const errCode = require('err-code') - -const IPFS_PREFIX = 'ipfs' - -const toMfsPath = async (context, path) => { - let outputArray = Array.isArray(path) - let paths = Array.isArray(path) ? path : [path] - const root = await loadMfsRoot(context) - - paths = paths.map(path => { - path = (path || '').trim() - path = path.replace(/(\/\/+)/g, '/') - - if (path.endsWith('/') && path.length > 1) { - path = path.substring(0, path.length - 1) - } - - if (!path) { - throw errCode(new Error('paths must not be empty'), 'ERR_NO_PATH') - } - - if (path.substring(0, 1) !== FILE_SEPARATOR) { - throw errCode(new Error(`paths must start with a leading ${FILE_SEPARATOR}`), 'ERR_INVALID_PATH') - } - - if (path.substring(path.length - FILE_SEPARATOR.length) === FILE_SEPARATOR) { - path = path.substring(0, path.length - FILE_SEPARATOR.length) - } - - const pathComponents = toPathComponents(path) - - if (pathComponents[0] === IPFS_PREFIX) { - // e.g. /ipfs/QMfoo or /ipfs/Qmfoo/sub/path - let mfsDirectory - - if (pathComponents.length === 2) { - mfsDirectory = `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}` - } else { - mfsDirectory = `${FILE_SEPARATOR}${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}` - } - - return { - type: 'ipfs', - depth: pathComponents.length - 2, - - mfsPath: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, - mfsDirectory, - parts: pathComponents, - path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, - name: pathComponents[pathComponents.length - 1] - } - } - - const mfsPath = `/${IPFS_PREFIX}/${root}${pathComponents.length ? '/' + pathComponents.join(FILE_SEPARATOR) : ''}` - const mfsDirectory = `/${IPFS_PREFIX}/${root}/${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}` - - return { - type: 'mfs', - depth: pathComponents.length, - - mfsDirectory, - mfsPath, - parts: pathComponents, - path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`, - name: pathComponents[pathComponents.length - 1] - } - }) - - await Promise.all( - paths.map(async (path) => { - const cidPath = path.type === 'mfs' ? path.mfsPath : path.path - - try { - const res = await exporter(cidPath, context.ipld) - - path.cid = res.cid - path.mfsPath = `/ipfs/${res.path}` - path.unixfs = res.unixfs - path.content = res.content - } catch (err) { - if (err.code !== 'ERR_NOT_FOUND') { - throw err - } - } - - path.exists = Boolean(path.cid) - }) - ) - - if (outputArray) { - return paths - } - - return paths[0] -} - -module.exports = toMfsPath - -},{"./constants":508,"./to-path-components":515,"./with-mfs-root":521,"err-code":495,"ipfs-unixfs-exporter":540}],515:[function(require,module,exports){ -'use strict' - -const toPathComponents = (path = '') => { - // split on / unless escaped with \ - return (path - .trim() - .match(/([^\\^/]|\\\/)+/g) || []) - .filter(Boolean) -} - -module.exports = toPathComponents - -},{}],516:[function(require,module,exports){ -'use strict' - -const toSources = require('./to-sources') - -async function toSourcesAndDestination (context, args) { - const { - sources, - options - } = await toSources(context, args) - - const destination = sources.pop() - - return { - destination, - sources, - options - } -} - -module.exports = toSourcesAndDestination - -},{"./to-sources":517}],517:[function(require,module,exports){ -'use strict' - -const toMfsPath = require('./to-mfs-path') - -async function toSources (context, args) { - // Support weird mfs.mv([source, dest], options, callback) signature - if (Array.isArray(args[0])) { - args = args[0] - } - - const sources = args - .filter(arg => typeof arg === 'string') - .map(source => source.trim()) - - return { - sources: await toMfsPath(context, sources) - } -} - -module.exports = toSources - -},{"./to-mfs-path":514}],518:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const log = require('debug')('ipfs:mfs:utils:to-trail') - -const toTrail = async (context, path) => { - log(`Creating trail for path ${path}`) - - const output = [] - - for await (const fsEntry of exporter.path(path, context.ipld)) { - output.push({ - name: fsEntry.name, - cid: fsEntry.cid, - size: fsEntry.node.size, - type: fsEntry.unixfs ? fsEntry.unixfs.type : undefined - }) - } - - return output -} - -module.exports = toTrail - -},{"debug":493,"ipfs-unixfs-exporter":540}],519:[function(require,module,exports){ -'use strict' - -const log = require('debug')('ipfs:mfs:utils:update-mfs-root') -const { - MFS_ROOT_KEY -} = require('./constants') - -const updateMfsRoot = async (context, cid) => { - log(`New MFS root will be ${cid}`) - - await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer) - - return cid -} - -module.exports = updateMfsRoot - -},{"./constants":508,"debug":493}],520:[function(require,module,exports){ -'use strict' - -const log = require('debug')('ipfs:mfs:utils:update-tree') -const addLink = require('./add-link') - -const defaultOptions = { - shardSplitThreshold: 1000 -} - -// loop backwards through the trail, replacing links of all components to update CIDs -const updateTree = async (context, trail, options) => { - options = Object.assign({}, defaultOptions, options) - - log('Trail', trail) - trail = trail.slice().reverse() - - let index = 0 - let child - - for await (const node of context.ipld.getMany(trail.map(node => node.cid))) { - const cid = trail[index].cid - const name = trail[index].name - index++ - - if (!child) { - child = { - cid, - name, - size: node.size - } - - continue - } - - const result = await addLink(context, { - parent: node, - name: child.name, - cid: child.cid, - size: child.size, - flush: options.flush, - shardSplitThreshold: options.shardSplitThreshold, - format: options.format, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion - }) - - // new child for next loop - child = { - cid: result.cid, - name, - size: result.node.size - } - } - - log(`Final CID ${child.cid}`) - - return child.cid -} - -module.exports = updateTree - -},{"./add-link":506,"debug":493}],521:[function(require,module,exports){ -'use strict' - -const CID = require('cids') -const UnixFs = require('ipfs-unixfs') -const { - DAGNode -} = require('ipld-dag-pb') -const log = require('debug')('ipfs:mfs:utils:with-mfs-root') -const mc = require('multicodec') -const mh = require('multihashes') - -const { - MFS_ROOT_KEY -} = require('./constants') - -const loadMfsRoot = async (context) => { - // Open the repo if it's been closed - await context.repo.datastore.open() - - // Load the MFS root CID - let cid - - try { - const buf = await context.repo.datastore.get(MFS_ROOT_KEY) - - cid = new CID(buf) - } catch (err) { - if (err.code !== 'ERR_NOT_FOUND') { - throw err - } - - log('Creating new MFS root') - const node = DAGNode.create(new UnixFs('directory').marshal()) - cid = await context.ipld.put(node, mc.DAG_PB, { - cidVersion: 0, - hashAlg: mh.names['sha2-256'] // why can't ipld look this up? - }) - - await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer) - } - - log(`Loaded MFS root /ipfs/${cid}`) - - return cid -} - -module.exports = loadMfsRoot - -},{"./constants":508,"cids":222,"debug":493,"ipfs-unixfs":592,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331}],522:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const log = require('debug')('ipfs:mfs:write') -const importer = require('ipfs-unixfs-importer') -const stat = require('./stat') -const mkdir = require('./mkdir') -const addLink = require('./utils/add-link') -const applyDefaultOptions = require('./utils/apply-default-options') -const createLock = require('./utils/create-lock') -const toAsyncIterator = require('./utils/to-async-iterator') -const toMfsPath = require('./utils/to-mfs-path') -const toPathComponents = require('./utils/to-path-components') -const toTrail = require('./utils/to-trail') -const updateTree = require('./utils/update-tree') -const updateMfsRoot = require('./utils/update-mfs-root') -const errCode = require('err-code') -const { - MAX_CHUNK_SIZE -} = require('./utils/constants') -const last = require('async-iterator-last') - -const defaultOptions = { - offset: 0, // the offset in the file to begin writing - length: undefined, // how many bytes from the incoming buffer to write - create: false, // whether to create the file if it does not exist - truncate: false, // whether to truncate the file first - rawLeaves: false, - reduceSingleLeafToSelf: false, - cidVersion: 0, - hashAlg: 'sha2-256', - format: 'dag-pb', - parents: false, // whether to create intermediate directories if they do not exist - progress: () => {}, - strategy: 'trickle', - flush: true, - leafType: 'raw', - shardSplitThreshold: 1000 -} - -module.exports = (context) => { - return async function mfsWrite (path, content, options) { - log('Hello world, writing', path, content, options) - options = applyDefaultOptions(options, defaultOptions) - - let source, destination, parent - log('Reading source, destination and parent') - await createLock().readLock(async () => { - source = await toAsyncIterator(content, options) - destination = await toMfsPath(context, path) - parent = await toMfsPath(context, destination.mfsDirectory) - })() - log('Read source, destination and parent') - if (!options.parents && !parent.exists) { - throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST') - } - - if (!options.create && !destination.exists) { - throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST') - } - - return updateOrImport(context, path, source, destination, options) - } -} - -const updateOrImport = async (context, path, source, destination, options) => { - const child = await write(context, source, destination, options) - - // The slow bit is done, now add or replace the DAGLink in the containing directory - // re-reading the path to the containing folder in case it has changed in the interim - await createLock().writeLock(async () => { - const pathComponents = toPathComponents(path) - const fileName = pathComponents.pop() - let parentExists = false - - try { - await stat(context)(`/${pathComponents.join('/')}`, options) - parentExists = true - } catch (err) { - if (err.code !== 'ERR_NOT_FOUND') { - throw err - } - } - - if (!parentExists) { - await mkdir(context)(`/${pathComponents.join('/')}`, options) - } - - // get an updated mfs path in case the root changed while we were writing - const updatedPath = await toMfsPath(context, path) - const trail = await toTrail(context, updatedPath.mfsDirectory, options) - const parent = trail[trail.length - 1] - - if (!parent.type.includes('directory')) { - throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY') - } - - const parentNode = await context.ipld.get(parent.cid) - - const result = await addLink(context, { - parent: parentNode, - name: fileName, - cid: child.cid, - size: child.size, - flush: options.flush, - shardSplitThreshold: options.shardSplitThreshold, - format: options.format, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion - }) - - parent.cid = result.cid - - // update the tree with the new child - const newRootCid = await updateTree(context, trail, options) - - // Update the MFS record with the new CID for the root of the tree - await updateMfsRoot(context, newRootCid) - })() -} - -const write = async (context, source, destination, options) => { - if (destination.exists) { - log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`) - } else { - log(`Writing file offset ${options.offset} length ${options.length}`) - } - - const sources = [] - - // pad start of file if necessary - if (options.offset > 0) { - if (destination.unixfs && destination.unixfs.fileSize() > options.offset) { - log(`Writing first ${options.offset} bytes of original file`) - - sources.push( - () => { - return destination.content({ - offset: 0, - length: options.offset - }) - } - ) - } else { - log(`Writing zeros for first ${options.offset} bytes`) - sources.push( - asyncZeroes(options.offset) - ) - } - } - - sources.push( - limitAsyncStreamBytes(source, options.length) - ) - - const content = countBytesStreamed(catAsyncInterators(sources), (bytesWritten) => { - if (destination.unixfs && !options.truncate) { - // if we've done reading from the new source and we are not going - // to truncate the file, add the end of the existing file to the output - const fileSize = destination.unixfs.fileSize() - - if (fileSize > bytesWritten) { - log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`) - - return destination.content({ - offset: bytesWritten - }) - } else { - log(`Not writing last bytes from original file`) - } - } - - return { - [Symbol.asyncIterator]: async function * () {} - } - }) - - let result = await last(importer([{ - content: content - }], context.ipld, { - progress: options.progress, - hashAlg: options.hashAlg, - cidVersion: options.cidVersion, - strategy: options.strategy, - rawLeaves: options.rawLeaves, - reduceSingleLeafToSelf: options.reduceSingleLeafToSelf, - leafType: options.leafType - })) - - log(`Wrote ${result.cid}`) - - return { - cid: result.cid, - size: result.size - } -} - -const limitAsyncStreamBytes = (stream, limit) => { - return async function * _limitAsyncStreamBytes () { - let emitted = 0 - - for await (const buf of stream) { - emitted += buf.length - - if (emitted > limit) { - yield buf.slice(0, limit - emitted) - - return - } - - yield buf - } - } -} - -const asyncZeroes = (count, chunkSize = MAX_CHUNK_SIZE) => { - const buf = Buffer.alloc(chunkSize, 0) - - const stream = { - [Symbol.asyncIterator]: async function * _asyncZeroes () { - while (true) { - yield buf.slice() - } - } - } - - return limitAsyncStreamBytes(stream, count) -} - -const catAsyncInterators = async function * (sources) { - for (let i = 0; i < sources.length; i++) { - for await (const buf of sources[i]()) { - yield buf - } - } -} - -const countBytesStreamed = async function * (source, notify) { - let wrote = 0 - - for await (const buf of source) { - wrote += buf.length - - yield buf - } - - for await (const buf of notify(wrote)) { - wrote += buf.length - - yield buf - } -} - -}).call(this,require("buffer").Buffer) -},{"./mkdir":501,"./stat":505,"./utils/add-link":506,"./utils/apply-default-options":507,"./utils/constants":508,"./utils/create-lock":509,"./utils/to-async-iterator":513,"./utils/to-mfs-path":514,"./utils/to-path-components":515,"./utils/to-trail":518,"./utils/update-mfs-root":519,"./utils/update-tree":520,"async-iterator-last":85,"buffer":217,"debug":493,"err-code":495,"ipfs-unixfs-importer":588}],523:[function(require,module,exports){ -arguments[4][464][0].apply(exports,arguments) -},{"dup":464}],524:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":525,"_process":1438,"dup":247}],525:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":526}],526:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],527:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Key = require('interface-datastore').Key - -const apiFile = new Key('api') - -module.exports = (store) => { - return { - /** - * Get the current configuration from the repo. - * - * @param {function(Error, Object)} callback - * @returns {void} - */ - get (callback) { - store.get(apiFile, (err, value) => callback(err, value && value.toString())) - }, - /** - * Set the current configuration for this repo. - * - * @param {Object} value - the api address to be written - * @param {function(Error)} callback - * @returns {void} - */ - set (value, callback) { - store.put(apiFile, Buffer.from(value.toString()), callback) - }, - /** - * Deletes api file - * - * @param {function(Error, bool)} callback - * @returns {void} - */ - delete (callback) { - store.delete(apiFile, callback) - } - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"interface-datastore":458}],528:[function(require,module,exports){ -'use strict' - -exports.create = function createBackend (name, path, options) { - const Ctor = options.storageBackends[name] - const backendOptions = Object.assign({}, options.storageBackendOptions[name] || {}) - return new Ctor(path, backendOptions) -} - -},{}],529:[function(require,module,exports){ -'use strict' - -const core = require('datastore-core') -const ShardingStore = core.ShardingDatastore -const Key = require('interface-datastore').Key -const base32 = require('base32.js') -const Block = require('ipfs-block') -const setImmediate = require('async/setImmediate') -const reject = require('async/reject') -const CID = require('cids') -const pull = require('pull-stream/pull') -const collect = require('pull-stream/sinks/collect') - -/** - * Transform a raw buffer to a base32 encoded key. - * - * @param {Buffer} rawKey - * @returns {Key} - */ -const keyFromBuffer = (rawKey) => { - const enc = new base32.Encoder() - return new Key('/' + enc.write(rawKey).finalize(), false) -} - -/** - * Transform a cid to the appropriate datastore key. - * - * @param {CID} cid - * @returns {Key} - */ -const cidToDsKey = (cid) => { - return keyFromBuffer(cid.buffer) -} - -module.exports = (filestore, options, callback) => { - maybeWithSharding(filestore, options, (err, store) => { - if (err) { return callback(err) } - - callback(null, createBaseStore(store)) - }) -} - -function maybeWithSharding (filestore, options, callback) { - if (options.sharding) { - const shard = new core.shard.NextToLast(2) - ShardingStore.createOrOpen(filestore, shard, callback) - } else { - setImmediate(() => callback(null, filestore)) - } -} - -function createBaseStore (store) { - return { - /** - * Query the store. - * - * @param {object} query - * @param {function(Error, Array)} callback - * @return {void} - */ - query (query, callback) { - pull( - store.query(query), - collect(callback) - ) - }, - /** - * Get a single block by CID. - * - * @param {CID} cid - * @param {function(Error, Block)} callback - * @returns {void} - */ - get (cid, callback) { - if (!CID.isCID(cid)) { - return setImmediate(() => { - callback(new Error('Not a valid cid')) - }) - } - - const key = cidToDsKey(cid) - store.get(key, (err, blockData) => { - if (err) { - // If not found, we try with the other CID version. - // If exists, then store that block under the CID that was requested. - // Some duplication occurs. - if (err.code === 'ERR_NOT_FOUND') { - const otherCid = cidToOtherVersion(cid) - if (!otherCid) return callback(err) - - const otherKey = cidToDsKey(otherCid) - return store.get(otherKey, (err, blockData) => { - if (err) return callback(err) - - store.put(key, blockData, (err) => { - if (err) return callback(err) - callback(null, new Block(blockData, cid)) - }) - }) - } - - return callback(err) - } - - callback(null, new Block(blockData, cid)) - }) - }, - put (block, callback) { - if (!Block.isBlock(block)) { - return setImmediate(() => { - callback(new Error('invalid block')) - }) - } - - const k = cidToDsKey(block.cid) - - store.has(k, (err, exists) => { - if (err) { return callback(err) } - if (exists) { return callback() } - - store.put(k, block.data, callback) - }) - }, - /** - * Like put, but for more. - * - * @param {Array} blocks - * @param {function(Error)} callback - * @returns {void} - */ - putMany (blocks, callback) { - const keys = blocks.map((b) => ({ - key: cidToDsKey(b.cid), - block: b - })) - - const batch = store.batch() - reject(keys, (k, cb) => store.has(k.key, cb), (err, newKeys) => { - if (err) { - return callback(err) - } - - newKeys.forEach((k) => { - batch.put(k.key, k.block.data) - }) - - batch.commit(callback) - }) - }, - /** - * Does the store contain block with this cid? - * - * @param {CID} cid - * @param {function(Error, bool)} callback - * @returns {void} - */ - has (cid, callback) { - if (!CID.isCID(cid)) { - return setImmediate(() => { - callback(new Error('Not a valid cid')) - }) - } - - store.has(cidToDsKey(cid), (err, exists) => { - if (err) return callback(err) - if (exists) return callback(null, true) - - // If not found, we try with the other CID version. - const otherCid = cidToOtherVersion(cid) - if (!otherCid) return callback(null, false) - - store.has(cidToDsKey(otherCid), callback) - }) - }, - /** - * Delete a block from the store - * - * @param {CID} cid - * @param {function(Error)} callback - * @returns {void} - */ - delete (cid, callback) { - if (!CID.isCID(cid)) { - return setImmediate(() => { - callback(new Error('Not a valid cid')) - }) - } - - store.delete(cidToDsKey(cid), callback) - }, - - close (callback) { - store.close(callback) - } - } -} - -function cidToOtherVersion (cid) { - try { - return cid.version === 0 ? cid.toV1() : cid.toV0() - } catch (err) { - return null - } -} - -},{"async/reject":143,"async/setImmediate":146,"base32.js":160,"cids":222,"datastore-core":238,"interface-datastore":458,"ipfs-block":491,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497}],530:[function(require,module,exports){ -'use strict' - -const Key = require('interface-datastore').Key -const queue = require('async/queue') -const waterfall = require('async/waterfall') -const _get = require('dlv') -const _set = require('just-safe-set') -const Buffer = require('buffer').Buffer - -const configKey = new Key('config') - -module.exports = (store) => { - const setQueue = queue(_doSet, 1) - - const configStore = { - /** - * Get the current configuration from the repo. - * - * @param {String} key - the config key to get - * @param {function(Error, Object)} callback - * @returns {void} - */ - get (key, callback) { - if (typeof key === 'function') { - callback = key - key = undefined - } - if (!key) { - key = undefined - } - store.get(configKey, (err, encodedValue) => { - if (err) { return callback(err) } - - let config - try { - config = JSON.parse(encodedValue.toString()) - } catch (err) { - return callback(err) - } - - if (typeof key === 'undefined') { - return callback(null, config) - } - - if (typeof key !== 'string') { - return callback(new Error('Key ' + key + ' must be a string.')) - } - - const value = _get(config, key, null) - - if (value === null) { - return callback(new Error('Key ' + key + ' does not exist in config.')) - } - - callback(null, value) - }) - }, - /** - * Set the current configuration for this repo. - * - * @param {String} key - the config key to be written - * @param {Object} value - the config value to be written - * @param {function(Error)} callback - * @returns {void} - */ - set (key, value, callback) { - if (typeof value === 'function') { - callback = value - value = key - key = undefined - } else if (!key || typeof key !== 'string') { - return callback(new Error('Invalid key type')) - } - - if (value === undefined || Buffer.isBuffer(value)) { - return callback(new Error('Invalid value type')) - } - - setQueue.push({ - key: key, - value: value - }, callback) - }, - - /** - * Check if a config file exists. - * - * @param {function(Error, bool)} callback - * @returns {void} - */ - exists (callback) { - store.has(configKey, callback) - } - } - - return configStore - - function _doSet (m, callback) { - const key = m.key - const value = m.value - if (key) { - waterfall( - [ - (cb) => configStore.get(cb), - (config, cb) => { - _set(config, key, value) - cb(null, config) - }, - _saveAll - ], - callback) - } else { - _saveAll(value, callback) - } - } - - function _saveAll (config, callback) { - const buf = Buffer.from(JSON.stringify(config, null, 2)) - store.put(configKey, buf, callback) - } -} - -},{"async/queue":142,"async/waterfall":152,"buffer":217,"dlv":276,"interface-datastore":458,"just-safe-set":831}],531:[function(require,module,exports){ -'use strict' - -module.exports = { - repoVersion: 7 -} - -},{}],532:[function(require,module,exports){ -'use strict' - -// Default configuration for the datastore spec in node.js -module.exports = { - Spec: { - type: 'mount', - mounts: [ - { - mountpoint: '/blocks', - type: 'measure', - prefix: 'flatfs.datastore', - child: { - type: 'flatfs', - path: 'blocks', - sync: true, - shardFunc: '/repo/flatfs/shard/v1/next-to-last/2' - } - }, - { - mountpoint: '/', - type: 'measure', - prefix: 'leveldb.datastore', - child: { - type: 'levelds', - path: 'datastore', - compression: 'none' - } - } - ] - } -} - -},{}],533:[function(require,module,exports){ -'use strict' - -// Default configuration for a repo in the browser -module.exports = { - lock: 'memory', - storageBackends: { - root: require('datastore-level'), - blocks: require('datastore-level'), - keys: require('datastore-level'), - datastore: require('datastore-level') - }, - storageBackendOptions: { - root: { - extension: '' - }, - blocks: { - sharding: false - }, - keys: { - sharding: false - } - } -} - -},{"datastore-level":246}],534:[function(require,module,exports){ -'use strict' - -exports.ERR_REPO_NOT_INITIALIZED = 'ERR_REPO_NOT_INITIALIZED' - -},{}],535:[function(require,module,exports){ -(function (setImmediate){ -'use strict' - -const waterfall = require('async/waterfall') -const series = require('async/series') -const parallel = require('async/parallel') -const each = require('async/each') -const _get = require('dlv') -const assert = require('assert') -const path = require('path') -const debug = require('debug') -const Big = require('bignumber.js') -const pull = require('pull-stream/pull') -const reduce = require('pull-stream/sinks/reduce') - -const backends = require('./backends') -const version = require('./version') -const config = require('./config') -const spec = require('./spec') -const apiAddr = require('./api-addr') -const blockstore = require('./blockstore') -const defaultOptions = require('./default-options') -const defaultDatastore = require('./default-datastore') -const ERRORS = require('./errors') - -const log = debug('repo') - -const noLimit = Number.MAX_SAFE_INTEGER - -const lockers = { - memory: require('./lock-memory'), - fs: require('./lock') -} - -const repoVersion = require('./constants').repoVersion - -/** - * IpfsRepo implements all required functionality to read and write to an ipfs repo. - * - */ -class IpfsRepo { - /** - * @param {string} repoPath - path where the repo is stored - * @param {object} options - Configuration - */ - constructor (repoPath, options) { - assert.strictEqual(typeof repoPath, 'string', 'missing repoPath') - - this.options = buildOptions(options) - this.closed = true - this.path = repoPath - - this._locker = this._getLocker() - - this.root = backends.create('root', this.path, this.options) - this.version = version(this.root) - this.config = config(this.root) - this.spec = spec(this.root) - this.apiAddr = apiAddr(this.root) - } - - /** - * Initialize a new repo. - * - * @param {Object} config - config to write into `config`. - * @param {function(Error)} callback - * @returns {void} - */ - init (config, callback) { - log('initializing at: %s', this.path) - - series([ - (cb) => this.root.open(ignoringAlreadyOpened(cb)), - (cb) => this.config.set(buildConfig(config), cb), - (cb) => this.spec.set(buildDatastoreSpec(config), cb), - (cb) => this.version.set(repoVersion, cb) - ], callback) - } - - /** - * Open the repo. If the repo is already open no action will be taken. - * If the repo is not initialized it will return an error. - * - * @param {function(Error)} callback - * @returns {void} - */ - open (callback) { - if (!this.closed) { - setImmediate(() => callback(new Error('repo is already open'))) - return // early - } - log('opening at: %s', this.path) - - // check if the repo is already initialized - waterfall([ - (cb) => this.root.open(ignoringAlreadyOpened(cb)), - (cb) => this._isInitialized(cb), - (cb) => this._openLock(this.path, cb), - (lck, cb) => { - log('aquired repo.lock') - this.lockfile = lck - cb() - }, - (cb) => { - log('creating datastore') - this.datastore = backends.create('datastore', path.join(this.path, 'datastore'), this.options) - log('creating blocks') - const blocksBaseStore = backends.create('blocks', path.join(this.path, 'blocks'), this.options) - blockstore( - blocksBaseStore, - this.options.storageBackendOptions.blocks, - cb) - }, - (blocks, cb) => { - this.blocks = blocks - cb() - }, - (cb) => { - log('creating keystore') - this.keys = backends.create('keys', path.join(this.path, 'keys'), this.options) - cb() - }, - - (cb) => { - this.closed = false - log('all opened') - cb() - } - ], (err) => { - if (err && this.lockfile) { - this._closeLock((err2) => { - if (!err2) { - this.lockfile = null - } else { - log('error removing lock', err2) - } - callback(err) - }) - } else { - callback(err) - } - }) - } - - /** - * Returns the repo locker to be used. Null will be returned if no locker is requested - * - * @private - * @returns {Locker} - */ - _getLocker () { - if (typeof this.options.lock === 'string') { - assert(lockers[this.options.lock], 'Unknown lock type: ' + this.options.lock) - return lockers[this.options.lock] - } - - assert(this.options.lock, 'No lock provided') - return this.options.lock - } - - /** - * Creates a lock on the repo if a locker is specified. The lockfile object will - * be returned in the callback if one has been created. - * - * @param {string} path - * @param {function(Error, lockfile)} callback - * @returns {void} - */ - _openLock (path, callback) { - this._locker.lock(path, (err, lockfile) => { - if (err) { - return callback(err, null) - } - - assert.strictEqual(typeof lockfile.close, 'function', 'Locks must have a close method') - callback(null, lockfile) - }) - } - - /** - * Closes the lock on the repo - * - * @param {function(Error)} callback - * @returns {void} - */ - _closeLock (callback) { - if (this.lockfile) { - return this.lockfile.close(callback) - } - callback() - } - - /** - * Check if the repo is already initialized. - * - * @private - * @param {function(Error)} callback - * @returns {void} - */ - _isInitialized (callback) { - log('init check') - parallel( - { - config: (cb) => this.config.exists(cb), - spec: (cb) => this.spec.exists(cb), - version: (cb) => this.version.check(repoVersion, cb) - }, - (err, res) => { - log('init', err, res) - if (err && !res.config) { - return callback(Object.assign(new Error('repo is not initialized yet'), - { - code: ERRORS.ERR_REPO_NOT_INITIALIZED, - path: this.path - })) - } - callback(err) - } - ) - } - - /** - * Close the repo and cleanup. - * - * @param {function(Error)} callback - * @returns {void} - */ - close (callback) { - if (this.closed) { - return callback(new Error('repo is already closed')) - } - - log('closing at: %s', this.path) - series([ - (cb) => this.apiAddr.delete(ignoringNotFound(cb)), - (cb) => { - each( - [this.blocks, this.keys, this.datastore], - (store, callback) => store.close(callback), - cb) - }, - (cb) => { - log('unlocking') - this.closed = true - this._closeLock(cb) - }, - (cb) => { - this.lockfile = null - cb() - } - ], (err) => callback(err)) - } - - /** - * Check if a repo exists. - * - * @param {function(Error, bool)} callback - * @returns {void} - */ - exists (callback) { - this.version.exists(callback) - } - - /** - * Get repo status. - * - * @param {Object} options - * @param {Boolean} options.human - * @param {function(Error, Object)} callback - * @return {void} - */ - stat (options, callback) { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = Object.assign({}, { human: false }, options) - - parallel({ - storageMax: (cb) => this.config.get('Datastore.StorageMax', (err, max) => { - if (err) { - cb(null, new Big(noLimit)) - } else { - cb(null, new Big(max)) - } - }), - version: (cb) => this.version.get(cb), - blocks: (cb) => this.blocks.query({}, (err, list) => { - list = list || [] - - const count = new Big(list.length) - let size = new Big(0) - - list.forEach(block => { - size = size - .plus(block.value.byteLength) - .plus(block.key._buf.byteLength) - }) - - cb(err, { - count: count, - size: size - }) - }), - datastore: (cb) => getSize(this.datastore, cb), - keys: (cb) => getSize(this.keys, cb) - }, (err, results) => { - if (err) return callback(err) - - let size = results.blocks.size - .plus(results.datastore) - .plus(results.keys) - - if (options.human) { - size = size.div(1048576) - } - - callback(null, { - repoPath: this.path, - storageMax: results.storageMax, - version: results.version, - numObjects: results.blocks.count, - repoSize: size - }) - }) - } -} - -function getSize (queryFn, callback) { - pull( - queryFn.query({}), - reduce((sum, block) => { - return sum - .plus(block.value.byteLength) - .plus(block.key._buf.byteLength) - }, new Big(0), callback)) -} - -module.exports = IpfsRepo -module.exports.repoVersion = repoVersion -module.exports.errors = ERRORS - -function ignoringIf (cond, cb) { - return (err) => { - cb(err && !cond(err) ? err : null) - } -} -function ignoringAlreadyOpened (cb) { - return ignoringIf((err) => err.message === 'Already open', cb) -} - -function ignoringNotFound (cb) { - return ignoringIf((err) => { - return err && (err.code === ERRORS.ERR_REPO_NOT_INITIALIZED || err.message.startsWith('ENOENT')) - }, cb) -} - -function buildOptions (_options) { - const options = Object.assign({}, defaultOptions, _options) - - options.storageBackends = Object.assign( - {}, - defaultOptions.storageBackends, - options.storageBackends) - - options.storageBackendOptions = Object.assign( - {}, - defaultOptions.storageBackendOptions, - options.storageBackendOptions) - - return options -} - -// TODO this should come from js-ipfs instead -function buildConfig (_config) { - _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {})) - - return _config -} - -function buildDatastoreSpec (_config) { - const spec = Object.assign({}, defaultDatastore.Spec, _get(_config, 'datastore.Spec', {})) - - return { - type: spec.type, - mounts: spec.mounts.map((mounting) => ({ - mountpoint: mounting.mountpoint, - type: mounting.child.type, - path: mounting.child.path, - shardFunc: mounting.child.shardFunc - })) - } -} - -}).call(this,require("timers").setImmediate) -},{"./api-addr":527,"./backends":528,"./blockstore":529,"./config":530,"./constants":531,"./default-datastore":532,"./default-options":533,"./errors":534,"./lock":536,"./lock-memory":536,"./spec":537,"./version":538,"assert":78,"async/each":106,"async/parallel":141,"async/series":145,"async/waterfall":152,"bignumber.js":523,"debug":524,"dlv":276,"path":1425,"pull-stream/pull":1496,"pull-stream/sinks/reduce":1504,"timers":1749}],536:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const setImmediate = require('async/setImmediate') - -const log = debug('repo:lock') - -const lockFile = 'repo.lock' - -const LOCKS = {} - -/** - * Lock the repo in the given dir. - * - * @param {string} dir - * @param {function(Error, lock)} callback - * @returns {void} - */ -exports.lock = (dir, callback) => { - const file = dir + '/' + lockFile - log('locking %s', file) - LOCKS[file] = true - const closer = { - close (cb) { - if (LOCKS[file]) { - delete LOCKS[file] - } - setImmediate(cb) - } - } - setImmediate(() => { - callback(null, closer) - }) -} - -/** - * Check if the repo in the given directory is locked. - * - * @param {string} dir - * @param {function(Error, bool)} callback - * @returns {void} - */ -exports.locked = (dir, callback) => { - const file = dir + '/' + lockFile - log('checking lock: %s') - - const locked = LOCKS[file] - setImmediate(() => { - callback(null, locked) - }) -} - -},{"async/setImmediate":146,"debug":524}],537:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Key = require('interface-datastore').Key -const sortKeys = require('sort-keys') - -const specKey = new Key('datastore_spec') - -module.exports = (store) => { - return { - /** - * Check if a datastore spec file exists. - * - * @param {function(Error, bool)} callback - * @returns {void} - */ - exists (callback) { - store.has(specKey, callback) - }, - /** - * Get the current datastore spec. - * - * @param {function(Error, number)} callback - * @returns {void} - */ - get (callback) { - store.get(specKey, (err, buf) => { - if (err) { - return callback(err) - } - callback(null, JSON.parse(buf.toString())) - }) - }, - /** - * Set the datastore spec of the repo, writing it to the underlying store. - * - * @param {number} spec - * @param {function(Error)} callback - * @returns {void} - */ - set (spec, callback) { - store.put(specKey, Buffer.from(JSON.stringify(sortKeys(spec, { deep: true }))), callback) - } - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"interface-datastore":458,"sort-keys":1671}],538:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Key = require('interface-datastore').Key -const debug = require('debug') -const log = debug('repo:version') - -const versionKey = new Key('version') - -module.exports = (store) => { - return { - /** - * Check if a version file exists. - * - * @param {function(Error, bool)} callback - * @returns {void} - */ - exists (callback) { - store.has(versionKey, callback) - }, - /** - * Get the current version. - * - * @param {function(Error, number)} callback - * @returns {void} - */ - get (callback) { - store.get(versionKey, (err, buf) => { - if (err) { - return callback(err) - } - callback(null, parseInt(buf.toString().trim(), 10)) - }) - }, - /** - * Set the version of the repo, writing it to the underlying store. - * - * @param {number} version - * @param {function(Error)} callback - * @returns {void} - */ - set (version, callback) { - store.put(versionKey, Buffer.from(String(version)), callback) - }, - /** - * Check the current version, and return an error on missmatch - * @param {number} expected - * @param {function(Error)} callback - * @returns {void} - */ - check (expected, callback) { - this.get((err, version) => { - if (err) { - return callback(err) - } - log('comparing version: %s and %s', version, expected) - - // Version 6 and 7 are the same - // TODO: Clean up the compatibility logic. Repo feature detection would be ideal, or a better version schema - const compatibleVersion = (version === 6 && expected === 7) || (expected === 6 && version === 7) - - if (version !== expected && !compatibleVersion) { - return callback(new Error(`ipfs repo needs migration: expected version v${expected}, found version v${version}`)) - } - callback() - }) - } - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"debug":524,"interface-datastore":458}],539:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],540:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const errCode = require('err-code') -const CID = require('cids') -const resolve = require('./resolvers') -const last = require('async-iterator-last') - -const toPathComponents = (path = '') => { - // split on / unless escaped with \ - return (path - .trim() - .match(/([^\\^/]|\\\/)+/g) || []) - .filter(Boolean) -} - -const cidAndRest = (path) => { - if (Buffer.isBuffer(path)) { - return { - cid: new CID(path), - toResolve: [] - } - } - - if (CID.isCID(path)) { - return { - cid: path, - toResolve: [] - } - } - - if (typeof path === 'string') { - if (path.indexOf('/ipfs/') === 0) { - path = path.substring(6) - } - - const output = toPathComponents(path) - - return { - cid: new CID(output[0]), - toResolve: output.slice(1) - } - } - - throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH') -} - -const walkPath = async function * (path, ipld) { - let { - cid, - toResolve - } = cidAndRest(path) - let name = cid.toBaseEncodedString() - let entryPath = name - const startingDepth = toResolve.length - - while (true) { - const result = await resolve(cid, name, entryPath, toResolve, startingDepth, ipld) - - if (!result.entry && !result.next) { - throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND') - } - - if (result.entry) { - yield result.entry - } - - if (!result.next) { - return - } - - // resolve further parts - toResolve = result.next.toResolve - cid = result.next.cid - name = result.next.name - entryPath = result.next.path - } -} - -const exporter = (path, ipld) => { - return last(walkPath(path, ipld)) -} - -const recursive = async function * (path, ipld) { - const node = await exporter(path, ipld) - - yield node - - if (node.unixfs && node.unixfs.type.includes('dir')) { - for await (const child of recurse(node)) { - yield child - } - } - - async function * recurse (node) { - for await (const file of node.content()) { - yield file - - if (file.unixfs.type.includes('dir')) { - for await (const subFile of recurse(file)) { - yield subFile - } - } - } - } -} - -module.exports = exporter -module.exports.path = walkPath -module.exports.recursive = recursive - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./resolvers":542,"async-iterator-last":85,"cids":222,"err-code":539}],541:[function(require,module,exports){ -'use strict' - -const CID = require('cids') -const errCode = require('err-code') - -const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => { - let node = await ipld.get(cid) - let subObject = node - let subPath = path - - while (toResolve.length) { - const prop = toResolve[0] - - if (prop in subObject) { - // remove the bit of the path we have resolved - toResolve.shift() - subPath = `${subPath}/${prop}` - - if (CID.isCID(subObject[prop])) { - return { - entry: { - name, - path, - cid, - node, - depth - }, - next: { - cid: subObject[prop], - name: prop, - path: subPath, - toResolve - } - } - } - - subObject = subObject[prop] - } else { - // cannot resolve further - throw errCode(new Error(`No property named ${prop} found in cbor node ${cid.toBaseEncodedString()}`), 'ERR_NO_PROP') - } - } - - return { - entry: { - name, - path, - cid, - node, - depth - } - } -} - -module.exports = resolve - -},{"cids":222,"err-code":539}],542:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') - -const resolvers = { - 'dag-pb': require('./unixfs-v1'), - raw: require('./raw'), - 'dag-cbor': require('./dag-cbor') -} - -const resolve = (cid, name, path, toResolve, depth, ipld) => { - const resolver = resolvers[cid.codec] - - if (!resolver) { - throw errCode(new Error(`No resolver for codec ${cid.codec}`), 'ERR_NO_RESOLVER') - } - - return resolver(cid, name, path, toResolve, resolve, depth, ipld) -} - -module.exports = resolve - -},{"./dag-cbor":541,"./raw":543,"./unixfs-v1":547,"err-code":539}],543:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const extractDataFromBlock = require('../utils/extract-data-from-block') -const validateOffsetAndLength = require('../utils/validate-offset-and-length') - -const rawContent = (node) => { - return function * (options = {}) { - const { - offset, - length - } = validateOffsetAndLength(node.length, options.offset, options.length) - - yield extractDataFromBlock(node, 0, offset, offset + length) - } -} - -const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => { - if (toResolve.length) { - throw errCode(new Error(`No link named ${path} found in raw node ${cid.toBaseEncodedString()}`), 'ERR_NOT_FOUND') - } - - const buf = await ipld.get(cid) - - return { - entry: { - name, - path, - cid, - node: buf, - content: rawContent(buf), - depth - } - } -} - -module.exports = resolve - -},{"../utils/extract-data-from-block":548,"../utils/validate-offset-and-length":550,"err-code":539}],544:[function(require,module,exports){ -'use strict' - -const directoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => { - return async function * (options = {}) { - const offset = options.offset || 0 - const length = options.length || node.Links.length - const links = node.Links.slice(offset, length) - - for (const link of links) { - const result = await resolve(link.Hash, link.Name, `${path}/${link.Name}`, [], depth + 1, ipld) - - yield result.entry - } - } -} - -module.exports = directoryContent - -},{}],545:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const extractDataFromBlock = require('../../../utils/extract-data-from-block') -const validateOffsetAndLength = require('../../../utils/validate-offset-and-length') -const UnixFS = require('ipfs-unixfs') -const errCode = require('err-code') - -async function * emitBytes (ipld, node, start, end, streamPosition = 0) { - // a `raw` node - if (Buffer.isBuffer(node)) { - const buf = extractDataFromBlock(node, streamPosition, start, end) - - if (buf.length) { - yield buf - } - - streamPosition += buf.length - - return streamPosition - } - - let file - - try { - file = UnixFS.unmarshal(node.Data) - } catch (err) { - throw errCode(err, 'ERR_NOT_UNIXFS') - } - - // might be a unixfs `raw` node or have data on intermediate nodes - const nodeHasData = Boolean(file.data && file.data.length) - - if (nodeHasData) { - const buf = extractDataFromBlock(file.data, streamPosition, start, end) - - if (buf.length) { - yield buf - } - - streamPosition += file.data.length - } - - let childStart = streamPosition - - // work out which child nodes contain the requested data - for (let i = 0; i < node.Links.length; i++) { - const childLink = node.Links[i] - const childEnd = streamPosition + file.blockSizes[i] - - if ((start >= childStart && start < childEnd) || // child has offset byte - (end > childStart && end <= childEnd) || // child has end byte - (start < childStart && end > childEnd)) { // child is between offset and end bytes - const child = await ipld.get(childLink.Hash) - - for await (const buf of emitBytes(ipld, child, start, end, streamPosition)) { - streamPosition += buf.length - - yield buf - } - } - - streamPosition = childEnd - childStart = childEnd + 1 - } -} - -const fileContent = (cid, node, unixfs, path, resolve, depth, ipld) => { - return (options = {}) => { - const fileSize = unixfs.fileSize() - - const { - offset, - length - } = validateOffsetAndLength(fileSize, options.offset, options.length) - - const start = offset - const end = offset + length - - return emitBytes(ipld, node, start, end) - } -} - -module.exports = fileContent - -}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"../../../utils/extract-data-from-block":548,"../../../utils/validate-offset-and-length":550,"err-code":539,"ipfs-unixfs":592}],546:[function(require,module,exports){ -'use strict' - -const hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => { - return (options = {}) => { - return listDirectory(node, path, resolve, depth, ipld, options) - } -} - -async function * listDirectory (node, path, resolve, depth, ipld, options) { - const links = node.Links - - for (const link of links) { - const name = link.Name.substring(2) - - if (name) { - const result = await resolve(link.Hash, name, `${path}/${name}`, [], depth + 1, ipld) - - yield result.entry - } else { - // descend into subshard - node = await ipld.get(link.Hash) - - for await (const file of listDirectory(node, path, resolve, depth, ipld, options)) { - yield file - } - } - } -} - -module.exports = hamtShardedDirectoryContent - -},{}],547:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const UnixFS = require('ipfs-unixfs') -const findShardCid = require('../../utils/find-cid-in-shard') - -const findLinkCid = (node, name) => { - const link = node.Links.find(link => link.Name === name) - - return link && link.Hash -} - -const contentExporters = { - raw: require('./content/file'), - file: require('./content/file'), - directory: require('./content/directory'), - 'hamt-sharded-directory': require('./content/hamt-sharded-directory'), - metadata: (cid, node, unixfs, path, resolve, depth, ipld) => {}, - symlink: (cid, node, unixfs, path, resolve, depth, ipld) => {} -} - -const unixFsResolver = async (cid, name, path, toResolve, resolve, depth, ipld) => { - const node = await ipld.get(cid) - let unixfs - let next - - if (!name) { - name = cid.toBaseEncodedString() - } - - try { - unixfs = UnixFS.unmarshal(node.Data) - } catch (err) { - // non-UnixFS dag-pb node? It could happen. - throw errCode(err, 'ERR_NOT_UNIXFS') - } - - if (!path) { - path = name - } - - if (toResolve.length) { - let linkCid - - if (unixfs && unixfs.type === 'hamt-sharded-directory') { - // special case - unixfs v1 hamt shards - linkCid = await findShardCid(node, toResolve[0], ipld) - } else { - linkCid = findLinkCid(node, toResolve[0]) - } - - if (!linkCid) { - throw errCode(new Error(`file does not exist`), 'ERR_NOT_FOUND') - } - - // remove the path component we have resolved - const nextName = toResolve.shift() - const nextPath = `${path}/${nextName}` - - next = { - cid: linkCid, - toResolve, - name: nextName, - path: nextPath - } - } - - return { - entry: { - name, - path, - cid, - node, - content: contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, ipld), - unixfs, - depth - }, - next - } -} - -module.exports = unixFsResolver - -},{"../../utils/find-cid-in-shard":549,"./content/directory":544,"./content/file":545,"./content/hamt-sharded-directory":546,"err-code":539,"ipfs-unixfs":592}],548:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -module.exports = function extractDataFromBlock (block, blockStart, requestedStart, requestedEnd) { - const blockLength = block.length - const blockEnd = blockStart + blockLength - - if (requestedStart >= blockEnd || requestedEnd < blockStart) { - // If we are looking for a byte range that is starts after the start of the block, - // return an empty block. This can happen when internal nodes contain data - return Buffer.alloc(0) - } - - if (requestedEnd >= blockStart && requestedEnd < blockEnd) { - // If the end byte is in the current block, truncate the block to the end byte - block = block.slice(0, requestedEnd - blockStart) - } - - if (requestedStart >= blockStart && requestedStart < blockEnd) { - // If the start byte is in the current block, skip to the start byte - block = block.slice(requestedStart - blockStart) - } - - return block -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217}],549:[function(require,module,exports){ -'use strict' - -const Bucket = require('hamt-sharding/src/bucket') -const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded') - -const addLinksToHamtBucket = (links, bucket, rootBucket) => { - return Promise.all( - links.map(link => { - if (link.Name.length === 2) { - const pos = parseInt(link.Name, 16) - - return bucket._putObjectAt(pos, new Bucket({ - hashFn: DirSharded.hashFn - }, bucket, pos)) - } - - return rootBucket.put(link.Name.substring(2), true) - }) - ) -} - -const toPrefix = (position) => { - return position - .toString('16') - .toUpperCase() - .padStart(2, '0') - .substring(0, 2) -} - -const toBucketPath = (position) => { - let bucket = position.bucket - const path = [] - - while (bucket._parent) { - path.push(bucket) - - bucket = bucket._parent - } - - path.push(bucket) - - return path.reverse() -} - -const findShardCid = async (node, name, ipld, context) => { - if (!context) { - context = { - rootBucket: new Bucket({ - hashFn: DirSharded.hashFn - }), - hamtDepth: 1 - } - - context.lastBucket = context.rootBucket - } - - await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket) - - const position = await context.rootBucket._findNewBucketAndPos(name) - let prefix = toPrefix(position.pos) - const bucketPath = toBucketPath(position) - - if (bucketPath.length > (context.hamtDepth)) { - context.lastBucket = bucketPath[context.hamtDepth] - - prefix = toPrefix(context.lastBucket._posAtParent) - } - - const link = node.Links.find(link => { - const entryPrefix = link.Name.substring(0, 2) - const entryName = link.Name.substring(2) - - if (entryPrefix !== prefix) { - // not the entry or subshard we're looking for - return - } - - if (entryName && entryName !== name) { - // not the entry we're looking for - return - } - - return true - }) - - if (!link) { - return null - } - - if (link.Name.substring(2) === name) { - return link.Hash - } - - context.hamtDepth++ - - node = await ipld.get(link.Hash) - - return findShardCid(node, name, ipld, context) -} - -module.exports = findShardCid - -},{"hamt-sharding/src/bucket":394,"ipfs-unixfs-importer/src/dir-sharded":585}],550:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') - -const validateOffsetAndLength = (size, offset, length) => { - if (!offset) { - offset = 0 - } - - if (offset < 0) { - throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') - } - - if (offset > size) { - throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS') - } - - if (!length && length !== 0) { - length = size - offset - } - - if (length < 0) { - throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS') - } - - if (offset + length > size) { - length = size - offset - } - - return { - offset, - length - } -} - -module.exports = validateOffsetAndLength - -},{"err-code":539}],551:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var DuplexStream = require('readable-stream').Duplex - , util = require('util') - -function BufferList (callback) { - if (!(this instanceof BufferList)) - return new BufferList(callback) - - this._bufs = [] - this.length = 0 - - if (typeof callback == 'function') { - this._callback = callback - - var piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - } else { - this.append(callback) - } - - DuplexStream.call(this) -} - - -util.inherits(BufferList, DuplexStream) - - -BufferList.prototype._offset = function _offset (offset) { - var tot = 0, i = 0, _t - if (offset === 0) return [ 0, 0 ] - for (; i < this._bufs.length; i++) { - _t = tot + this._bufs[i].length - if (offset < _t || i == this._bufs.length - 1) { - return [ i, offset - tot ] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - var bufferId = blOffset[0] - var offset = blOffset[1] - for (var i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - return offset -} - -BufferList.prototype.append = function append (buf) { - var i = 0 - - if (Buffer.isBuffer(buf)) { - this._appendBuffer(buf) - } else if (Array.isArray(buf)) { - for (; i < buf.length; i++) - this.append(buf[i]) - } else if (buf instanceof BufferList) { - // unwrap argument into individual BufferLists - for (; i < buf._bufs.length; i++) - this.append(buf._bufs[i]) - } else if (buf != null) { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf == 'number') - buf = buf.toString() - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - - -BufferList.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback == 'function') - callback() -} - - -BufferList.prototype._read = function _read (size) { - if (!this.length) - return this.push(null) - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - - -BufferList.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - var offset = this._offset(index) - return this._bufs[offset[0]][offset[1]] -} - - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start == 'number' && start < 0) - start += this.length - if (typeof end == 'number' && end < 0) - end += this.length - return this.copy(null, 0, start, end) -} - - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart != 'number' || srcStart < 0) - srcStart = 0 - if (typeof srcEnd != 'number' || srcEnd > this.length) - srcEnd = this.length - if (srcStart >= this.length) - return dst || Buffer.alloc(0) - if (srcEnd <= 0) - return dst || Buffer.alloc(0) - - var copy = !!dst - , off = this._offset(srcStart) - , len = srcEnd - srcStart - , bytes = len - , bufoff = (copy && dstStart) || 0 - , start = off[1] - , l - , i - - // copy/slice everything - if (srcStart === 0 && srcEnd == this.length) { - if (!copy) { // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - - for (i = off[0]; i < this._bufs.length; i++) { - l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - break - } - - bufoff += l - bytes -= l - - if (start) - start = 0 - } - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) - start += this.length - if (end < 0) - end += this.length - - if (start === end) { - return new BufferList() - } - var startOffset = this._offset(start) - , endOffset = this._offset(end) - , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] == 0) - buffers.pop() - else - buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) - - if (startOffset[1] != 0) - buffers[0] = buffers[0].slice(startOffset[1]) - - return new BufferList(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - return this -} - - -BufferList.prototype.duplicate = function duplicate () { - var i = 0 - , copy = new BufferList() - - for (; i < this._bufs.length; i++) - copy.append(this._bufs[i]) - - return copy -} - - -BufferList.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} - - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (search instanceof BufferList) { - search = search.slice() - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - var blOffset = this._offset(offset) - var blIndex = blOffset[0] // index of which internal buffer we're working on - var buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (blIndex; blIndex < this._bufs.length; blIndex++) { - var buff = this._bufs[blIndex] - while(buffOffset < buff.length) { - var availableWindow = buff.length - buffOffset - if (availableWindow >= search.length) { - var nativeSearchResult = buff.indexOf(search, buffOffset) - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - var revOffset = this._reverseOffset([blIndex, buffOffset]) - if (this._match(revOffset, search)) { - return revOffset - } - buffOffset++ - } - } - buffOffset = 0 - } - return -1 -} - -BufferList.prototype._match = function(offset, search) { - if (this.length - offset < search.length) { - return false - } - for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { - if(this.get(offset + searchOffset) !== search[searchOffset]){ - return false - } - } - return true -} - - -;(function () { - var methods = { - 'readDoubleBE' : 8 - , 'readDoubleLE' : 8 - , 'readFloatBE' : 4 - , 'readFloatLE' : 4 - , 'readInt32BE' : 4 - , 'readInt32LE' : 4 - , 'readUInt32BE' : 4 - , 'readUInt32LE' : 4 - , 'readInt16BE' : 2 - , 'readInt16LE' : 2 - , 'readUInt16BE' : 2 - , 'readUInt16LE' : 2 - , 'readInt8' : 1 - , 'readUInt8' : 1 - , 'readIntBE' : null - , 'readIntLE' : null - , 'readUIntBE' : null - , 'readUIntLE' : null - } - - for (var m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } - else { - BufferList.prototype[m] = function (offset) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - - -module.exports = BufferList - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"readable-stream":573,"util":1776}],552:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],553:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],554:[function(require,module,exports){ -'use strict' - -const { Buffer } = require('buffer') -const blake = require('blakejs') - -const minB = 0xb201 -const minS = 0xb241 - -const blake2b = { - init: blake.blake2bInit, - update: blake.blake2bUpdate, - digest: blake.blake2bFinal -} - -const blake2s = { - init: blake.blake2sInit, - update: blake.blake2sUpdate, - digest: blake.blake2sFinal -} - -// Note that although this function doesn't do any asynchronous work, we mark -// the function as async because it must return a Promise to match the API -// for other functions that do perform asynchronous work (see sha.browser.js) -const makeB2Hash = (size, hf) => async (data) => { - const ctx = hf.init(size, null) - hf.update(ctx, data) - return Buffer.from(hf.digest(ctx)) -} - -module.exports = (table) => { - for (let i = 0; i < 64; i++) { - table[minB + i] = makeB2Hash(i + 1, blake2b) - } - for (let i = 0; i < 32; i++) { - table[minS + i] = makeB2Hash(i + 1, blake2s) - } -} - -},{"blakejs":168,"buffer":217}],555:[function(require,module,exports){ -'use strict' - -const { Buffer } = require('buffer') -const sha3 = require('js-sha3') -const mur = require('murmurhash3js-revisited') -const sha = require('./sha') -const { fromNumberTo32BitBuf } = require('./utils') - -// Note that although this function doesn't do any asynchronous work, we mark -// the function as async because it must return a Promise to match the API -// for other functions that do perform asynchronous work (see sha.browser.js) -const hash = (algorithm) => async (data) => { - switch (algorithm) { - case 'sha3-224': - return Buffer.from(sha3.sha3_224.arrayBuffer(data)) - case 'sha3-256': - return Buffer.from(sha3.sha3_256.arrayBuffer(data)) - case 'sha3-384': - return Buffer.from(sha3.sha3_384.arrayBuffer(data)) - case 'sha3-512': - return Buffer.from(sha3.sha3_512.arrayBuffer(data)) - case 'shake-128': - return Buffer.from(sha3.shake128.create(128).update(data).arrayBuffer()) - case 'shake-256': - return Buffer.from(sha3.shake256.create(256).update(data).arrayBuffer()) - case 'keccak-224': - return Buffer.from(sha3.keccak224.arrayBuffer(data)) - case 'keccak-256': - return Buffer.from(sha3.keccak256.arrayBuffer(data)) - case 'keccak-384': - return Buffer.from(sha3.keccak384.arrayBuffer(data)) - case 'keccak-512': - return Buffer.from(sha3.keccak512.arrayBuffer(data)) - case 'murmur3-128': - return Buffer.from(mur.x64.hash128(data), 'hex') - case 'murmur3-32': - return fromNumberTo32BitBuf(mur.x86.hash32(data)) - - default: - throw new TypeError(`${algorithm} is not a supported algorithm`) - } -} - -module.exports = { - sha1: sha('sha1'), - sha2256: sha('sha2-256'), - sha2512: sha('sha2-512'), - dblSha2256: sha('dbl-sha2-256'), - sha3224: hash('sha3-224'), - sha3256: hash('sha3-256'), - sha3384: hash('sha3-384'), - sha3512: hash('sha3-512'), - shake128: hash('shake-128'), - shake256: hash('shake-256'), - keccak224: hash('keccak-224'), - keccak256: hash('keccak-256'), - keccak384: hash('keccak-384'), - keccak512: hash('keccak-512'), - murmur3128: hash('murmur3-128'), - murmur332: hash('murmur3-32'), - addBlake: require('./blake') -} - -},{"./blake":554,"./sha":557,"./utils":558,"buffer":217,"js-sha3":553,"murmurhash3js-revisited":1352}],556:[function(require,module,exports){ -'use strict' - -const { Buffer } = require('buffer') -const errcode = require('err-code') -const multihash = require('multihashes') -const crypto = require('./crypto') - -/** - * Hash the given `buf` using the algorithm specified by `alg`. - * @param {Buffer} buf - The value to hash. - * @param {number|string} alg - The algorithm to use eg 'sha1' - * @param {number} [length] - Optionally trim the result to this length. - * @returns {Promise} - */ -async function Multihashing (buf, alg, length) { - const digest = await Multihashing.digest(buf, alg, length) - return multihash.encode(digest, alg, length) -} - -/** - * The `buffer` module for easy use in the browser. - * - * @type {Buffer} - */ -Multihashing.Buffer = Buffer // for browser things - -/** - * Expose multihash itself, to avoid silly double requires. - */ -Multihashing.multihash = multihash - -/** - * @param {Buffer} buf - The value to hash. - * @param {number|string} alg - The algorithm to use eg 'sha1' - * @param {number} [length] - Optionally trim the result to this length. - * @returns {Promise} - */ -Multihashing.digest = async (buf, alg, length) => { - const hash = Multihashing.createHash(alg) - const digest = await hash(buf) - return length ? digest.slice(0, length) : digest -} - -/** - * Creates a function that hashes with the given algorithm - * - * @param {string|number} alg - The algorithm to use eg 'sha1' - * - * @returns {function} - The hash function corresponding to `alg` - */ -Multihashing.createHash = function (alg) { - if (!alg) { - throw errcode('hash algorithm must be specified', 'ERR_HASH_ALGORITHM_NOT_SPECIFIED') - } - - alg = multihash.coerceCode(alg) - if (!Multihashing.functions[alg]) { - throw errcode(`multihash function '${alg}' not yet supported`, 'ERR_HASH_ALGORITHM_NOT_SUPPORTED') - } - - return Multihashing.functions[alg] -} - -/** - * Mapping of multihash codes to their hashing functions. - * @type {Object} - */ -Multihashing.functions = { - // sha1 - 0x11: crypto.sha1, - // sha2-256 - 0x12: crypto.sha2256, - // sha2-512 - 0x13: crypto.sha2512, - // sha3-512 - 0x14: crypto.sha3512, - // sha3-384 - 0x15: crypto.sha3384, - // sha3-256 - 0x16: crypto.sha3256, - // sha3-224 - 0x17: crypto.sha3224, - // shake-128 - 0x18: crypto.shake128, - // shake-256 - 0x19: crypto.shake256, - // keccak-224 - 0x1A: crypto.keccak224, - // keccak-256 - 0x1B: crypto.keccak256, - // keccak-384 - 0x1C: crypto.keccak384, - // keccak-512 - 0x1D: crypto.keccak512, - // murmur3-128 - 0x22: crypto.murmur3128, - // murmur3-32 - 0x23: crypto.murmur332, - // dbl-sha2-256 - 0x56: crypto.dblSha2256 -} - -// add blake functions -crypto.addBlake(Multihashing.functions) - -Multihashing.validate = async (buf, hash) => { - const newHash = await Multihashing(buf, multihash.decode(hash).name) - - return Buffer.compare(hash, newHash) === 0 -} - -module.exports = Multihashing - -},{"./crypto":555,"buffer":217,"err-code":552,"multihashes":1331}],557:[function(require,module,exports){ -'use strict' - -const { Buffer } = require('buffer') - -const crypto = self.crypto || self.msCrypto - -module.exports = (algorithm) => { - if (typeof self === 'undefined' || (!self.crypto && !self.msCrypto)) { - throw new Error( - 'Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context' - ) - } - - return async (data) => { - switch (algorithm) { - case 'sha1': - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-1' }, data)) - case 'sha2-256': - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, data)) - case 'sha2-512': - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-512' }, data)) - case 'dbl-sha2-256': { - const d = await crypto.subtle.digest({ name: 'SHA-256' }, data) - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, d)) - } - default: - throw new Error(`${algorithm} is not a supported algorithm`) - } - } -} - -},{"buffer":217}],558:[function(require,module,exports){ -'use strict' - -const { Buffer } = require('buffer') - -const fromNumberTo32BitBuf = (number) => { - const bytes = new Array(4) - - for (let i = 0; i < 4; i++) { - bytes[i] = number & 0xff - number = number >> 8 - } - - return Buffer.from(bytes) -} - -module.exports = { - fromNumberTo32BitBuf -} - -},{"buffer":217}],559:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],560:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],561:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":563,"./_stream_writable":565,"_process":1438,"dup":90,"inherits":453}],562:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":564,"dup":91,"inherits":453}],563:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":559,"../experimentalWarning":560,"./_stream_duplex":561,"./internal/streams/async_iterator":566,"./internal/streams/buffer_list":567,"./internal/streams/destroy":568,"./internal/streams/state":571,"./internal/streams/stream":572,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],564:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":559,"./_stream_duplex":561,"dup":93,"inherits":453}],565:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":559,"./_stream_duplex":561,"./internal/streams/destroy":568,"./internal/streams/state":571,"./internal/streams/stream":572,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],566:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":569,"_process":1438,"dup":95}],567:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],568:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],569:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":559,"dup":98}],570:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":559,"./end-of-stream":569,"dup":99}],571:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":559,"dup":100}],572:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],573:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":561,"./lib/_stream_passthrough.js":562,"./lib/_stream_readable.js":563,"./lib/_stream_transform.js":564,"./lib/_stream_writable.js":565,"./lib/internal/streams/end-of-stream.js":569,"./lib/internal/streams/pipeline.js":570,"dup":102}],574:[function(require,module,exports){ -'use strict' - -const BufferList = require('bl') - -module.exports = async function * fixedSizeChunker (source, options) { - let bl = new BufferList() - let currentLength = 0 - let emitted = false - const maxChunkSize = options.maxChunkSize - - for await (const buffer of source) { - bl.append(buffer) - - currentLength += buffer.length - - while (currentLength >= maxChunkSize) { - yield bl.slice(0, maxChunkSize) - emitted = true - - // throw away consumed bytes - if (maxChunkSize === bl.length) { - bl = new BufferList() - currentLength = 0 - } else { - const newBl = new BufferList() - newBl.append(bl.shallowSlice(maxChunkSize)) - bl = newBl - - // update our offset - currentLength -= maxChunkSize - } - } - } - - if (!emitted || currentLength) { - // return any remaining bytes or an empty buffer - yield bl.slice(0, currentLength) - } -} - -},{"bl":551}],575:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') - -const chunkers = { - fixed: require('../chunker/fixed-size'), - rabin: require('../chunker/rabin') -} - -module.exports = (type, source, options) => { - const chunker = chunkers[type] - - if (!chunker) { - throw errCode(new Error(`Unknkown chunker named ${type}`), 'ERR_UNKNOWN_CHUNKER') - } - - return chunker(source, options) -} - -},{"../chunker/fixed-size":574,"../chunker/rabin":576,"err-code":552}],576:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const BufferList = require('bl') -const { create } = require('rabin-wasm') -const errcode = require('err-code') - -module.exports = async function * rabinChunker (source, options) { - const rabin = jsRabin() - - let min, max, avg - - if (options.minChunkSize && options.maxChunkSize && options.avgChunkSize) { - avg = options.avgChunkSize - min = options.minChunkSize - max = options.maxChunkSize - } else if (!options.avgChunkSize) { - throw errcode(new Error('please specify an average chunk size'), 'ERR_INVALID_AVG_CHUNK_SIZE') - } else { - avg = options.avgChunkSize - min = avg / 3 - max = avg + (avg / 2) - } - - // validate min/max/avg in the same way as go - if (min < 16) { - throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE') - } - - if (max < min) { - max = min - } - - if (avg < min) { - avg = min - } - - const sizepow = Math.floor(Math.log2(avg)) - - for await (const chunk of rabin(source, { - min: min, - max: max, - bits: sizepow, - window: options.window, - polynomial: options.polynomial - })) { - yield chunk - } -} - -const jsRabin = () => { - return async function * (source, options) { - const r = await create(options.bits, options.min, options.max, options.window) - const buffers = new BufferList() - let pending = [] - - for await (const chunk of source) { - buffers.append(chunk) - pending.push(chunk) - - const sizes = r.fingerprint(Buffer.concat(pending)) - pending = [] - - for (let i = 0; i < sizes.length; i++) { - var size = sizes[i] - var buf = buffers.slice(0, size) - buffers.consume(size) - - yield buf - } - } - - if (buffers.length) { - yield buffers.slice(0) - } - } -} - -}).call(this,require("buffer").Buffer) -},{"bl":551,"buffer":217,"err-code":552,"rabin-wasm":1550}],577:[function(require,module,exports){ -'use strict' - -const UnixFS = require('ipfs-unixfs') -const persist = require('../utils/persist') -const { - DAGNode -} = require('ipld-dag-pb') - -const dirBuilder = async (item, ipld, options) => { - const unixfs = new UnixFS('directory') - const node = DAGNode.create(unixfs.marshal(), []) - const cid = await persist(node, ipld, options) - let path = item.path - - return { - cid, - path, - unixfs, - node - } -} - -module.exports = dirBuilder - -},{"../utils/persist":590,"ipfs-unixfs":592,"ipld-dag-pb":745}],578:[function(require,module,exports){ -'use strict' - -const batch = require('async-iterator-batch') - -async function * balanced (source, reduce, options) { - yield await reduceToParents(source, reduce, options) -} - -async function reduceToParents (source, reduce, options) { - const roots = [] - - for await (const chunked of batch(source, options.maxChildrenPerNode)) { - roots.push(await reduce(chunked)) - } - - if (roots.length > 1) { - return reduceToParents(roots, reduce, options) - } - - return roots[0] -} - -module.exports = balanced - -},{"async-iterator-batch":83}],579:[function(require,module,exports){ -'use strict' - -const batch = require('async-iterator-batch') - -module.exports = async function * (source, reduce) { - const roots = [] - - for await (const chunk of batch(source, Infinity)) { - roots.push(await reduce(chunk)) - } - - yield roots[0] -} - -},{"async-iterator-batch":83}],580:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const UnixFS = require('ipfs-unixfs') -const persist = require('../../utils/persist') -const { - DAGNode, - DAGLink -} = require('ipld-dag-pb') -const all = require('async-iterator-all') - -const dagBuilders = { - flat: require('./flat'), - balanced: require('./balanced'), - trickle: require('./trickle') -} - -async function * buildFile (source, ipld, options) { - let count = -1 - let previous - - for await (const buffer of source) { - count++ - options.progress(buffer.length) - let node - let unixfs - - let opts = { - ...options - } - - if (options.rawLeaves) { - node = buffer - - opts.codec = 'raw' - opts.cidVersion = 1 - } else { - unixfs = new UnixFS(options.leafType, buffer) - node = DAGNode.create(unixfs.marshal(), []) - } - - const cid = await persist(node, ipld, opts) - - const entry = { - cid: cid, - unixfs, - node - } - - if (count === 0) { - previous = entry - continue - } else if (count === 1) { - yield previous - previous = null - } - - yield entry - } - - if (previous) { - previous.single = true - yield previous - } -} - -const reduce = (file, ipld, options) => { - return async function (leaves) { - if (leaves.length === 1 && leaves[0].single && options.reduceSingleLeafToSelf) { - const leaf = leaves[0] - - return { - cid: leaf.cid, - path: file.path, - name: (file.path || '').split('/').pop(), - unixfs: leaf.unixfs, - node: leaf.node - } - } - - // create a parent node and add all the leaves - const f = new UnixFS('file') - - const links = leaves - .filter(leaf => { - if (leaf.cid.codec === 'raw' && leaf.node.length) { - return true - } - - if (!leaf.unixfs.data && leaf.unixfs.fileSize()) { - return true - } - - return Boolean(leaf.unixfs.data.length) - }) - .map((leaf) => { - if (leaf.cid.codec === 'raw') { - // node is a leaf buffer - f.addBlockSize(leaf.node.length) - - return new DAGLink(leaf.name, leaf.node.length, leaf.cid) - } - - if (!leaf.unixfs.data) { - // node is an intermediate node - f.addBlockSize(leaf.unixfs.fileSize()) - } else { - // node is a unixfs 'file' leaf node - f.addBlockSize(leaf.unixfs.data.length) - } - - return new DAGLink(leaf.name, leaf.node.size, leaf.cid) - }) - - const node = DAGNode.create(f.marshal(), links) - const cid = await persist(node, ipld, options) - - return { - cid, - path: file.path, - unixfs: f, - node, - size: node.size - } - } -} - -const fileBuilder = async (file, source, ipld, options) => { - const dagBuilder = dagBuilders[options.strategy] - - if (!dagBuilder) { - throw errCode(new Error(`Unknown importer build strategy name: ${options.strategy}`), 'ERR_BAD_STRATEGY') - } - - const roots = await all(dagBuilder(buildFile(source, ipld, options), reduce(file, ipld, options), options.builderOptions)) - - if (roots.length > 1) { - throw errCode(new Error('expected a maximum of 1 roots and got ' + roots.length), 'ETOOMANYROOTS') - } - - return roots[0] -} - -module.exports = fileBuilder - -},{"../../utils/persist":590,"./balanced":578,"./flat":579,"./trickle":581,"async-iterator-all":82,"err-code":552,"ipfs-unixfs":592,"ipld-dag-pb":745}],581:[function(require,module,exports){ -'use strict' - -const batch = require('async-iterator-batch') - -module.exports = function * trickleReduceToRoot (source, reduce, options) { - yield trickleStream(source, reduce, options) -} - -async function trickleStream (source, reduce, options) { - let root - let iteration = 0 - let maxDepth = 1 - let subTree = root = new Root(options.layerRepeat) - - for await (const layer of batch(source, options.maxChildrenPerNode)) { - if (subTree.isFull()) { - if (subTree !== root) { - root.addChild(await subTree.reduce(reduce)) - } - - if (iteration && iteration % options.layerRepeat === 0) { - maxDepth++ - } - - subTree = new SubTree(maxDepth, options.layerRepeat, iteration) - - iteration++ - } - - subTree.append(layer) - } - - if (subTree && subTree !== root) { - root.addChild(await subTree.reduce(reduce)) - } - - return root.reduce(reduce) -} - -class SubTree { - constructor (maxDepth, layerRepeat, iteration) { - this.maxDepth = maxDepth - this.layerRepeat = layerRepeat - this.currentDepth = 1 - this.iteration = iteration - - this.root = this.node = this.parent = { - children: [], - depth: this.currentDepth, - maxDepth, - maxChildren: (this.maxDepth - this.currentDepth) * this.layerRepeat - } - } - - isFull () { - if (!this.root.data) { - return false - } - - if (this.currentDepth < this.maxDepth && this.node.maxChildren) { - // can descend - this._addNextNodeToParent(this.node) - - return false - } - - // try to find new node from node.parent - const distantRelative = this._findParent(this.node, this.currentDepth) - - if (distantRelative) { - this._addNextNodeToParent(distantRelative) - - return false - } - - return true - } - - _addNextNodeToParent (parent) { - this.parent = parent - - // find site for new node - const nextNode = { - children: [], - depth: parent.depth + 1, - parent, - maxDepth: this.maxDepth, - maxChildren: Math.floor(parent.children.length / this.layerRepeat) * this.layerRepeat - } - - parent.children.push(nextNode) - - this.currentDepth = nextNode.depth - this.node = nextNode - } - - append (layer) { - this.node.data = layer - } - - reduce (reduce) { - return this._reduce(this.root, reduce) - } - - async _reduce (node, reduce) { - let children = [] - - if (node.children.length) { - children = await Promise.all( - node.children - .filter(child => child.data) - .map(child => this._reduce(child, reduce)) - ) - } - - return reduce(node.data.concat(children)) - } - - _findParent (node, depth) { - const parent = node.parent - - if (!parent || parent.depth === 0) { - return - } - - if (parent.children.length === parent.maxChildren || !parent.maxChildren) { - // this layer is full, may be able to traverse to a different branch - return this._findParent(parent, depth) - } - - return parent - } -} - -class Root extends SubTree { - constructor (layerRepeat) { - super(0, layerRepeat) - - this.root.depth = 0 - this.currentDepth = 1 - } - - addChild (child) { - this.root.children.push(child) - } - - reduce (reduce) { - return reduce(this.root.data.concat(this.root.children)) - } -} - -},{"async-iterator-batch":83}],582:[function(require,module,exports){ -'use strict' - -const dirBuilder = require('./dir') -const fileBuilder = require('./file') -const createChunker = require('../chunker') -const validateChunks = require('./validate-chunks') - -async function * dagBuilder (source, ipld, options) { - for await (const entry of source) { - if (entry.path) { - if (entry.path.substring(0, 2) === './') { - options.wrapWithDirectory = true - } - - entry.path = entry.path - .split('/') - .filter(path => path && path !== '.') - .join('/') - } - - if (entry.content) { - let source = entry.content - - // wrap in iterator if it is array-like or not an iterator - if ((!source[Symbol.asyncIterator] && !source[Symbol.iterator]) || source.length !== undefined) { - source = { - [Symbol.iterator]: function * () { - yield entry.content - } - } - } - - const chunker = createChunker(options.chunker, validateChunks(source), options.chunkerOptions) - - // item is a file - yield fileBuilder(entry, chunker, ipld, options) - } else { - // item is a directory - yield dirBuilder(entry, ipld, options) - } - } -} - -module.exports = dagBuilder - -},{"../chunker":575,"./dir":577,"./file":580,"./validate-chunks":583}],583:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const errCode = require('err-code') - -// make sure the content only emits buffer-a-likes -async function * validateChunks (source) { - for await (const content of source) { - if (content.length === undefined) { - throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT') - } - - if (typeof content === 'string' || content instanceof String) { - yield Buffer.from(content, 'utf8') - } else if (Array.isArray(content)) { - yield Buffer.from(content) - } else { - yield content - } - } -} - -module.exports = validateChunks - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"err-code":552}],584:[function(require,module,exports){ -'use strict' - -const { - DAGLink, - DAGNode -} = require('ipld-dag-pb') -const UnixFS = require('ipfs-unixfs') -const Dir = require('./dir') -const persist = require('./utils/persist') - -class DirFlat extends Dir { - constructor (props, options) { - super(props, options) - this._children = {} - } - - put (name, value) { - this.cid = undefined - this.size = undefined - this._children[name] = value - } - - get (name) { - return this._children[name] - } - - childCount () { - return Object.keys(this._children).length - } - - directChildrenCount () { - return this.childCount() - } - - onlyChild () { - return this._children[Object.keys(this._children)[0]] - } - - * eachChildSeries () { - const keys = Object.keys(this._children) - - for (let i = 0; i < keys.length; i++) { - const key = keys[i] - - yield { - key: key, - child: this._children[key] - } - } - } - - async * flush (path, ipld) { - const children = Object.keys(this._children) - const links = [] - - for (let i = 0; i < children.length; i++) { - let child = this._children[children[i]] - - if (typeof child.flush === 'function') { - for await (const entry of child.flush(child.path, ipld)) { - child = entry - - yield child - } - } - - links.push(new DAGLink(children[i], child.node.length || child.node.size, child.cid)) - } - - const unixfs = new UnixFS('directory') - let node = DAGNode.create(unixfs.marshal(), links) - const cid = await persist(node, ipld, this.options) - - this.cid = cid - this.size = node.size - - yield { - cid, - unixfs, - path, - node - } - } -} - -module.exports = DirFlat - -},{"./dir":586,"./utils/persist":590,"ipfs-unixfs":592,"ipld-dag-pb":745}],585:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const { - DAGLink, - DAGNode -} = require('ipld-dag-pb') -const UnixFS = require('ipfs-unixfs') -const multihashing = require('multihashing-async') -const Dir = require('./dir') -const persist = require('./utils/persist') -const Bucket = require('hamt-sharding') -const extend = require('deep-extend') - -const hashFn = async function (value) { - const hash = await multihashing(Buffer.from(value, 'utf8'), 'murmur3-128') - - // Multihashing inserts preamble of 2 bytes. Remove it. - // Also, murmur3 outputs 128 bit but, accidently, IPFS Go's - // implementation only uses the first 64, so we must do the same - // for parity.. - const justHash = hash.slice(2, 10) - const length = justHash.length - const result = Buffer.alloc(length) - // TODO: invert buffer because that's how Go impl does it - for (let i = 0; i < length; i++) { - result[length - i - 1] = justHash[i] - } - - return result -} -hashFn.code = 0x22 // TODO: get this from multihashing-async? - -const defaultOptions = { - hashFn: hashFn -} - -class DirSharded extends Dir { - constructor (props, options) { - options = extend({}, defaultOptions, options) - - super(props, options) - - this._bucket = Bucket(options) - } - - async put (name, value) { - await this._bucket.put(name, value) - } - - get (name) { - return this._bucket.get(name) - } - - childCount () { - return this._bucket.leafCount() - } - - directChildrenCount () { - return this._bucket.childrenCount() - } - - onlyChild () { - return this._bucket.onlyChild() - } - - async * eachChildSeries () { - for await (const { key, value } of this._bucket.eachLeafSeries()) { - yield { - key, - child: value - } - } - } - - async * flush (path, ipld) { - for await (const entry of flush(path, this._bucket, ipld, this.options)) { - yield entry - } - } -} - -module.exports = DirSharded - -module.exports.hashFn = hashFn - -async function * flush (path, bucket, ipld, options) { - const children = bucket._children - const links = [] - - for (let i = 0; i < children.length; i++) { - const child = children.get(i) - - if (!child) { - continue - } - - const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0') - - if (Bucket.isBucket(child)) { - let shard - - for await (const subShard of await flush('', child, ipld, options)) { - shard = subShard - } - - links.push(await new DAGLink(labelPrefix, shard.node.size, shard.cid)) - } else if (typeof child.value.flush === 'function') { - const dir = child.value - let flushedDir - - for await (const entry of dir.flush(dir.path, ipld)) { - flushedDir = entry - - yield flushedDir - } - - const label = labelPrefix + child.key - links.push(new DAGLink(label, flushedDir.node.size, flushedDir.cid)) - } else { - const value = child.value - - if (!value.node) { - if (value.cid) { - value.node = await ipld.get(value.cid) - } else { - continue - } - } - - const label = labelPrefix + child.key - const size = value.node.length || value.node.size || value.node.Size - - links.push(await new DAGLink(label, size, value.cid)) - } - } - - // go-ipfs uses little endian, that's why we have to - // reverse the bit field before storing it - const data = Buffer.from(children.bitField().reverse()) - const dir = new UnixFS('hamt-sharded-directory', data) - dir.fanout = bucket.tableSize() - dir.hashType = options.hashFn.code - - const node = DAGNode.create(dir.marshal(), links) - const cid = await persist(node, ipld, options) - - yield { - cid, - node, - unixfs: dir, - path - } -} - -}).call(this,require("buffer").Buffer) -},{"./dir":586,"./utils/persist":590,"buffer":217,"deep-extend":256,"hamt-sharding":397,"ipfs-unixfs":592,"ipld-dag-pb":745,"multihashing-async":556}],586:[function(require,module,exports){ -'use strict' - -module.exports = class Dir { - constructor (props, options) { - this.options = options || {} - Object.assign(this, props) - } -} - -},{}],587:[function(require,module,exports){ -'use strict' - -const DirSharded = require('./dir-sharded') - -module.exports = async function flatToShard (child, dir, threshold, options) { - let newDir = dir - - if (dir.flat && dir.directChildrenCount() >= threshold) { - newDir = await convertToShard(dir, options) - } - - const parent = newDir.parent - - if (parent) { - if (newDir !== dir) { - if (child) { - child.parent = newDir - } - - await parent.put(newDir.parentKey, newDir) - } - - if (parent) { - return flatToShard(newDir, parent, threshold, options) - } - } - - return newDir -} - -async function convertToShard (oldDir, options) { - const newDir = new DirSharded({ - root: oldDir.root, - dir: true, - parent: oldDir.parent, - parentKey: oldDir.parentKey, - path: oldDir.path, - dirty: oldDir.dirty, - flat: false - }, options) - - for await (const { key, child } of oldDir.eachChildSeries()) { - await newDir.put(key, child) - } - - return newDir -} - -},{"./dir-sharded":585}],588:[function(require,module,exports){ -'use strict' - -const { superstruct } = require('superstruct') -const dagBuilder = require('./dag-builder') -const treeBuilder = require('./tree-builder') -const mh = require('multihashes') - -const struct = superstruct({ - types: { - codec: v => ['dag-pb', 'dag-cbor', 'raw'].includes(v), - hashAlg: v => Object.keys(mh.names).includes(v), - leafType: v => ['file', 'raw'].includes(v) - } -}) - -const ChunkerOptions = struct({ - minChunkSize: 'number?', - maxChunkSize: 'number?', - avgChunkSize: 'number?', - window: 'number?', - polynomial: 'number?' -}, { - maxChunkSize: 262144, - avgChunkSize: 262144, - window: 16, - polynomial: 17437180132763653 // https://github.com/ipfs/go-ipfs-chunker/blob/d0125832512163708c0804a3cda060e21acddae4/rabin.go#L11 -}) - -const BuilderOptions = struct({ - maxChildrenPerNode: 'number?', - layerRepeat: 'number?' -}, { - maxChildrenPerNode: 174, - layerRepeat: 4 -}) - -const Options = struct({ - chunker: struct.enum(['fixed', 'rabin']), - rawLeaves: 'boolean?', - hashOnly: 'boolean?', - strategy: struct.enum(['balanced', 'flat', 'trickle']), - reduceSingleLeafToSelf: 'boolean?', - codec: 'codec?', - format: 'codec?', - hashAlg: 'hashAlg?', - leafType: 'leafType?', - cidVersion: 'number?', - progress: 'function?', - wrapWithDirectory: 'boolean?', - shardSplitThreshold: 'number?', - onlyHash: 'boolean?', - chunkerOptions: ChunkerOptions, - builderOptions: BuilderOptions, - - wrap: 'boolean?', - pin: 'boolean?', - recursive: 'boolean?', - ignore: 'array?', - hidden: 'boolean?', - preload: 'boolean?' -}, { - chunker: 'fixed', - strategy: 'balanced', - rawLeaves: false, - reduceSingleLeafToSelf: true, - codec: 'dag-pb', - hashAlg: 'sha2-256', - leafType: 'file', - cidVersion: 0, - progress: () => () => {}, - shardSplitThreshold: 1000 -}) - -module.exports = async function * (source, ipld, options = {}) { - const opts = Options(options) - - if (options.cidVersion > 0 && options.rawLeaves === undefined) { - // if the cid version is 1 or above, use raw leaves as this is - // what go does. - opts.rawLeaves = true - } - - if (options.hashAlg !== undefined && options.rawLeaves === undefined) { - // if a non-default hash alg has been specified, use raw leaves as this is - // what go does. - opts.rawLeaves = true - } - - // go-ifps trickle dag defaults to unixfs raw leaves, balanced dag defaults to file leaves - if (options.strategy === 'trickle') { - opts.leafType = 'raw' - opts.reduceSingleLeafToSelf = false - } - - if (options.format) { - options.codec = options.format - } - - for await (const entry of treeBuilder(dagBuilder(source, ipld, opts), ipld, opts)) { - yield { - cid: entry.cid, - path: entry.path, - unixfs: entry.unixfs, - size: entry.size - } - } -} - -},{"./dag-builder":582,"./tree-builder":589,"multihashes":1331,"superstruct":1743}],589:[function(require,module,exports){ -'use strict' - -const DirFlat = require('./dir-flat') -const flatToShard = require('./flat-to-shard') -const Dir = require('./dir') -const toPathComponents = require('./utils/to-path-components') -const errCode = require('err-code') -const first = require('async-iterator-first') - -async function addToTree (elem, tree, options) { - const pathElems = toPathComponents(elem.path || '') - const lastIndex = pathElems.length - 1 - let parent = tree - let currentPath = '' - - for (let i = 0; i < pathElems.length; i++) { - const pathElem = pathElems[i] - - currentPath += `${currentPath ? '/' : ''}${pathElem}` - - const last = (i === lastIndex) - parent.dirty = true - parent.cid = null - parent.size = null - - if (last) { - await parent.put(pathElem, elem) - tree = await flatToShard(null, parent, options.shardSplitThreshold, options) - } else { - let dir = await parent.get(pathElem) - - if (!dir || !(dir instanceof Dir)) { - dir = new DirFlat({ - dir: true, - parent: parent, - parentKey: pathElem, - path: currentPath, - dirty: true, - flat: true - }, options) - } - - await parent.put(pathElem, dir) - - parent = dir - } - } - - return tree -} - -async function * treeBuilder (source, ipld, options) { - let tree = new DirFlat({ - root: true, - dir: true, - path: '', - dirty: true, - flat: true - }, options) - - for await (const entry of source) { - tree = await addToTree(entry, tree, options) - - yield entry - } - - if (tree) { - if (!options.wrapWithDirectory) { - if (tree.childCount() > 1) { - throw errCode(new Error('detected more than one root'), 'ERR_MORE_THAN_ONE_ROOT') - } - - const unwrapped = await first(tree.eachChildSeries()) - - if (!unwrapped) { - return - } - - tree = unwrapped.child - } - - if (!tree.dir) { - return - } - - for await (const entry of tree.flush(tree.path, ipld)) { - yield entry - } - } -} - -module.exports = treeBuilder - -},{"./dir":586,"./dir-flat":584,"./flat-to-shard":587,"./utils/to-path-components":591,"async-iterator-first":84,"err-code":552}],590:[function(require,module,exports){ -'use strict' - -const mh = require('multihashes') -const mc = require('multicodec') - -const persist = (node, ipld, options) => { - if (!options.codec && node.length) { - options.cidVersion = 1 - options.codec = 'raw' - } - - if (isNaN(options.hashAlg)) { - options.hashAlg = mh.names[options.hashAlg] - } - - if (options.hashAlg !== mh.names['sha2-256']) { - options.cidVersion = 1 - } - - if (options.format) { - options.codec = options.format - } - - const format = mc[options.codec.toUpperCase().replace(/-/g, '_')] - - return ipld.put(node, format, options) -} - -module.exports = persist - -},{"multicodec":1325,"multihashes":1331}],591:[function(require,module,exports){ -arguments[4][515][0].apply(exports,arguments) -},{"dup":515}],592:[function(require,module,exports){ -'use strict' - -const protons = require('protons') -const pb = protons(require('./unixfs.proto')) -// encode/decode -const unixfsData = pb.Data -// const unixfsMetadata = pb.MetaData // encode/decode - -const types = [ - 'raw', - 'directory', - 'file', - 'metadata', - 'symlink', - 'hamt-sharded-directory' -] - -const dirTypes = [ - 'directory', - 'hamt-sharded-directory' -] - -function Data (type, data) { - if (!(this instanceof Data)) { - return new Data(type, data) - } - if (types.indexOf(type) === -1) { - throw new Error('Type: ' + type + ' is not valid') - } - - this.type = type - this.data = data - this.blockSizes = [] - - this.addBlockSize = (size) => { - this.blockSizes.push(size) - } - - this.removeBlockSize = (index) => { - this.blockSizes.splice(index, 1) - } - - // data.length + blockSizes - this.fileSize = () => { - if (dirTypes.indexOf(this.type) >= 0) { - // dirs don't have file size - return undefined - } - - let sum = 0 - this.blockSizes.forEach((size) => { - sum += size - }) - if (data) { - sum += data.length - } - return sum - } - - // encode to protobuf - this.marshal = () => { - let type - - switch (this.type) { - case 'raw': type = unixfsData.DataType.Raw; break - case 'directory': type = unixfsData.DataType.Directory; break - case 'file': type = unixfsData.DataType.File; break - case 'metadata': type = unixfsData.DataType.Metadata; break - case 'symlink': type = unixfsData.DataType.Symlink; break - case 'hamt-sharded-directory': type = unixfsData.DataType.HAMTShard; break - default: - throw new Error(`Unkown type: "${this.type}"`) - } - let fileSize = this.fileSize() - - let data = this.data - - if (!this.data || !this.data.length) { - data = undefined - } - - let blockSizes = this.blockSizes - - if (!this.blockSizes || !this.blockSizes.length) { - blockSizes = undefined - } - - return unixfsData.encode({ - Type: type, - Data: data, - filesize: fileSize, - blocksizes: blockSizes, - hashType: this.hashType, - fanout: this.fanout - }) - } -} - -// decode from protobuf https://github.com/ipfs/go-ipfs/blob/master/unixfs/format.go#L24 -Data.unmarshal = (marsheled) => { - const decoded = unixfsData.decode(marsheled) - if (!decoded.Data) { - decoded.Data = undefined - } - const obj = new Data(types[decoded.Type], decoded.Data) - obj.blockSizes = decoded.blocksizes - return obj -} - -exports = module.exports = Data - -},{"./unixfs.proto":593,"protons":1454}],593:[function(require,module,exports){ -'use strict' - -module.exports = `message Data { - enum DataType { - Raw = 0; - Directory = 1; - File = 2; - Metadata = 3; - Symlink = 4; - HAMTShard = 5; - } - - required DataType Type = 1; - optional bytes Data = 2; - optional uint64 filesize = 3; - repeated uint64 blocksizes = 4; - - optional uint64 hashType = 5; - optional uint64 fanout = 6; -} - -message Metadata { - optional string MimeType = 1; -}` - -},{}],594:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],595:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],596:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":598,"./_stream_writable":600,"_process":1438,"dup":90,"inherits":453}],597:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":599,"dup":91,"inherits":453}],598:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":594,"../experimentalWarning":595,"./_stream_duplex":596,"./internal/streams/async_iterator":601,"./internal/streams/buffer_list":602,"./internal/streams/destroy":603,"./internal/streams/state":606,"./internal/streams/stream":607,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],599:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":594,"./_stream_duplex":596,"dup":93,"inherits":453}],600:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":594,"./_stream_duplex":596,"./internal/streams/destroy":603,"./internal/streams/state":606,"./internal/streams/stream":607,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],601:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":604,"_process":1438,"dup":95}],602:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],603:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],604:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":594,"dup":98}],605:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":594,"./end-of-stream":604,"dup":99}],606:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":594,"dup":100}],607:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],608:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":596,"./lib/_stream_passthrough.js":597,"./lib/_stream_readable.js":598,"./lib/_stream_transform.js":599,"./lib/_stream_writable.js":600,"./lib/internal/streams/end-of-stream.js":604,"./lib/internal/streams/pipeline.js":605,"dup":102}],609:[function(require,module,exports){ -'use strict' - -const errCode = require('err-code') -const { Buffer } = require('buffer') -const pullStreamToIterable = require('pull-stream-to-async-iterator') -const { isSource } = require('is-pull-stream') -const globalThis = require('../globalthis') -const { Readable } = require('stream') -const Readable3 = require('readable-stream') - -/* - * Transform one of: - * - * ``` - * Bytes (Buffer|ArrayBuffer|TypedArray) [single file] - * Bloby (Blob|File) [single file] - * String [single file] - * { path, content: Bytes } [single file] - * { path, content: Bloby } [single file] - * { path, content: String } [single file] - * { path, content: Iterable } [single file] - * { path, content: Iterable } [single file] - * { path, content: AsyncIterable } [single file] - * { path, content: PullStream } [single file] - * { path, content: Readable } [single file] - * Iterable [single file] - * Iterable [single file] - * Iterable [multiple files] - * Iterable [multiple files] - * Iterable<{ path, content: Bytes }> [multiple files] - * Iterable<{ path, content: Bloby }> [multiple files] - * Iterable<{ path, content: String }> [multiple files] - * Iterable<{ path, content: Iterable }> [multiple files] - * Iterable<{ path, content: Iterable }> [multiple files] - * Iterable<{ path, content: AsyncIterable }> [multiple files] - * Iterable<{ path, content: PullStream }> [multiple files] - * Iterable<{ path, content: Readable }> [multiple files] - * AsyncIterable [single file] - * AsyncIterable [multiple files] - * AsyncIterable [multiple files] - * AsyncIterable<{ path, content: Bytes }> [multiple files] - * AsyncIterable<{ path, content: Bloby }> [multiple files] - * AsyncIterable<{ path, content: String }> [multiple files] - * AsyncIterable<{ path, content: Iterable }> [multiple files] - * AsyncIterable<{ path, content: Iterable }> [multiple files] - * AsyncIterable<{ path, content: AsyncIterable }> [multiple files] - * AsyncIterable<{ path, content: PullStream }> [multiple files] - * AsyncIterable<{ path, content: Readable }> [multiple files] - * PullStream [single file] - * PullStream [multiple files] - * PullStream [multiple files] - * PullStream<{ path, content: Bytes }> [multiple files] - * PullStream<{ path, content: Bloby }> [multiple files] - * PullStream<{ path, content: String }> [multiple files] - * PullStream<{ path, content: Iterable }> [multiple files] - * PullStream<{ path, content: Iterable }> [multiple files] - * PullStream<{ path, content: AsyncIterable }> [multiple files] - * PullStream<{ path, content: PullStream }> [multiple files] - * PullStream<{ path, content: Readable }> [multiple files] - * Readable [single file] - * Readable [multiple files] - * Readable [multiple files] - * Readable<{ path, content: Bytes }> [multiple files] - * Readable<{ path, content: Bloby }> [multiple files] - * Readable<{ path, content: String }> [multiple files] - * Readable<{ path, content: Iterable }> [multiple files] - * Readable<{ path, content: Iterable }> [multiple files] - * Readable<{ path, content: AsyncIterable }> [multiple files] - * Readable<{ path, content: PullStream }> [multiple files] - * Readable<{ path, content: Readable }> [multiple files] - * ``` - * Into: - * - * ``` - * AsyncIterable<{ path, content: AsyncIterable }> - * ``` - * - * @param input Object - * @return AsyncInterable<{ path, content: AsyncIterable }> - */ -module.exports = function normaliseInput (input) { - // must give us something - if (input === null || input === undefined) { - throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT')) - } - - // String - if (typeof input === 'string' || input instanceof String) { - return (async function * () { // eslint-disable-line require-await - yield toFileObject(input) - })() - } - - // Buffer|ArrayBuffer|TypedArray - // Blob|File - if (isBytes(input) || isBloby(input)) { - return (async function * () { // eslint-disable-line require-await - yield toFileObject(input) - })() - } - - // Readable - if (isOldReadable(input)) { - input = upgradeOldStream(input) - } - - // Iterable - if (input[Symbol.iterator]) { - return (async function * () { // eslint-disable-line require-await - const iterator = input[Symbol.iterator]() - const first = iterator.next() - if (first.done) return iterator - - // Iterable - // Iterable - if (Number.isInteger(first.value) || isBytes(first.value)) { - yield toFileObject((function * () { - yield first.value - yield * iterator - })()) - return - } - - // Iterable - // Iterable - // Iterable<{ path, content }> - if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { - yield toFileObject(first.value) - for (const obj of iterator) { - yield toFileObject(obj) - } - return - } - - throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') - })() - } - - // AsyncIterable - if (input[Symbol.asyncIterator]) { - return (async function * () { - const iterator = input[Symbol.asyncIterator]() - const first = await iterator.next() - if (first.done) return iterator - - // AsyncIterable - if (isBytes(first.value)) { - yield toFileObject((async function * () { // eslint-disable-line require-await - yield first.value - yield * iterator - })()) - return - } - - // AsyncIterable - // AsyncIterable - // AsyncIterable<{ path, content }> - if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { - yield toFileObject(first.value) - for await (const obj of iterator) { - yield toFileObject(obj) - } - return - } - - throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') - })() - } - - // { path, content: ? } - // Note: Detected _after_ AsyncIterable because Node.js streams have a - // `path` property that passes this check. - if (isFileObject(input)) { - return (async function * () { // eslint-disable-line require-await - yield toFileObject(input) - })() - } - - // PullStream - if (isSource(input)) { - return (async function * () { - const iterator = pullStreamToIterable(input)[Symbol.asyncIterator]() - const first = await iterator.next() - if (first.done) return iterator - - // PullStream - if (isBytes(first.value)) { - yield toFileObject((async function * () { // eslint-disable-line require-await - yield first.value - yield * iterator - })()) - return - } - - // PullStream - // PullStream - // PullStream<{ path, content }> - if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') { - yield toFileObject(first.value) - for await (const obj of iterator) { - yield toFileObject(obj) - } - return - } - - throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') - })() - } - - throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') -} - -function toFileObject (input) { - const obj = { path: input.path || '' } - - if (input.content) { - obj.content = toAsyncIterable(input.content) - } else if (!input.path) { // Not already a file object with path or content prop - obj.content = toAsyncIterable(input) - } - - return obj -} - -function toAsyncIterable (input) { - // Bytes | String - if (isBytes(input) || typeof input === 'string') { - return (async function * () { // eslint-disable-line require-await - yield toBuffer(input) - })() - } - - // Bloby - if (isBloby(input)) { - return blobToAsyncGenerator(input) - } - - // Readable - if (isOldReadable(input)) { - input = upgradeOldStream(input) - } - - // Iterator - if (input[Symbol.iterator]) { - return (async function * () { // eslint-disable-line require-await - const iterator = input[Symbol.iterator]() - const first = iterator.next() - if (first.done) return iterator - - // Iterable - if (Number.isInteger(first.value)) { - yield toBuffer(Array.from((function * () { - yield first.value - yield * iterator - })())) - return - } - - // Iterable - if (isBytes(first.value)) { - yield toBuffer(first.value) - for (const chunk of iterator) { - yield toBuffer(chunk) - } - return - } - - throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT') - })() - } - - // AsyncIterable - if (input[Symbol.asyncIterator]) { - return (async function * () { - for await (const chunk of input) { - yield toBuffer(chunk) - } - })() - } - - // PullStream - if (isSource(input)) { - return pullStreamToIterable(input) - } - - throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT')) -} - -function isOldReadable (obj) { - if (obj[Symbol.iterator] || obj[Symbol.asyncIterator]) { - return false - } - - return Boolean(obj.readable) -} - -function toBuffer (chunk) { - return isBytes(chunk) ? chunk : Buffer.from(chunk) -} - -function isBytes (obj) { - return Buffer.isBuffer(obj) || ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer -} - -function isBloby (obj) { - return typeof globalThis.Blob !== 'undefined' && obj instanceof globalThis.Blob -} - -// An object with a path or content property -function isFileObject (obj) { - return typeof obj === 'object' && (obj.path || obj.content) -} - -function upgradeOldStream (stream) { - if (stream[Symbol.asyncIterator] || stream[Symbol.iterator]) { - return stream - } - - // in the browser the stream.Readable is not an async iterator but readble-stream@3 is... - stream[Symbol.asyncIterator] = Readable.prototype[Symbol.asyncIterator] || Readable3.prototype[Symbol.asyncIterator] - - return stream -} - -function blobToAsyncGenerator (blob) { - if (typeof blob.stream === 'function') { - // firefox < 69 does not support blob.stream() - return streamBlob(blob) - } - - return readBlob(blob) -} - -async function * streamBlob (blob) { - const reader = blob.stream().getReader() - - while (true) { - const result = await reader.read() - - if (result.done) { - return - } - - yield result.value - } -} - -async function * readBlob (blob, options) { - options = options || {} - - const reader = new globalThis.FileReader() - const chunkSize = options.chunkSize || 1024 * 1024 - let offset = options.offset || 0 - - const getNextChunk = () => new Promise((resolve, reject) => { - reader.onloadend = e => { - const data = e.target.result - resolve(data.byteLength === 0 ? null : data) - } - reader.onerror = reject - - const end = offset + chunkSize - const slice = blob.slice(offset, end) - reader.readAsArrayBuffer(slice) - offset = end - }) - - while (true) { - const data = await getNextChunk() - - if (data == null) { - return - } - - yield Buffer.from(data) - } -} - -},{"../globalthis":610,"buffer":217,"err-code":315,"is-pull-stream":778,"pull-stream-to-async-iterator":1493,"readable-stream":608,"stream":1715}],610:[function(require,module,exports){ -/* eslint-disable no-undef */ -/* eslint-disable no-extend-native */ -/* eslint-disable strict */ - -// polyfill for globalThis -// https://v8.dev/features/globalthis -// https://mathiasbynens.be/notes/globalthis -(function () { - if (typeof globalThis === 'object') return - Object.defineProperty(Object.prototype, '__magic__', { - get: function () { - return this - }, - configurable: true - }) - __magic__.globalThis = __magic__ - delete Object.prototype.__magic__ -}()) - -module.exports = globalThis - -},{}],611:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":612,"_process":1438,"dup":247}],612:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":613}],613:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],614:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],615:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],616:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":618,"./_stream_writable":620,"_process":1438,"dup":90,"inherits":453}],617:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":619,"dup":91,"inherits":453}],618:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":614,"../experimentalWarning":615,"./_stream_duplex":616,"./internal/streams/async_iterator":621,"./internal/streams/buffer_list":622,"./internal/streams/destroy":623,"./internal/streams/state":626,"./internal/streams/stream":627,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],619:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":614,"./_stream_duplex":616,"dup":93,"inherits":453}],620:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":614,"./_stream_duplex":616,"./internal/streams/destroy":623,"./internal/streams/state":626,"./internal/streams/stream":627,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],621:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":624,"_process":1438,"dup":95}],622:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],623:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],624:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":614,"dup":98}],625:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":614,"./end-of-stream":624,"dup":99}],626:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":614,"dup":100}],627:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],628:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":616,"./lib/_stream_passthrough.js":617,"./lib/_stream_readable.js":618,"./lib/_stream_transform.js":619,"./lib/_stream_writable.js":620,"./lib/internal/streams/end-of-stream.js":624,"./lib/internal/streams/pipeline.js":625,"dup":102}],629:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - "ipfs", - "/var/www/html/ethoFSV2" - ] - ], - "_from": "ipfs@latest", - "_hasShrinkwrap": false, - "_id": "ipfs@0.38.0", - "_inCache": true, - "_installable": true, - "_location": "/ipfs", - "_nodeVersion": "10.16.2", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/ipfs_0.38.0_1569859877853_0.44313385297986096" - }, - "_npmUser": { - "email": "alex@achingbrain.net", - "name": "achingbrain" - }, - "_npmVersion": "6.11.3", - "_phantomChildren": { - "end-of-stream": "1.4.4", - "fs-constants": "1.0.0", - "inherits": "2.0.4", - "string_decoder": "1.3.0", - "util-deprecate": "1.0.2" - }, - "_requested": { - "name": "ipfs", - "raw": "ipfs", - "rawSpec": "", - "scope": null, - "spec": "latest", - "type": "tag" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/ipfs/-/ipfs-0.38.0.tgz", - "_shasum": "03f79912ce4b5ebeb081b26e92410c8f6751903c", - "_shrinkwrap": null, - "_spec": "ipfs", - "_where": "/var/www/html/ethoFSV2", - "bin": { - "jsipfs": "src/cli/bin.js" - }, - "browser": { - "./src/core/components/init-assets.js": false, - "./src/core/runtime/add-from-fs-nodejs.js": "./src/core/runtime/add-from-fs-browser.js", - "./src/core/runtime/config-nodejs.js": "./src/core/runtime/config-browser.js", - "./src/core/runtime/dns-nodejs.js": "./src/core/runtime/dns-browser.js", - "./src/core/runtime/fetch-nodejs.js": "./src/core/runtime/fetch-browser.js", - "./src/core/runtime/ipld-nodejs.js": "./src/core/runtime/ipld-browser.js", - "./src/core/runtime/libp2p-nodejs.js": "./src/core/runtime/libp2p-browser.js", - "./src/core/runtime/libp2p-pubsub-routers-nodejs.js": "./src/core/runtime/libp2p-pubsub-routers-browser.js", - "./src/core/runtime/preload-nodejs.js": "./src/core/runtime/preload-browser.js", - "./src/core/runtime/repo-nodejs.js": "./src/core/runtime/repo-browser.js", - "./test/utils/create-repo-nodejs.js": "./test/utils/create-repo-browser.js", - "stream": "readable-stream" - }, - "browser-all-ipld-formats": { - "./src/core/runtime/ipld-browser.js": "./src/core/runtime/ipld-browser-all.js" - }, - "bugs": { - "url": "https://github.com/ipfs/js-ipfs/issues" - }, - "contributors": [ - { - "name": "Maciej Krüger", - "email": "mkg20001@gmail.com" - }, - { - "name": "0xflotus", - "email": "0xflotus@gmail.com" - }, - { - "name": "Alan Shaw", - "email": "alan.shaw@protocol.ai" - }, - { - "name": "Alan Shaw", - "email": "alan@tableflip.io" - }, - { - "name": "Alex North", - "email": "alex@alexnorth.me" - }, - { - "name": "Andrew Nesbitt", - "email": "andrewnez@gmail.com" - }, - { - "name": "Andrew de Andrade", - "email": "andrew@deandrade.com.br" - }, - { - "name": "André Cruz", - "email": "andremiguelcruz@msn.com" - }, - { - "name": "Arkadiy Kukarkin", - "email": "parkan@users.noreply.github.com" - }, - { - "name": "Arpit Agarwal", - "email": "93arpit@gmail.com" - }, - { - "name": "Arpit Agarwal", - "email": "atvanguard@users.noreply.github.com" - }, - { - "name": "Bernard Mordan", - "email": "bernard@tableflip.io" - }, - { - "name": "Brian Vander Schaaf", - "email": "bvs330@gmail.com" - }, - { - "name": "Bruno Zell", - "email": "bruno.zzell@gmail.com" - }, - { - "name": "CHEVALAY JOSSELIN", - "email": "josselin54.chevalay@gmail.com" - }, - { - "name": "Caio Gondim", - "email": "me@caiogondim.com" - }, - { - "name": "Chance Hudson", - "email": "jchancehud@gmail.com" - }, - { - "name": "Chirag Shinde", - "email": "chirag-shinde@users.noreply.github.com" - }, - { - "name": "Christian Couder", - "email": "chriscool@tuxfamily.org" - }, - { - "name": "Dafeng", - "email": "dfguo.joe@gmail.com" - }, - { - "name": "Dan Ordille", - "email": "dordille@gmail.com" - }, - { - "name": "Dan Shields", - "email": "35669742+NukeManDan@users.noreply.github.com" - }, - { - "name": "Daniel J. O'Quinn", - "email": "danieljoquinn@gmail.com" - }, - { - "name": "Daniela Borges Matos de Carvalho", - "email": "alunassertiva@gmail.com" - }, - { - "name": "David Dias", - "email": "daviddias.p@gmail.com" - }, - { - "name": "David Gilbertson", - "email": "gilbertson.david@gmail.com" - }, - { - "name": "David da Silva", - "email": "dasilvacontin@gmail.com" - }, - { - "name": "Diogo Silva", - "email": "fsdiogo@gmail.com" - }, - { - "name": "Dmitriy Ryajov", - "email": "dryajov@gmail.com" - }, - { - "name": "Dominic Della Valle", - "email": "ddvpublic@Gmail.com" - }, - { - "name": "Dzmitry Bachko", - "email": "dbachko@gmail.com" - }, - { - "name": "Enrico Marino", - "email": "enrico.marino@email.com" - }, - { - "name": "Faheel Ahmad", - "email": "faheel@live.in" - }, - { - "name": "Felix Yan", - "email": "felixonmars@archlinux.org" - }, - { - "name": "Francisco Baio Dias", - "email": "xicombd@gmail.com" - }, - { - "name": "Francisco Baio Dias", - "email": "francisco@typeform.com" - }, - { - "name": "Friedel Ziegelmayer", - "email": "dignifiedquire@gmail.com" - }, - { - "name": "Gar", - "email": "gar+gh@danger.computer" - }, - { - "name": "Georgios Rassias", - "email": "georassias@gmail.com" - }, - { - "name": "Gorka Ludlow", - "email": "gorka@aquigorka.com" - }, - { - "name": "Grant Herman", - "email": "grantlouisherman041@gmail.com" - }, - { - "name": "Greenkeeper", - "email": "support@greenkeeper.io" - }, - { - "name": "Haad", - "email": "haadcode@users.noreply.github.com" - }, - { - "name": "Haoliang Yu", - "email": "haoliangyu@users.noreply.github.com" - }, - { - "name": "Harsh Vakharia", - "email": "harshjv@users.noreply.github.com" - }, - { - "name": "Henrique Dias", - "email": "hacdias@gmail.com" - }, - { - "name": "Henry Rodrick", - "email": "moshisushi@gmail.com" - }, - { - "name": "Heo Sangmin", - "email": "heo@mapiacompany.com" - }, - { - "name": "Hugo Dias", - "email": "hugomrdias@gmail.com" - }, - { - "name": "Hugo Dias", - "email": "mail@hugodias.me" - }, - { - "name": "Irakli Gozalishvili", - "email": "contact@gozala.io" - }, - { - "name": "Jacob Heun", - "email": "jacobheun@gmail.com" - }, - { - "name": "Jacob Heun", - "email": "jake@andyet.net" - }, - { - "name": "Jade Meskill", - "email": "jade.meskill@gmail.com" - }, - { - "name": "Johannes Wikner", - "email": "johannes.wikner@gmail.com" - }, - { - "name": "Jon Schlinkert", - "email": "dev@sellside.com" - }, - { - "name": "Jonathan", - "email": "jkrone@vt.edu" - }, - { - "name": "Jonybang", - "email": "Jonybange@gmail.com" - }, - { - "name": "João Antunes", - "email": "j.goncalo.antunes@gmail.com" - }, - { - "name": "João Santos", - "email": "joaosantos15@users.noreply.github.com" - }, - { - "name": "Kevin Wang", - "email": "kevin@fossa.io" - }, - { - "name": "Lars Gierth", - "email": "larsg@systemli.org" - }, - { - "name": "Lukas Drgon", - "email": "lukas.drgon@gmail.com" - }, - { - "name": "A_A", - "email": "21040751+Otto-AA@users.noreply.github.com" - }, - { - "name": "Marcin Rataj", - "email": "lidel@lidel.org" - }, - { - "name": "Marius Darila", - "email": "marius.darila@gmail.com" - }, - { - "name": "Mat Kelly", - "email": "machawk1@gmail.com" - }, - { - "name": "Michelle Lee", - "email": "michelle@protocol.ai" - }, - { - "name": "Mikeal Rogers", - "email": "mikeal.rogers@gmail.com" - }, - { - "name": "Mithgol", - "email": "getgit@mithgol.ru" - }, - { - "name": "Molly", - "email": "momack2@users.noreply.github.com" - }, - { - "name": "Mounish Sai", - "email": "pvsmounish@gmail.com" - }, - { - "name": "My9Bot", - "email": "34904312+My9Bot@users.noreply.github.com" - }, - { - "name": "Nick Poulden", - "email": "nick@poulden.com" - }, - { - "name": "Nitin Patel", - "email": "31539366+niinpatel@users.noreply.github.com" - }, - { - "name": "Nuno Nogueira", - "email": "nunofmn@gmail.com" - }, - { - "name": "Oli Evans", - "email": "oli@tableflip.io" - }, - { - "name": "Oskar Nyberg", - "email": "oskar@oskarnyberg.com" - }, - { - "name": "Pascal Precht", - "email": "pascal.precht@googlemail.com" - }, - { - "name": "Pau Ramon Revilla", - "email": "masylum@gmail.com" - }, - { - "name": "Paulo Rodrigues", - "email": "me@paulogr.com" - }, - { - "name": "Pedro Teixeira", - "email": "i@pgte.me" - }, - { - "name": "Portia Burton", - "email": "plburton@gmail.com" - }, - { - "name": "Prabhakar Poudel", - "email": "yuvrajzohan@gmail.com" - }, - { - "name": "Qmstream", - "email": "51881352+Qmstream@users.noreply.github.com" - }, - { - "name": "Raoul Millais", - "email": "raoul@raoulmillais.com" - }, - { - "name": "RasmusErik Voel Jensen", - "email": "github@solsort.com" - }, - { - "name": "Richard Littauer", - "email": "richard.littauer@gmail.com" - }, - { - "name": "Richard Schneider", - "email": "makaretu@gmail.com" - }, - { - "name": "Rob Brackett", - "email": "rob@robbrackett.com" - }, - { - "name": "Rod Keys", - "email": "rod@zokos.com" - }, - { - "name": "Sangwon Hong", - "email": "qpakzk@gmail.com" - }, - { - "name": "Sid Harder", - "email": "sideharder@gmail.com" - }, - { - "name": "SidHarder", - "email": "softwarenavigator@gmail.com" - }, - { - "name": "Stephen Whitmore", - "email": "stephen.whitmore@gmail.com" - }, - { - "name": "Stephen Whitmore", - "email": "noffle@users.noreply.github.com" - }, - { - "name": "Steven Allen", - "email": "steven@stebalien.com" - }, - { - "name": "Terence Pae", - "email": "terencepae@gmail.com" - }, - { - "name": "Teri Chadbourne", - "email": "terichadbourne@users.noreply.github.com" - }, - { - "name": "Uroš Jurglič", - "email": "jurglic@gmail.com" - }, - { - "name": "Vasco Santos", - "email": "vasco.santos@moxy.studio" - }, - { - "name": "Vasco Santos", - "email": "vasco.santos@ua.pt" - }, - { - "name": "Volker Mische", - "email": "volker.mische@gmail.com" - }, - { - "name": "Xiao Liang", - "email": "yxliang01@users.noreply.github.com" - }, - { - "name": "Yahya", - "email": "ya7yaz@gmail.com" - }, - { - "name": "Yole", - "email": "yole@ultiledger.io" - }, - { - "name": "achingbrain", - "email": "alex@achingbrain.net" - }, - { - "name": "bitspill", - "email": "bitspill+github@bitspill.net" - }, - { - "name": "datafatmunger", - "email": "jbg@peerparty.org" - }, - { - "name": "dirkmc", - "email": "dirkmdev@gmail.com" - }, - { - "name": "dirkmc", - "email": "dirk@mccormick.cx" - }, - { - "name": "greenkeeper[bot]", - "email": "23040076+greenkeeper[bot]@users.noreply.github.com" - }, - { - "name": "greenkeeper[bot]", - "email": "greenkeeper[bot]@users.noreply.github.com" - }, - { - "name": "haad", - "email": "haad@headbanggames.com" - }, - { - "name": "hapsody", - "email": "hapsody@gmail.com" - }, - { - "name": "jbenet", - "email": "juan@benet.ai" - }, - { - "name": "jonahweissman", - "email": "19804455+jonahweissman@users.noreply.github.com" - }, - { - "name": "kevingzhang", - "email": "kevin.zhang.canada@gmail.com" - }, - { - "name": "kumavis", - "email": "kumavis@users.noreply.github.com" - }, - { - "name": "nginnever", - "email": "ginneversource@gmail.com" - }, - { - "name": "npmcdn-to-unpkg-bot", - "email": "npmcdn-to-unpkg-bot@users.noreply.github.com" - }, - { - "name": "robbsolter", - "email": "35879806+robbsolter@users.noreply.github.com" - }, - { - "name": "seungwon-kang", - "email": "ksw3894@gmail.com" - }, - { - "name": "tcme", - "email": "hi@this-connect.me" - }, - { - "name": "victorbjelkholm", - "email": "victorbjelkholm@gmail.com" - }, - { - "name": "Łukasz Magiera", - "email": "magik6k@users.noreply.github.com" - }, - { - "name": "Максим Ильин", - "email": "negamaxi@gmail.com" - } - ], - "dependencies": { - "@hapi/ammo": "^3.1.1", - "@hapi/boom": "^7.4.3", - "@hapi/hapi": "^18.3.2", - "@hapi/joi": "^15.0.1", - "array-shuffle": "^1.0.1", - "async": "^2.6.1", - "async-iterator-all": "^1.0.0", - "async-iterator-to-pull-stream": "^1.3.0", - "async-iterator-to-stream": "^1.1.0", - "base32.js": "~0.1.0", - "bignumber.js": "^9.0.0", - "binary-querystring": "~0.1.2", - "bl": "^3.0.0", - "bs58": "^4.0.1", - "buffer-peek-stream": "^1.0.1", - "byteman": "^1.3.5", - "cid-tool": "~0.3.0", - "cids": "~0.7.1", - "class-is": "^1.1.0", - "datastore-core": "~0.6.0", - "datastore-pubsub": "~0.1.1", - "debug": "^4.1.0", - "dlv": "^1.1.3", - "err-code": "^2.0.0", - "explain-error": "^1.0.4", - "file-type": "^12.0.1", - "fnv1a": "^1.0.1", - "fsm-event": "^2.1.0", - "get-folder-size": "^2.0.0", - "glob": "^7.1.3", - "hapi-pino": "^6.1.0", - "hashlru": "^2.3.0", - "human-to-milliseconds": "^2.0.0", - "interface-datastore": "~0.6.0", - "ipfs-bitswap": "~0.25.1", - "ipfs-block": "~0.8.1", - "ipfs-block-service": "~0.15.2", - "ipfs-http-client": "^37.0.1", - "ipfs-http-response": "~0.3.1", - "ipfs-mfs": "^0.12.2", - "ipfs-multipart": "^0.2.0", - "ipfs-repo": "~0.26.6", - "ipfs-unixfs": "~0.1.16", - "ipfs-unixfs-exporter": "~0.37.7", - "ipfs-unixfs-importer": "~0.39.11", - "ipfs-utils": "^0.3.0", - "ipld": "~0.24.1", - "ipld-bitcoin": "~0.3.0", - "ipld-dag-cbor": "~0.15.0", - "ipld-dag-pb": "~0.17.4", - "ipld-ethereum": "^4.0.0", - "ipld-git": "~0.5.0", - "ipld-raw": "^4.0.0", - "ipld-zcash": "~0.3.0", - "ipns": "~0.5.2", - "is-domain-name": "^1.0.1", - "is-ipfs": "~0.6.1", - "is-pull-stream": "~0.0.0", - "is-stream": "^2.0.0", - "iso-url": "~0.4.6", - "it-pipe": "^1.0.1", - "it-to-stream": "^0.1.1", - "just-safe-set": "^2.1.0", - "kind-of": "^6.0.2", - "libp2p": "~0.26.1", - "libp2p-bootstrap": "~0.9.3", - "libp2p-crypto": "~0.16.0", - "libp2p-delegated-content-routing": "^0.2.4", - "libp2p-delegated-peer-routing": "^0.2.4", - "libp2p-floodsub": "^0.18.0", - "libp2p-gossipsub": "~0.0.5", - "libp2p-kad-dht": "~0.15.3", - "libp2p-keychain": "~0.4.2", - "libp2p-mdns": "~0.12.0", - "libp2p-record": "~0.6.3", - "libp2p-secio": "~0.11.0", - "libp2p-tcp": "~0.13.1", - "libp2p-webrtc-star": "~0.16.0", - "libp2p-websocket-star-multi": "~0.4.3", - "libp2p-websockets": "~0.12.3", - "lodash": "^4.17.15", - "mafmt": "^6.0.10", - "merge-options": "^1.0.1", - "mime-types": "^2.1.21", - "mkdirp": "~0.5.1", - "mortice": "^2.0.0", - "multiaddr": "^6.1.0", - "multiaddr-to-uri": "^5.0.0", - "multibase": "~0.6.0", - "multicodec": "~0.5.5", - "multihashes": "~0.4.14", - "multihashing-async": "~0.6.0", - "node-fetch": "^2.3.0", - "peer-book": "~0.9.0", - "peer-id": "~0.12.3", - "peer-info": "~0.15.0", - "progress": "^2.0.1", - "prom-client": "^11.5.3", - "prometheus-gc-stats": "~0.6.0", - "promise-nodeify": "^3.0.1", - "promisify-es6": "^1.0.3", - "protons": "^1.0.1", - "pull-abortable": "^4.1.1", - "pull-cat": "^1.1.11", - "pull-defer": "~0.2.3", - "pull-file": "^1.1.0", - "pull-mplex": "~0.1.1", - "pull-ndjson": "~0.1.1", - "pull-pushable": "^2.2.0", - "pull-sort": "^1.0.1", - "pull-stream": "^3.6.14", - "pull-stream-to-async-iterator": "^1.0.2", - "pull-stream-to-stream": "^1.3.4", - "pull-traverse": "^1.0.3", - "readable-stream": "^3.4.0", - "receptacle": "^1.3.2", - "semver": "^6.3.0", - "stream-to-pull-stream": "^1.7.3", - "superstruct": "~0.6.2", - "tar-stream": "^2.0.0", - "temp": "~0.9.0", - "update-notifier": "^3.0.1", - "uri-to-multiaddr": "^3.0.1", - "varint": "^5.0.0", - "yargs": "^14.0.0", - "yargs-promise": "^1.1.0" - }, - "description": "JavaScript implementation of the IPFS specification", - "devDependencies": { - "aegir": "^20.1.0", - "base64url": "^3.0.1", - "chai": "^4.2.0", - "clear-module": "^4.0.0", - "delay": "^4.1.0", - "detect-node": "^2.0.4", - "dir-compare": "^1.7.3", - "dirty-chai": "^2.0.1", - "execa": "^2.0.4", - "form-data": "^2.5.1", - "hat": "0.0.3", - "interface-ipfs-core": "^0.113.0", - "ipfs-interop": "~0.1.0", - "ipfsd-ctl": "0.46.0", - "libp2p-websocket-star": "~0.10.2", - "ncp": "^2.0.0", - "p-event": "^4.1.0", - "qs": "^6.5.2", - "rimraf": "^3.0.0", - "sinon": "^7.4.2", - "stream-to-promise": "^2.2.0" - }, - "directories": {}, - "dist": { - "fileCount": 271, - "integrity": "sha512-Yt4bTEqJ32zml6FbTIaEUZS4Wo8MI97Q/fqU3TgbflKln5YEY7nXcr4Y/fzC/2n6jZG7j7XZsP0LFM557WJ+Fw==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdkiknCRA9TVsSAnZWagAAllIP/299cEcEVo5s5nk0xqCV\naNsQMfj2cX8hePUrOUeII9KRkzPvfFl4iM0rpe7Dk2MhTNpqCVpic1ZwHCR9\nRspStQSu5VbLpSHRBDEJE4UyqSmJs5BbYv3zR/OZKnHArc198d7Q/LBloxi1\n8/SxchfsDsfsbnDvIEpMxX9v8tkKHYCgLUN/t3rtzH5ljG1fSmp1PUlbwVj7\nIoCV8YrZqTGiZFw1o2IqLVyIw3V/P1Ia8NelxdywCqtmR9GxIs9qNyVNFpx9\nIQxLntKWDotYCYMWm95OwU9hcGdRgK86ckYKvqMM1vVASz+YfWTdRm6Yc04k\nwLPTOKnQGrlHcmF1j3DwlGQJGGml7I5KZvc4HWHK8ZPmbl+FtCkgQvzbLzHm\nLSji8LP+EaNve2i/0ekQxjjta2hwyyKZYnlDaDQFmvLREMzrf2Z4aH2gQVzE\nDFU2m1YWekO+lpUJtQ9VlBt/ctml9aMMzpUeZxgio0rc9FNe2YIJ+7OXUOF4\nW0FG2qzGGQc5NqhBDYiCriJIBuycFwm0R0eniZFht7t192TmUILG+OLN0YdB\nZfDGinxvUtcWwGb0kvxjWhItsKMPoM45du7YbA4O5E6+nLtOSoQq4RT6O0yX\nddggIsVXUXOoiXU2vSciofPVB8+XC/wp6aykrV7XA+BxHxeHwgcGpFye2iAa\no8A+\r\n=MQTz\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "03f79912ce4b5ebeb081b26e92410c8f6751903c", - "tarball": "https://registry.npmjs.org/ipfs/-/ipfs-0.38.0.tgz", - "unpackedSize": 27517601 - }, - "engines": { - "node": ">=10.0.0", - "npm": ">=6.0.0" - }, - "gitHead": "6c4f081d75acbc1ed9e1bbb67b49ce61cb816807", - "homepage": "https://js.ipfs.io", - "keywords": [ - "IPFS" - ], - "leadMaintainer": "Alan Shaw ", - "license": "MIT", - "main": "src/core/index.js", - "maintainers": [ - { - "name": "alanshaw", - "email": "alan138@gmail.com" - }, - { - "name": "daviddias", - "email": "mail@daviddias.me" - } - ], - "name": "ipfs", - "optionalDependencies": { - "prom-client": "^11.5.3", - "prometheus-gc-stats": "~0.6.0" - }, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+https://github.com/ipfs/js-ipfs.git" - }, - "scripts": { - "benchmark": "echo \"Error: no benchmarks yet\" && exit 1", - "benchmark:browser": "echo \"Error: no benchmarks yet\" && exit 1", - "benchmark:node": "echo \"Error: no benchmarks yet\" && exit 1", - "benchmark:node:core": "echo \"Error: no benchmarks yet\" && exit 1", - "benchmark:node:http": "echo \"Error: no benchmarks yet\" && exit 1", - "build": "aegir build", - "coverage": "nyc --reporter=text --reporter=lcov npm run test:node", - "lint": "aegir lint", - "release": "aegir release -t node -t browser", - "release-major": "aegir release --type major -t node -t browser", - "release-minor": "aegir release --type minor -t node -t browser", - "test": "aegir test", - "test:bootstrapers": "IPFS_TEST=bootstrapers aegir test -t browser -f test/bootstrapers.js", - "test:browser": "aegir test -t browser", - "test:external": "aegir test-external", - "test:interop": "IPFS_JS_EXEC=$PWD/src/cli/bin.js ipfs-interop", - "test:node": "aegir test -t node", - "test:node:cli": "aegir test -t node -f test/cli/index.js", - "test:node:core": "aegir test -t node -f test/core/**/*.js", - "test:node:gateway": "aegir test -t node -f test/gateway/index.js", - "test:node:http": "aegir test -t node -f test/http-api/index.js", - "test:node:interface": "aegir test -t node -f test/core/interface.spec.js", - "test:webworker": "aegir test -t webworker" - }, - "version": "0.38.0" -} - -},{}],630:[function(require,module,exports){ -'use strict' - -const waterfall = require('async/waterfall') -const RepoErrors = require('ipfs-repo').errors - -// Boot an IPFS node depending on the options set -module.exports = (self) => { - self.log('booting') - const options = self._options - const doInit = options.init - const doStart = options.start - - // Do the actual boot sequence - waterfall([ - // Checks if a repo exists, and if so opens it - // Will return callback with a bool indicating the existence - // of the repo - (cb) => { - // nothing to do - if (!self._repo.closed) { - return cb(null, true) - } - - self._repo.open((err, res) => { - if (isRepoUninitializedError(err)) return cb(null, false) - if (err) return cb(err) - cb(null, true) - }) - }, - (repoOpened, cb) => { - // Init with existing initialized, opened, repo - if (repoOpened) { - return self.init({ repo: self._repo }, (err) => { - if (err) return cb(Object.assign(err, { emitted: true })) - cb() - }) - } - - if (doInit) { - const initOptions = Object.assign( - { bits: 2048, pass: self._options.pass }, - typeof options.init === 'object' ? options.init : {} - ) - return self.init(initOptions, (err) => { - if (err) return cb(Object.assign(err, { emitted: true })) - cb() - }) - } - - cb() - }, - (cb) => { - // No problem, we don't have to start the node - if (!doStart) { - return cb() - } - - self.start((err) => { - if (err) return cb(Object.assign(err, { emitted: true })) - cb() - }) - } - ], (err) => { - if (err) { - if (!err.emitted) { - self.emit('error', err) - } - return - } - self.log('booted') - self.emit('ready') - }) -} - -function isRepoUninitializedError (err) { - if (!err) { - return false - } - - // If the error is that no repo exists, - // which happens when the version file is not found - // we just want to signal that no repo exist, not - // fail the whole process. - - // Use standardized errors as much as possible - if (err.code === RepoErrors.ERR_REPO_NOT_INITIALIZED) { - return true - } - - // TODO: As error codes continue to be standardized, this logic can be phase out; - // it is here to maintain compatibility - if (err.message.match(/not found/) || // indexeddb - err.message.match(/ENOENT/) || // fs - err.message.match(/No value/) // memory - ) { - return true - } - - return false -} - -},{"async/waterfall":152,"ipfs-repo":535}],631:[function(require,module,exports){ -'use strict' - -const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR -const promisify = require('promisify-es6') -const setImmediate = require('async/setImmediate') -const Big = require('bignumber.js') -const CID = require('cids') -const PeerId = require('peer-id') -const errCode = require('err-code') - -function formatWantlist (list, cidBase) { - return Array.from(list).map((e) => ({ '/': e[1].cid.toBaseEncodedString(cidBase) })) -} - -module.exports = function bitswap (self) { - return { - wantlist: promisify((peerId, callback) => { - if (typeof peerId === 'function') { - callback = peerId - peerId = null - } - - if (!self.isOnline()) { - return setImmediate(() => callback(new Error(OFFLINE_ERROR))) - } - - let list - if (peerId) { - try { - peerId = PeerId.createFromB58String(peerId) - } catch (e) { - peerId = null - } - if (!peerId) { - return setImmediate(() => callback(new Error('Invalid peerId'))) - } - list = self._bitswap.wantlistForPeer(peerId) - } else { - list = self._bitswap.getWantlist() - } - - setImmediate(() => callback(null, { Keys: formatWantlist(list) })) - }), - - stat: promisify((callback) => { - if (!self.isOnline()) { - return setImmediate(() => callback(new Error(OFFLINE_ERROR))) - } - - const snapshot = self._bitswap.stat().snapshot - - setImmediate(() => { - callback(null, { - provideBufLen: parseInt(snapshot.providesBufferLength.toString()), - blocksReceived: new Big(snapshot.blocksReceived), - wantlist: formatWantlist(self._bitswap.getWantlist()), - peers: self._bitswap.peers().map((id) => id.toB58String()), - dupBlksReceived: new Big(snapshot.dupBlksReceived), - dupDataReceived: new Big(snapshot.dupDataReceived), - dataReceived: new Big(snapshot.dataReceived), - blocksSent: new Big(snapshot.blocksSent), - dataSent: new Big(snapshot.dataSent) - }) - }) - }), - - unwant: promisify((keys, callback) => { - if (!self.isOnline()) { - return setImmediate(() => callback(new Error(OFFLINE_ERROR))) - } - - if (!Array.isArray(keys)) { - keys = [keys] - } - - try { - keys = keys.map((key) => { - if (CID.isCID(key)) { - return key - } - return new CID(key) - }) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - setImmediate(() => callback(null, self._bitswap.unwant(keys))) - }) - } -} - -},{"../utils":714,"async/setImmediate":146,"bignumber.js":164,"cids":222,"err-code":315,"peer-id":1432,"promisify-es6":1443}],632:[function(require,module,exports){ -'use strict' - -const Block = require('ipfs-block') -const multihashing = require('multihashing-async') -const CID = require('cids') -const waterfall = require('async/waterfall') -const setImmediate = require('async/setImmediate') -const promisify = require('promisify-es6') -const errCode = require('err-code') - -module.exports = function block (self) { - return { - get: promisify((cid, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - try { - cid = cleanCid(cid) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - if (options.preload !== false) { - self._preload(cid) - } - - self._blockService.get(cid, callback) - }), - put: promisify((block, options, callback) => { - callback = callback || function noop () {} - - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - if (Array.isArray(block)) { - return callback(new Error('Array is not supported')) - } - - waterfall([ - (cb) => { - if (Block.isBlock(block)) { - return cb(null, block) - } - - if (options.cid && CID.isCID(options.cid)) { - return cb(null, new Block(block, options.cid)) - } - - const mhtype = options.mhtype || 'sha2-256' - const format = options.format || 'dag-pb' - let cidVersion - // const mhlen = options.mhlen || 0 - - if (options.version == null) { - // Pick appropriate CID version - cidVersion = mhtype === 'sha2-256' && format === 'dag-pb' ? 0 : 1 - } else { - cidVersion = options.version - } - - multihashing(block, mhtype, (err, multihash) => { - if (err) { - return cb(err) - } - - let cid - try { - cid = new CID(cidVersion, format, multihash) - } catch (err) { - return cb(err) - } - - cb(null, new Block(block, cid)) - }) - }, - (block, cb) => self._gcLock.readLock((_cb) => { - self._blockService.put(block, (err) => { - if (err) { - return _cb(err) - } - - if (options.preload !== false) { - self._preload(block.cid) - } - - _cb(null, block) - }) - }, cb) - ], callback) - }), - rm: promisify((cid, callback) => { - try { - cid = cleanCid(cid) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - // We need to take a write lock here to ensure that adding and removing - // blocks are exclusive operations - self._gcLock.writeLock((cb) => self._blockService.delete(cid, cb), callback) - }), - stat: promisify((cid, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - try { - cid = cleanCid(cid) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - if (options.preload !== false) { - self._preload(cid) - } - - self._blockService.get(cid, (err, block) => { - if (err) { - return callback(err) - } - callback(null, { - key: cid.toString(), - size: block.data.length - }) - }) - }) - } -} - -function cleanCid (cid) { - if (CID.isCID(cid)) { - return cid - } - - // CID constructor knows how to do the cleaning :) - return new CID(cid) -} - -},{"async/setImmediate":146,"async/waterfall":152,"cids":222,"err-code":315,"ipfs-block":491,"multihashing-async":1336,"promisify-es6":1443}],633:[function(require,module,exports){ -(function (setImmediate){ -'use strict' - -const defaultConfig = require('../runtime/config-nodejs.js') -const isMultiaddr = require('mafmt').IPFS.matches -const promisify = require('promisify-es6') - -function isValidMultiaddr (ma) { - try { - return isMultiaddr(ma) - } catch (err) { - return false - } -} - -function invalidMultiaddrError (ma) { - return new Error(`${ma} is not a valid Multiaddr`) -} - -module.exports = function bootstrap (self) { - return { - list: promisify((callback) => { - self._repo.config.get((err, config) => { - if (err) { - return callback(err) - } - callback(null, { Peers: config.Bootstrap }) - }) - }), - add: promisify((multiaddr, args, callback) => { - if (typeof args === 'function') { - callback = args - args = { default: false } - } - - if (multiaddr && !isValidMultiaddr(multiaddr)) { - return setImmediate(() => callback(invalidMultiaddrError(multiaddr))) - } - - self._repo.config.get((err, config) => { - if (err) { - return callback(err) - } - if (args.default) { - config.Bootstrap = defaultConfig().Bootstrap - } else if (multiaddr && config.Bootstrap.indexOf(multiaddr) === -1) { - config.Bootstrap.push(multiaddr) - } - self._repo.config.set(config, (err) => { - if (err) { - return callback(err) - } - - callback(null, { - Peers: args.default ? defaultConfig().Bootstrap : [multiaddr] - }) - }) - }) - }), - rm: promisify((multiaddr, args, callback) => { - if (typeof args === 'function') { - callback = args - args = { all: false } - } - if (multiaddr && !isValidMultiaddr(multiaddr)) { - return setImmediate(() => callback(invalidMultiaddrError(multiaddr))) - } - - self._repo.config.get((err, config) => { - if (err) { - return callback(err) - } - if (args.all) { - config.Bootstrap = [] - } else { - config.Bootstrap = config.Bootstrap.filter((mh) => mh !== multiaddr) - } - - self._repo.config.set(config, (err) => { - if (err) { - return callback(err) - } - - const res = [] - if (!args.all && multiaddr) { - res.push(multiaddr) - } - - callback(null, { Peers: res }) - }) - }) - }) - } -} - -}).call(this,require("timers").setImmediate) -},{"../runtime/config-nodejs.js":705,"mafmt":1296,"promisify-es6":1443,"timers":1749}],634:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') - -module.exports = function config (self) { - return { - get: promisify((key, callback) => { - if (typeof key === 'function') { - callback = key - key = undefined - } - - return self._repo.config.get(key, callback) - }), - set: promisify((key, value, callback) => { - self._repo.config.set(key, value, callback) - }), - replace: promisify((config, callback) => { - self._repo.config.set(config, callback) - }) - } -} - -},{"promisify-es6":1443}],635:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const promisify = require('promisify-es6') -const CID = require('cids') -const pull = require('pull-stream') -const iterToPull = require('async-iterator-to-pull-stream') -const setImmediate = require('async/setImmediate') -const errCode = require('err-code') -const multicodec = require('multicodec') - -module.exports = function dag (self) { - return { - put: promisify((dagNode, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - if (options.cid && (options.format || options.hashAlg)) { - return callback(new Error('Can\'t put dag node. Please provide either `cid` OR `format` and `hashAlg` options.')) - } else if (((options.format && !options.hashAlg) || (!options.format && options.hashAlg))) { - return callback(new Error('Can\'t put dag node. Please provide `format` AND `hashAlg` options.')) - } - - const optionDefaults = { - format: multicodec.DAG_CBOR, - hashAlg: multicodec.SHA2_256 - } - - // The IPLD expects the format and hashAlg as constants - if (options.format && typeof options.format === 'string') { - const constantName = options.format.toUpperCase().replace(/-/g, '_') - options.format = multicodec[constantName] - } - if (options.hashAlg && typeof options.hashAlg === 'string') { - const constantName = options.hashAlg.toUpperCase().replace(/-/g, '_') - options.hashAlg = multicodec[constantName] - } - - options = options.cid ? options : Object.assign({}, optionDefaults, options) - - // js-ipld defaults to verion 1 CIDs. Hence set version 0 explicitly for - // dag-pb nodes - if (options.version === undefined) { - if (options.format === multicodec.DAG_PB && options.hashAlg === multicodec.SHA2_256) { - options.version = 0 - } else { - options.version = 1 - } - } - - self._ipld.put(dagNode, options.format, { - hashAlg: options.hashAlg, - cidVersion: options.version - }).then( - (cid) => { - if (options.preload !== false) { - self._preload(cid) - } - return callback(null, cid) - }, - (error) => callback(error) - ) - }), - - get: promisify((cid, path, options, callback) => { - if (typeof path === 'function') { - callback = path - path = undefined - } - - if (typeof options === 'function') { - callback = options - - // Allow options in path position - if (typeof path !== 'string') { - options = path - path = undefined - } else { - options = {} - } - } - - options = options || {} - - if (typeof cid === 'string') { - const split = cid.split('/') - - try { - cid = new CID(split[0]) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - split.shift() - - if (split.length > 0) { - path = split.join('/') - } else { - path = path || '/' - } - } else if (Buffer.isBuffer(cid)) { - try { - cid = new CID(cid) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - } - - if (options.preload !== false) { - self._preload(cid) - } - - if (path == null || path === '/') { - self._ipld.get(cid).then( - (value) => { - callback(null, { - value, - remainderPath: '' - }) - }, - (error) => callback(error) - ) - } else { - const result = self._ipld.resolve(cid, path) - const promisedValue = options.localResolve ? result.first() : result.last() - promisedValue.then( - (value) => callback(null, value), - (error) => callback(error) - ) - } - }), - - tree: promisify((cid, path, options, callback) => { - if (typeof path === 'object') { - callback = options - options = path - path = undefined - } - - if (typeof path === 'function') { - callback = path - path = undefined - } - - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - if (typeof cid === 'string') { - const split = cid.split('/') - - try { - cid = new CID(split[0]) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - split.shift() - - if (split.length > 0) { - path = split.join('/') - } else { - path = undefined - } - } - - if (options.preload !== false) { - self._preload(cid) - } - - pull( - iterToPull(self._ipld.tree(cid, path, options)), - pull.collect(callback) - ) - }) - } -} - -}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) -},{"../../../../is-buffer/index.js":766,"async-iterator-to-pull-stream":86,"async/setImmediate":146,"cids":222,"err-code":315,"multicodec":1325,"promisify-es6":1443,"pull-stream":1495}],636:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const promisify = require('promisify-es6') -const every = require('async/every') -const PeerId = require('peer-id') -const PeerInfo = require('peer-info') -const CID = require('cids') -const each = require('async/each') -const nextTick = require('async/nextTick') - -const errcode = require('err-code') - -const debug = require('debug') -const log = debug('ipfs:dht') -log.error = debug('ipfs:dht:error') - -module.exports = (self) => { - return { - /** - * Given a key, query the DHT for its best value. - * - * @param {Buffer} key - * @param {Object} options - get options - * @param {number} options.timeout - optional timeout - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - get: promisify((key, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - if (!Buffer.isBuffer(key)) { - try { - key = (new CID(key)).buffer - } catch (err) { - log.error(err) - - return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) - } - } - - self.libp2p.dht.get(key, options, callback) - }), - - /** - * Write a key/value pair to the DHT. - * - * Given a key of the form /foo/bar and a value of any - * form, this will write that value to the DHT with - * that key. - * - * @param {Buffer} key - * @param {Buffer} value - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - put: promisify((key, value, callback) => { - if (!Buffer.isBuffer(key)) { - try { - key = (new CID(key)).buffer - } catch (err) { - log.error(err) - - return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) - } - } - - self.libp2p.dht.put(key, value, callback) - }), - - /** - * Find peers in the DHT that can provide a specific value, given a key. - * - * @param {CID} key - They key to find providers for. - * @param {Object} options - findProviders options - * @param {number} options.timeout - how long the query should maximally run, in milliseconds (default: 60000) - * @param {number} options.maxNumProviders - maximum number of providers to find - * @param {function(Error, Array)} [callback] - * @returns {Promise|void} - */ - findProvs: promisify((key, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - if (typeof key === 'string') { - try { - key = new CID(key) - } catch (err) { - log.error(err) - - return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID'))) - } - } - - self.libp2p.contentRouting.findProviders(key, options, callback) - }), - - /** - * Query the DHT for all multiaddresses associated with a `PeerId`. - * - * @param {PeerId} peer - The id of the peer to search for. - * @param {function(Error, PeerInfo)} [callback] - * @returns {Promise|void} - */ - findPeer: promisify((peer, callback) => { - if (typeof peer === 'string') { - peer = PeerId.createFromB58String(peer) - } - - self.libp2p.peerRouting.findPeer(peer, callback) - }), - - /** - * Announce to the network that we are providing given values. - * - * @param {CID|Array} keys - The keys that should be announced. - * @param {Object} options - provide options - * @param {bool} [options.recursive=false] - Provide not only the given object but also all objects linked from it. - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - provide: promisify((keys, options, callback) => { - if (!Array.isArray(keys)) { - keys = [keys] - } - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - // ensure blocks are actually local - every(keys, (key, cb) => { - self._repo.blocks.has(key, cb) - }, (err, has) => { - if (err) { - return callback(err) - } - - if (!has) { - const errMsg = 'block(s) not found locally, cannot provide' - - log.error(errMsg) - return callback(errcode(errMsg, 'ERR_BLOCK_NOT_FOUND')) - } - - if (options.recursive) { - // TODO: Implement recursive providing - return callback(errcode('not implemented yet', 'ERR_NOT_IMPLEMENTED_YET')) - } else { - each(keys, (cid, cb) => { - self.libp2p.contentRouting.provide(cid, cb) - }, callback) - } - }) - }), - - /** - * Find the closest peers to a given `PeerId`, by querying the DHT. - * - * @param {PeerId} peer - The `PeerId` to run the query agains. - * @param {function(Error, Array)} [callback] - * @returns {Promise>|void} - */ - query: promisify((peerId, callback) => { - if (typeof peerId === 'string') { - try { - peerId = PeerId.createFromB58String(peerId) - } catch (err) { - log.error(err) - return callback(err) - } - } - - // TODO expose this method in peerRouting - self.libp2p._dht.getClosestPeers(peerId.toBytes(), (err, peerIds) => { - if (err) { - log.error(err) - return callback(err) - } - - callback(null, peerIds.map((id) => new PeerInfo(id))) - }) - }) - } -} - -}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) -},{"../../../../is-buffer/index.js":766,"async/each":106,"async/every":112,"async/nextTick":140,"cids":222,"debug":611,"err-code":315,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],637:[function(require,module,exports){ -'use strict' - -// dns-nodejs gets replaced by dns-browser when webpacked/browserified -const dns = require('../runtime/dns-nodejs') -const promisify = require('promisify-es6') - -function fqdnFixups (domain) { - // Allow resolution of .eth names via .eth.link - // More context at the go-ipfs counterpart: https://github.com/ipfs/go-ipfs/pull/6448 - if (domain.endsWith('.eth')) { - domain = domain.replace(/.eth$/, '.eth.link') - } - return domain -} - -module.exports = () => { - return promisify((domain, opts, callback) => { - if (typeof domain !== 'string') { - return callback(new Error('Invalid arguments, domain must be a string')) - } - - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - opts = opts || {} - domain = fqdnFixups(domain) - - dns(domain, opts, callback) - }) -} - -},{"../runtime/dns-nodejs":706,"promisify-es6":1443}],638:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const mfs = require('ipfs-mfs/core') -const isPullStream = require('is-pull-stream') -const toPullStream = require('async-iterator-to-pull-stream') -const toReadableStream = require('async-iterator-to-stream') -const pullStreamToAsyncIterator = require('pull-stream-to-async-iterator') -const all = require('async-iterator-all') -const nodeify = require('promise-nodeify') -const PassThrough = require('stream').PassThrough -const pull = require('pull-stream/pull') -const map = require('pull-stream/throughs/map') -const isIpfs = require('is-ipfs') -const { cidToString } = require('../../utils/cid') - -/** - * @typedef { import("readable-stream").Readable } ReadableStream - * @typedef { import("pull-stream") } PullStream - */ - -const mapLsFile = (options = {}) => { - const long = options.long || options.l - - return (file) => { - return { - hash: long ? cidToString(file.cid, { base: options.cidBase }) : '', - name: file.name, - type: long ? file.type : 0, - size: long ? file.size || 0 : 0 - } - } -} - -module.exports = (/** @type { import("../index") } */ ipfs) => { - const methodsOriginal = mfs({ - ipld: ipfs._ipld, - blocks: ipfs._blockService, - datastore: ipfs._repo.root, - repoOwner: ipfs._options.repoOwner - }) - - const withPreload = fn => (...args) => { - const paths = args.filter(arg => isIpfs.ipfsPath(arg) || isIpfs.cid(arg)) - - if (paths.length) { - const options = args[args.length - 1] - if (options.preload !== false) { - paths.forEach(path => ipfs._preload(path)) - } - } - - return fn(...args) - } - - const methods = { - ...methodsOriginal, - cp: withPreload(methodsOriginal.cp), - ls: withPreload(methodsOriginal.ls), - mv: withPreload(methodsOriginal.mv), - read: withPreload(methodsOriginal.read), - stat: withPreload(methodsOriginal.stat) - } - - return { - /** - * Copy files - * - * @param {String | Array} from - The path(s) of the source to copy. - * @param {String} to - The path of the destination to copy to. - * @param {Object} [opts] - Options for copy. - * @param {boolean} [opts.parents=false] - Whether or not to make the parent directories if they don't exist. (default: false) - * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb) - * @param {String} [opts.hashAlg=sha2-256] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} - * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true). - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - cp: (from, to, opts, cb) => { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(methods.cp(from, to, opts), cb) - }, - - /** - * Make a directory - * - * @param {String} path - The path to the directory to make. - * @param {Object} [opts] - Options for mkdir. - * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) - * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb). - * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} - * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true). - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - mkdir: (path, opts, cb) => { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(methods.mkdir(path, opts), cb) - }, - - /** - * @typedef {Object} StatOutput - * @prop {String} hash - Output hash. - * @prop {number} size - File size in bytes. - * @prop {number} cumulativeSize - Integer with the size of the DAGNodes making up the file in Bytes. - * @prop {string} type - Output type either 'directory' or 'file'. - * @prop {number} blocks - If type is directory, this is the number of files in the directory. If it is file it is the number of blocks that make up the file. - * @prop {boolean} withLocality - Indicate if locality information is present. - * @prop {boolean} local - Indicate if the queried dag is fully present locally. - * @prop {number} sizeLocal - Integer indicating the cumulative size of the data present locally. - */ - - /** - * Get file or directory status. - * - * @param {String} path - Path to the file or directory to stat. - * @param {Object} [opts] - Options for stat. - * @param {boolean} [opts.hash=false] - Return only the hash. (default: false) - * @param {boolean} [opts.size=false] - Return only the size. (default: false) - * @param {boolean} [opts.withLocal=false] - Compute the amount of the dag that is local, and if possible the total size. (default: false) - * @param {String} [opts.cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc) - * @param {function(Error, StatOutput): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - stat: (path, opts, cb) => { - const stat = async (path, opts = {}) => { - const stats = await methods.stat(path, opts) - - stats.hash = stats.cid.toBaseEncodedString(opts && opts.cidBase) - delete stats.cid - - return stats - } - - if (typeof opts === 'function') { - cb = opts - opts = {} - } - - return nodeify(stat(path, opts), cb) - }, - - /** - * Remove a file or directory. - * - * @param {String | Array} paths - One or more paths to remove. - * @param {Object} [opts] - Options for remove. - * @param {boolean} [opts.recursive=false] - Whether or not to remove directories recursively. (default: false) - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - rm: (paths, opts, cb) => { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(methods.rm(paths, opts), cb) - }, - - /** - * @typedef {Object} ReadOptions - * @prop {number} [opts.offset=0] - Integer with the byte offset to begin reading from (default: 0). - * @prop {number} [opts.length] - Integer with the maximum number of bytes to read (default: Read to the end of stream). - */ - - /** - * Read a file into a Buffer. - * - * @param {string} path - Path of the file to read and must point to a file (and not a directory). - * @param {ReadOptions} [opts] - Object for read. - * @param {function(Error, Buffer): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - read: (path, opts, cb) => { - const read = async (path, opts = {}) => { - return Buffer.concat(await all(methods.read(path, opts))) - } - - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(read(path, opts), cb) - }, - - /** - * Read a file into a ReadableStream. - * - * @param {string} path - Path of the file to read and must point to a file (and not a directory). - * @param {ReadOptions} [opts] - Object for read. - * @returns {ReadableStream} Returns a ReadableStream with the contents of path. - */ - readReadableStream: (path, opts = {}) => toReadableStream(methods.read(path, opts)), - - /** - * Read a file into a PullStrean. - * - * @param {string} path - Path of the file to read and must point to a file (and not a directory). - * @param {ReadOptions} [opts] - Object for read. - * @returns {PullStream} Returns a PullStream with the contents of path. - */ - readPullStream: (path, opts = {}) => toPullStream.source(methods.read(path, opts)), - - /** - * Write to a file. - * - * @param {string} path - Path of the file to write. - * @param {Buffer | PullStream | ReadableStream | Blob | string} content - Content to write. - * @param {Object} opts - Options for write. - * @param {number} [opts.offset=0] - Integer with the byte offset to begin writing at. (default: 0) - * @param {boolean} [opts.create=false] - Indicate to create the file if it doesn't exist. (default: false) - * @param {boolean} [opts.truncate=false] - Indicate if the file should be truncated after writing all the bytes from content. (default: false) - * @param {boolena} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) - * @param {number} [opts.length] - Maximum number of bytes to read. (default: Read all bytes from content) - * @param {boolean} [opts.rawLeaves=false] - If true, DAG leaves will contain raw file data and not be wrapped in a protobuf. (default: false) - * @param {number} [opts.cidVersion=0] - The CID version to use when storing the data (storage keys are based on the CID, including its version). (default: 0) - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - write: (path, content, opts, cb) => { - const write = async (path, content, opts = {}) => { - if (isPullStream.isSource(content)) { - content = pullStreamToAsyncIterator(content) - } - - await methods.write(path, content, opts) - } - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(write(path, content, opts), cb) - }, - - /** - * Move files. - * - * @param {string | Array} from - Path(s) of the source to move. - * @param {string} to - Path of the destination to move to. - * @param {Object} opts - Options for mv. - * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false) - * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb). - * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values} - * @param {boolean} [opts.flush=true] - Value to decide whether or not to immediately flush MFS changes to disk. (default: true) - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - * @description - * If from has multiple values then to must be a directory. - * - * If from has a single value and to exists and is a directory, from will be moved into to. - * - * If from has a single value and to exists and is a file, from must be a file and the contents of to will be replaced with the contents of from otherwise an error will be returned. - * - * If from is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen. - * - * All values of from will be removed after the operation is complete unless they are an IPFS path. - */ - mv: (from, to, opts, cb) => { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(methods.mv(from, to, opts), cb) - }, - - /** - * Flush a given path's data to the disk. - * - * @param {string | Array} [paths] - String paths to flush. (default: /) - * @param {function(Error): void} [cb] - Callback function. - * @returns {Promise | void} When callback is provided nothing is returned. - */ - flush: (paths, cb) => { - if (typeof paths === 'function') { - cb = paths - paths = undefined - } - return nodeify(methods.flush(paths), cb) - }, - - /** - * @typedef {Object} ListOutputFile - * @prop {string} name - Which is the file's name. - * @prop {string} type - Which is the object's type (directory or file). - * @prop {number} size - The size of the file in bytes. - * @prop {string} hash - The hash of the file. - */ - - /** - * @typedef {Object} ListOptions - * @prop {boolean} [long=false] - Value to decide whether or not to populate type, size and hash. (default: false) - * @prop {string} [cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc) - * @prop {boolean} [sort=false] - If true entries will be sorted by filename. (default: false) - */ - - /** - * List directories in the local mutable namespace. - * - * @param {string} [path="/"] - String to show listing for. (default: /) - * @param {ListOptions} [opts] - Options for list. - * @param {function(Error, Array): void} [cb] - Callback function. - * @returns {Promise> | void} When callback is provided nothing is returned. - */ - ls: (path, opts, cb) => { - const ls = async (path, opts = {}) => { - const files = await all(methods.ls(path, opts)) - - return files.map(mapLsFile(opts)) - } - - if (typeof path === 'function') { - cb = path - path = '/' - opts = {} - } - - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(ls(path, opts), cb) - }, - - /** - * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as Readable Streams. - * - * @param {string} [path="/"] - String to show listing for. (default: /) - * @param {ListOptions} [opts] - Options for list. - * @returns {ReadableStream} It returns a Readable Stream in Object mode that will yield {@link ListOutputFile} - */ - lsReadableStream: (path, opts = {}) => { - const stream = toReadableStream.obj(methods.ls(path, opts)) - const through = new PassThrough({ - objectMode: true - }) - stream.on('data', (file) => { - through.write(mapLsFile(opts)(file)) - }) - stream.on('error', (err) => { - through.destroy(err) - }) - stream.on('end', (file, enc, cb) => { - if (file) { - file = mapLsFile(opts)(file) - } - - through.end(file, enc, cb) - }) - - return through - }, - - /** - * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as PullStreams. - * - * @param {string} [path="/"] - String to show listing for. (default: /) - * @param {ListOptions} [opts] - Options for list. - * @returns {PullStream} It returns a PullStream that will yield {@link ListOutputFile} - */ - lsPullStream: (path, opts = {}) => { - return pull( - toPullStream.source(methods.ls(path, opts)), - map(mapLsFile(opts)) - ) - } - } -} - -}).call(this,require("buffer").Buffer) -},{"../../utils/cid":715,"async-iterator-all":82,"async-iterator-to-pull-stream":86,"async-iterator-to-stream":87,"buffer":217,"ipfs-mfs/core":492,"is-ipfs":775,"is-pull-stream":778,"promise-nodeify":1439,"pull-stream-to-async-iterator":1493,"pull-stream/pull":1496,"pull-stream/throughs/map":1518,"stream":628}],639:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const importer = require('ipfs-unixfs-importer') -const normaliseAddInput = require('ipfs-utils/src/files/normalise-input') -const { parseChunkerString } = require('./utils') -const pipe = require('it-pipe') -const log = require('debug')('ipfs:add') -log.error = require('debug')('ipfs:add:error') - -function noop () {} - -module.exports = function (self) { - // Internal add func that gets used by all add funcs - return async function * addAsyncIterator (source, options) { - options = options || {} - - const chunkerOptions = parseChunkerString(options.chunker) - - const opts = Object.assign({}, { - shardSplitThreshold: self._options.EXPERIMENTAL.sharding - ? 1000 - : Infinity - }, options, { - chunker: chunkerOptions.chunker, - chunkerOptions: chunkerOptions.chunkerOptions - }) - - // CID v0 is for multihashes encoded with sha2-256 - if (opts.hashAlg && opts.cidVersion !== 1) { - opts.cidVersion = 1 - } - - let total = 0 - - const prog = opts.progress || noop - const progress = (bytes) => { - total += bytes - prog(total) - } - - opts.progress = progress - - const iterator = pipe( - normaliseAddInput(source), - doImport(self, opts), - transformFile(self, opts), - preloadFile(self, opts), - pinFile(self, opts) - ) - - const releaseLock = await self._gcLock.readLock() - - try { - yield * iterator - } finally { - releaseLock() - } - } -} - -function doImport (ipfs, opts) { - return async function * (source) { // eslint-disable-line require-await - yield * importer(source, ipfs._ipld, opts) - } -} - -function transformFile (ipfs, opts) { - return async function * (source) { - for await (const file of source) { - let cid = file.cid - const hash = cid.toBaseEncodedString() - let path = file.path ? file.path : hash - - if (opts.wrapWithDirectory && !file.path) { - path = '' - } - - if (opts.onlyHash) { - yield { - path, - hash, - size: file.unixfs.fileSize() - } - - return - } - - const node = await ipfs.object.get(file.cid, Object.assign({}, opts, { preload: false })) - - if (opts.cidVersion === 1) { - cid = cid.toV1() - } - - let size = node.size - - if (Buffer.isBuffer(node)) { - size = node.length - } - - yield { - path, - hash, - size - } - } - } -} - -function preloadFile (ipfs, opts) { - return async function * (source) { - for await (const file of source) { - const isRootFile = !file.path || opts.wrapWithDirectory - ? file.path === '' - : !file.path.includes('/') - - const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false - - if (shouldPreload) { - ipfs._preload(file.hash) - } - - yield file - } - } -} - -function pinFile (ipfs, opts) { - return async function * (source) { - for await (const file of source) { - // Pin a file if it is the root dir of a recursive add or the single file - // of a direct add. - const pin = 'pin' in opts ? opts.pin : true - const isRootDir = !file.path.includes('/') - const shouldPin = pin && isRootDir && !opts.onlyHash && !opts.hashAlg - - if (shouldPin) { - // Note: addAsyncIterator() has already taken a GC lock, so tell - // pin.add() not to take a (second) GC lock - await ipfs.pin.add(file.hash, { - preload: false, - lock: false - }) - } - - yield file - } - } -} - -}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"./utils":662,"debug":611,"ipfs-unixfs-importer":588,"ipfs-utils/src/files/normalise-input":609,"it-pipe":806}],640:[function(require,module,exports){ -'use strict' - -module.exports = (self) => require('../../runtime/add-from-fs-nodejs')(self) - -},{"../../runtime/add-from-fs-nodejs":704}],641:[function(require,module,exports){ -'use strict' - -module.exports = self => require('./add')(self) - -},{"./add":645}],642:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const { URL } = require('iso-url') -const fetch = require('../../runtime/fetch-nodejs') - -module.exports = (self) => { - return async (url, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - let files - - try { - const parsedUrl = new URL(url) - const res = await fetch(url) - - if (!res.ok) { - throw new Error('unexpected status code: ' + res.status) - } - - // TODO: use res.body when supported - const content = Buffer.from(await res.arrayBuffer()) - const path = decodeURIComponent(parsedUrl.pathname.split('/').pop()) - - files = await self.add({ content, path }, options) - } catch (err) { - if (callback) { - return callback(err) - } - throw err - } - - if (callback) { - callback(null, files) - } - - return files - } -} - -}).call(this,require("buffer").Buffer) -},{"../../runtime/fetch-nodejs":707,"buffer":217,"iso-url":802}],643:[function(require,module,exports){ -'use strict' - -const toPullStream = require('async-iterator-to-pull-stream') - -module.exports = function (self) { - return function addPullStream (options) { - return toPullStream.transform((source) => { - return self._addAsyncIterator(source, options) - }) - } -} - -},{"async-iterator-to-pull-stream":86}],644:[function(require,module,exports){ -'use strict' - -const toStream = require('it-to-stream') - -module.exports = function (self) { - return function addReadableStream (options) { - return toStream.transform(source => { - return self._addAsyncIterator(source, options) - }, { - objectMode: true - }) - } -} - -},{"it-to-stream":823}],645:[function(require,module,exports){ -'use strict' - -const all = require('async-iterator-all') - -module.exports = function (self) { - // can't use callbackify because if `data` is a pull stream - // it thinks we are passing a callback. This is why we can't have nice things. - return (data, options, callback) => { - if (!callback && typeof options === 'function') { - callback = options - options = {} - } - - const result = all(self._addAsyncIterator(data, options)) - - if (!callback) { - return result - } - - result.then((result) => callback(null, result), callback) - } -} - -},{"async-iterator-all":82}],646:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const deferred = require('pull-defer') -const toPullStream = require('async-iterator-to-pull-stream') -const { normalizePath } = require('./utils') - -module.exports = function (self) { - return function catPullStream (ipfsPath, options) { - if (typeof ipfsPath === 'function') { - throw new Error('You must supply an ipfsPath') - } - - options = options || {} - - ipfsPath = normalizePath(ipfsPath) - const pathComponents = ipfsPath.split('/') - - if (options.preload !== false) { - self._preload(pathComponents[0]) - } - - const d = deferred.source() - - exporter(ipfsPath, self._ipld, options) - .then(file => { - // File may not have unixfs prop if small & imported with rawLeaves true - if (file.unixfs && file.unixfs.type.includes('dir')) { - return d.abort(new Error('this dag node is a directory')) - } - - if (!file.content) { - return d.abort(new Error('this dag node has no content')) - } - - d.resolve(toPullStream.source(file.content(options))) - }, err => { - d.abort(err) - }) - - return d - } -} - -},{"./utils":662,"async-iterator-to-pull-stream":86,"ipfs-unixfs-exporter":540,"pull-defer":1467}],647:[function(require,module,exports){ -'use strict' - -const toStream = require('pull-stream-to-stream') - -module.exports = function (self) { - return (ipfsPath, options) => toStream.source(self.catPullStream(ipfsPath, options)) -} - -},{"pull-stream-to-stream":1494}],648:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream') - -module.exports = function (self) { - return promisify((ipfsPath, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - pull( - self.catPullStream(ipfsPath, options), - pull.collect((err, buffers) => { - if (err) { return callback(err) } - callback(null, Buffer.concat(buffers)) - }) - ) - }) -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"promisify-es6":1443,"pull-stream":1495}],649:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const toPullStream = require('async-iterator-to-pull-stream') -const errCode = require('err-code') -const pull = require('pull-stream/pull') -const pullError = require('pull-stream/sources/error') -const map = require('pull-stream/throughs/map') -const { normalizePath, mapFile } = require('./utils') - -module.exports = function (self) { - return (ipfsPath, options) => { - options = options || {} - - if (options.preload !== false) { - let pathComponents - - try { - pathComponents = normalizePath(ipfsPath).split('/') - } catch (err) { - return pullError(errCode(err, 'ERR_INVALID_PATH')) - } - - self._preload(pathComponents[0]) - } - - return pull( - toPullStream.source(exporter.recursive(ipfsPath, self._ipld, options)), - map(mapFile({ - ...options, - includeContent: true - })) - ) - } -} - -},{"./utils":662,"async-iterator-to-pull-stream":86,"err-code":315,"ipfs-unixfs-exporter":540,"pull-stream/pull":1496,"pull-stream/sources/error":1507,"pull-stream/throughs/map":1518}],650:[function(require,module,exports){ -'use strict' - -const pull = require('pull-stream') -const toStream = require('pull-stream-to-stream') - -module.exports = function (self) { - return (ipfsPath, options) => { - options = options || {} - - return toStream.source( - pull( - self.getPullStream(ipfsPath, options), - pull.map((file) => { - if (file.content) { - file.content = toStream.source(file.content) - file.content.pause() - } - - return file - }) - ) - ) - } -} - -},{"pull-stream":1495,"pull-stream-to-stream":1494}],651:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream') - -module.exports = function (self) { - return promisify((ipfsPath, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - pull( - self.getPullStream(ipfsPath, options), - pull.asyncMap((file, cb) => { - if (file.content) { - pull( - file.content, - pull.collect((err, buffers) => { - if (err) { return cb(err) } - file.content = Buffer.concat(buffers) - cb(null, file) - }) - ) - } else { - cb(null, file) - } - }), - pull.collect(callback) - ) - }) -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"promisify-es6":1443,"pull-stream":1495}],652:[function(require,module,exports){ -'use strict' - -module.exports = (self) => { - const filesRegular = { - add: require('./add')(self), - addFromFs: require('./add-from-fs')(self), - addFromStream: require('./add-from-stream')(self), - addFromURL: require('./add-from-url')(self), - addPullStream: require('./add-pull-stream')(self), - addReadableStream: require('./add-readable-stream')(self), - _addAsyncIterator: require('./add-async-iterator')(self), - cat: require('./cat')(self), - catPullStream: require('./cat-pull-stream')(self), - catReadableStream: require('./cat-readable-stream')(self), - get: require('./get')(self), - getPullStream: require('./get-pull-stream')(self), - getReadableStream: require('./get-readable-stream')(self), - ls: require('./ls')(self), - lsPullStream: require('./ls-pull-stream')(self), - lsReadableStream: require('./ls-readable-stream')(self), - refs: require('./refs')(self), - refsReadableStream: require('./refs-readable-stream')(self), - refsPullStream: require('./refs-pull-stream')(self) - } - filesRegular.refs.local = require('./refs-local')(self) - filesRegular.refs.localReadableStream = require('./refs-local-readable-stream')(self) - filesRegular.refs.localPullStream = require('./refs-local-pull-stream')(self) - return filesRegular -} - -},{"./add":645,"./add-async-iterator":639,"./add-from-fs":640,"./add-from-stream":641,"./add-from-url":642,"./add-pull-stream":643,"./add-readable-stream":644,"./cat":648,"./cat-pull-stream":646,"./cat-readable-stream":647,"./get":651,"./get-pull-stream":649,"./get-readable-stream":650,"./ls":655,"./ls-pull-stream":653,"./ls-readable-stream":654,"./refs":661,"./refs-local":658,"./refs-local-pull-stream":656,"./refs-local-readable-stream":657,"./refs-pull-stream":659,"./refs-readable-stream":660}],653:[function(require,module,exports){ -'use strict' - -const exporter = require('ipfs-unixfs-exporter') -const deferred = require('pull-defer') -const pull = require('pull-stream/pull') -const once = require('pull-stream/sources/once') -const map = require('pull-stream/throughs/map') -const filter = require('pull-stream/throughs/filter') -const errCode = require('err-code') -const toPullStream = require('async-iterator-to-pull-stream') -const { normalizePath, mapFile } = require('./utils') - -module.exports = function (self) { - return function (ipfsPath, options) { - options = options || {} - - const path = normalizePath(ipfsPath) - const recursive = options.recursive - const pathComponents = path.split('/') - - if (options.preload !== false) { - self._preload(pathComponents[0]) - } - - const d = deferred.source() - - exporter(ipfsPath, self._ipld, options) - .then(file => { - if (!file.unixfs) { - return d.abort(errCode(new Error('dag node was not a UnixFS node'), 'ENOTUNIXFS')) - } - - if (file.unixfs.type === 'file') { - return d.resolve(once(mapFile(options)(file))) - } - - if (file.unixfs.type.includes('dir')) { - if (recursive) { - return d.resolve(pull( - toPullStream.source(exporter.recursive(file.cid, self._ipld, options)), - filter(child => file.cid.toBaseEncodedString() !== child.cid.toBaseEncodedString()), - map(mapFile(options)) - )) - } - - return d.resolve(pull( - toPullStream.source(file.content()), - map(mapFile(options)), - map((file) => { - file.depth-- - - return file - }) - )) - } - - d.abort(errCode(new Error(`Unknown UnixFS type ${file.unixfs.type}`), 'EUNKNOWNUNIXFSTYPE')) - }, err => { - d.abort(err) - }) - - return d - } -} - -},{"./utils":662,"async-iterator-to-pull-stream":86,"err-code":315,"ipfs-unixfs-exporter":540,"pull-defer":1467,"pull-stream/pull":1496,"pull-stream/sources/once":1511,"pull-stream/throughs/filter":1515,"pull-stream/throughs/map":1518}],654:[function(require,module,exports){ -'use strict' - -const toStream = require('pull-stream-to-stream') - -module.exports = function (self) { - return (ipfsPath, options) => { - return toStream.source(self.lsPullStream(ipfsPath, options)) - } -} - -},{"pull-stream-to-stream":1494}],655:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream') - -module.exports = function (self) { - return promisify((ipfsPath, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - pull( - self.lsPullStream(ipfsPath, options), - pull.collect((err, values) => { - if (err) { - return callback(err) - } - callback(null, values) - }) - ) - }) -} - -},{"promisify-es6":1443,"pull-stream":1495}],656:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') -const base32 = require('base32.js') -const pull = require('pull-stream') -const pullDefer = require('pull-defer') - -module.exports = function (self) { - return () => { - const deferred = pullDefer.source() - - self._repo.blocks.query({ keysOnly: true }, (err, blocks) => { - if (err) { - return deferred.resolve(pull.error(err)) - } - - const refs = blocks.map(b => dsKeyToRef(b.key)) - deferred.resolve(pull.values(refs)) - }) - - return deferred - } -} - -function dsKeyToRef (key) { - try { - // Block key is of the form / - const decoder = new base32.Decoder() - const buff = Buffer.from(decoder.write(key.toString().slice(1)).finalize()) - return { ref: new CID(buff).toString() } - } catch (err) { - return { err: `Could not convert block with key '${key}' to CID: ${err.message}` } - } -} - -}).call(this,require("buffer").Buffer) -},{"base32.js":160,"buffer":217,"cids":222,"pull-defer":1467,"pull-stream":1495}],657:[function(require,module,exports){ -'use strict' - -const toStream = require('pull-stream-to-stream') - -module.exports = function (self) { - return (ipfsPath, options) => { - return toStream.source(self.refs.localPullStream()) - } -} - -},{"pull-stream-to-stream":1494}],658:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream') - -module.exports = function (self) { - return promisify((callback) => { - pull( - self.refs.localPullStream(), - pull.collect((err, values) => { - if (err) { - return callback(err) - } - callback(null, values) - }) - ) - }) -} - -},{"promisify-es6":1443,"pull-stream":1495}],659:[function(require,module,exports){ -'use strict' - -const pull = require('pull-stream') -const pullDefer = require('pull-defer') -const pullTraverse = require('pull-traverse') -const pullCat = require('pull-cat') -const isIpfs = require('is-ipfs') -const CID = require('cids') -const { DAGNode } = require('ipld-dag-pb') -const { normalizePath } = require('./utils') -const { Format } = require('./refs') - -module.exports = function (self) { - return function (ipfsPath, options = {}) { - if (options.maxDepth === 0) { - return pull.empty() - } - if (options.edges && options.format && options.format !== Format.default) { - return pull.error(new Error('Cannot set edges to true and also specify format')) - } - - options.format = options.edges ? Format.edges : options.format || Format.default - - if (typeof options.maxDepth !== 'number') { - options.maxDepth = options.recursive ? Infinity : 1 - } - - let paths - try { - const rawPaths = Array.isArray(ipfsPath) ? ipfsPath : [ipfsPath] - paths = rawPaths.map(p => getFullPath(self, p, options)) - } catch (err) { - return pull.error(err) - } - - return pullCat(paths.map(p => refsStream(self, p, options))) - } -} - -function getFullPath (ipfs, ipfsPath, options) { - // normalizePath() strips /ipfs/ off the front of the path so the CID will - // be at the front of the path - const path = normalizePath(ipfsPath) - const pathComponents = path.split('/') - const cid = pathComponents[0] - if (!isIpfs.cid(cid)) { - throw new Error(`Error resolving path '${path}': '${cid}' is not a valid CID`) - } - - if (options.preload !== false) { - ipfs._preload(cid) - } - - return '/ipfs/' + path -} - -// Get a stream of refs at the given path -function refsStream (ipfs, path, options) { - const deferred = pullDefer.source() - - // Resolve to the target CID of the path - ipfs.resolve(path, (err, resPath) => { - if (err) { - return deferred.resolve(pull.error(err)) - } - - // path is /ipfs/ - const parts = resPath.split('/') - const cid = parts[2] - deferred.resolve(pull( - // Traverse the DAG, converting it into a stream - objectStream(ipfs, cid, options.maxDepth, options.unique), - // Root object will not have a parent - pull.filter(obj => Boolean(obj.parent)), - // Filter out duplicates (isDuplicate flag is only set if options.unique is set) - pull.filter(obj => !obj.isDuplicate), - // Format the links - pull.map(obj => formatLink(obj.parent.cid, obj.node.cid, obj.node.name, options.format)), - // Clients expect refs to be in the format { ref: } - pull.map(ref => ({ ref })) - )) - }) - - return deferred -} - -// Get formatted link -function formatLink (srcCid, dstCid, linkName, format) { - let out = format.replace(//g, srcCid.toString()) - out = out.replace(//g, dstCid.toString()) - out = out.replace(//g, linkName) - return out -} - -// Do a depth first search of the DAG, starting from the given root cid -function objectStream (ipfs, rootCid, maxDepth, isUnique) { - const uniques = new Set() - - const root = { node: { cid: rootCid }, depth: 0 } - const traverseLevel = (obj) => { - const { node, depth } = obj - - // Check the depth - const nextLevelDepth = depth + 1 - if (nextLevelDepth > maxDepth) { - return pull.empty() - } - - // If unique option is enabled, check if the CID has been seen before. - // Note we need to do this here rather than before adding to the stream - // so that the unique check happens in the order that items are examined - // in the DAG. - if (isUnique) { - if (uniques.has(node.cid.toString())) { - // Mark this object as a duplicate so we can filter it out later - obj.isDuplicate = true - return pull.empty() - } - uniques.add(node.cid.toString()) - } - - const deferred = pullDefer.source() - - // Get this object's links - getLinks(ipfs, node.cid, (err, links) => { - if (err) { - if (err.code === 'ERR_NOT_FOUND') { - err.message = `Could not find object with CID: ${node.cid}` - } - return deferred.resolve(pull.error(err)) - } - - // Add to the stream each link, parent and the new depth - const vals = links.map(link => ({ - parent: node, - node: link, - depth: nextLevelDepth - })) - - deferred.resolve(pull.values(vals)) - }) - - return deferred - } - - return pullTraverse.depthFirst(root, traverseLevel) -} - -// Fetch a node from IPLD then get all its links -function getLinks (ipfs, cid, callback) { - ipfs._ipld.get(new CID(cid)) - .then(node => { - let links - if (DAGNode.isDAGNode(node)) { - links = node.Links.map(({ Name, Hash }) => { - return { name: Name, cid: new CID(Hash) } - }) - } else { - links = getNodeLinks(node) - } - callback(null, links) - }) - .catch(callback) -} - -// Recursively search the node for CIDs -function getNodeLinks (node, path = '') { - let links = [] - for (const [name, value] of Object.entries(node)) { - if (CID.isCID(value)) { - links.push({ - name: path + name, - cid: value - }) - } else if (typeof value === 'object') { - links = links.concat(getNodeLinks(value, path + name + '/')) - } - } - return links -} - -},{"./refs":661,"./utils":662,"cids":222,"ipld-dag-pb":745,"is-ipfs":775,"pull-cat":1465,"pull-defer":1467,"pull-stream":1495,"pull-traverse":1527}],660:[function(require,module,exports){ -'use strict' - -const toStream = require('pull-stream-to-stream') - -module.exports = function (self) { - return (ipfsPath, options) => { - return toStream.source(self.refsPullStream(ipfsPath, options)) - } -} - -},{"pull-stream-to-stream":1494}],661:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream') - -module.exports = function (self) { - return promisify((ipfsPath, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - pull( - self.refsPullStream(ipfsPath, options), - pull.collect((err, values) => { - if (err) { - return callback(err) - } - callback(null, values) - }) - ) - }) -} - -// Preset format strings -module.exports.Format = { - default: '', - edges: ' -> ' -} - -},{"promisify-es6":1443,"pull-stream":1495}],662:[function(require,module,exports){ -'use strict' - -const CID = require('cids') -const { Buffer } = require('buffer') -const { cidToString } = require('../../../utils/cid') -const toPullStream = require('async-iterator-to-pull-stream') - -const normalizePath = (path) => { - if (Buffer.isBuffer(path)) { - return new CID(path).toString() - } - if (CID.isCID(path)) { - return path.toString() - } - if (path.indexOf('/ipfs/') === 0) { - path = path.substring('/ipfs/'.length) - } - if (path.charAt(path.length - 1) === '/') { - path = path.substring(0, path.length - 1) - } - return path -} - -/** - * Parses chunker string into options used by DAGBuilder in ipfs-unixfs-engine - * - * - * @param {String} chunker Chunker algorithm supported formats: - * "size-{size}" - * "rabin" - * "rabin-{avg}" - * "rabin-{min}-{avg}-{max}" - * - * @return {Object} Chunker options for DAGBuilder - */ -const parseChunkerString = (chunker) => { - if (!chunker) { - return { - chunker: 'fixed' - } - } else if (chunker.startsWith('size-')) { - const sizeStr = chunker.split('-')[1] - const size = parseInt(sizeStr) - if (isNaN(size)) { - throw new Error('Chunker parameter size must be an integer') - } - return { - chunker: 'fixed', - chunkerOptions: { - maxChunkSize: size - } - } - } else if (chunker.startsWith('rabin')) { - return { - chunker: 'rabin', - chunkerOptions: parseRabinString(chunker) - } - } else { - throw new Error(`Unrecognized chunker option: ${chunker}`) - } -} - -/** - * Parses rabin chunker string - * - * @param {String} chunker Chunker algorithm supported formats: - * "rabin" - * "rabin-{avg}" - * "rabin-{min}-{avg}-{max}" - * - * @return {Object} rabin chunker options - */ -const parseRabinString = (chunker) => { - const options = {} - const parts = chunker.split('-') - switch (parts.length) { - case 1: - options.avgChunkSize = 262144 - break - case 2: - options.avgChunkSize = parseChunkSize(parts[1], 'avg') - break - case 4: - options.minChunkSize = parseChunkSize(parts[1], 'min') - options.avgChunkSize = parseChunkSize(parts[2], 'avg') - options.maxChunkSize = parseChunkSize(parts[3], 'max') - break - default: - throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"') - } - - return options -} - -const parseChunkSize = (str, name) => { - const size = parseInt(str) - if (isNaN(size)) { - throw new Error(`Chunker parameter ${name} must be an integer`) - } - - return size -} - -const mapFile = (options = {}) => { - return (file) => { - let size = 0 - let type = 'dir' - - if (file.unixfs && file.unixfs.type === 'file') { - size = file.unixfs.fileSize() - type = 'file' - } - - const output = { - hash: cidToString(file.cid, { base: options.cidBase }), - path: file.path, - name: file.name, - depth: file.path.split('/').length, - size, - type - } - - if (options.includeContent && file.unixfs && file.unixfs.type === 'file') { - output.content = toPullStream.source(file.content()) - } - - return output - } -} - -module.exports = { - normalizePath, - parseChunkSize, - parseRabinString, - parseChunkerString, - mapFile -} - -},{"../../../utils/cid":715,"async-iterator-to-pull-stream":86,"buffer":217,"cids":222}],663:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const setImmediate = require('async/setImmediate') -const pkgversion = require('../../../package.json').version - -module.exports = function id (self) { - return promisify((opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - setImmediate(() => callback(null, { - id: self._peerInfo.id.toB58String(), - publicKey: self._peerInfo.id.pubKey.bytes.toString('base64'), - addresses: self._peerInfo.multiaddrs - .toArray() - .map((ma) => ma.toString()) - .filter((ma) => ma.indexOf('ipfs') >= 0) - .sort(), - agentVersion: `js-ipfs/${pkgversion}`, - protocolVersion: '9000' - })) - }) -} - -},{"../../../package.json":629,"async/setImmediate":146,"promisify-es6":1443}],664:[function(require,module,exports){ -'use strict' - -exports.preStart = require('./pre-start') -exports.start = require('./start') -exports.stop = require('./stop') -exports.isOnline = require('./is-online') -exports.version = require('./version') -exports.id = require('./id') -exports.repo = require('./repo') -exports.init = require('./init') -exports.bootstrap = require('./bootstrap') -exports.config = require('./config') -exports.block = require('./block') -exports.object = require('./object') -exports.dag = require('./dag') -exports.libp2p = require('./libp2p') -exports.swarm = require('./swarm') -exports.ping = require('./ping') -exports.pingPullStream = require('./ping-pull-stream') -exports.pingReadableStream = require('./ping-readable-stream') -exports.pin = require('./pin') -exports.filesRegular = require('./files-regular') -exports.filesMFS = require('./files-mfs') -exports.bitswap = require('./bitswap') -exports.pubsub = require('./pubsub') -exports.dht = require('./dht') -exports.dns = require('./dns') -exports.key = require('./key') -exports.stats = require('./stats') -exports.resolve = require('./resolve') -exports.name = require('./name') - -},{"./bitswap":631,"./block":632,"./bootstrap":633,"./config":634,"./dag":635,"./dht":636,"./dns":637,"./files-mfs":638,"./files-regular":652,"./id":663,"./init":665,"./is-online":666,"./key":667,"./libp2p":668,"./name":670,"./object":672,"./pin":673,"./ping":681,"./ping-pull-stream":679,"./ping-readable-stream":680,"./pre-start":682,"./pubsub":683,"./repo":684,"./resolve":685,"./start":686,"./stats":687,"./stop":688,"./swarm":689,"./version":690}],665:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const peerId = require('peer-id') -const mergeOptions = require('merge-options') -const waterfall = require('async/waterfall') -const parallel = require('async/parallel') -const promisify = require('promisify-es6') -const defaultConfig = require('../runtime/config-nodejs.js') -const Keychain = require('libp2p-keychain') -const { - DAGNode -} = require('ipld-dag-pb') -const UnixFs = require('ipfs-unixfs') -const multicodec = require('multicodec') - -const IPNS = require('../ipns') -const OfflineDatastore = require('../ipns/routing/offline-datastore') - -const addDefaultAssets = require('./init-assets') - -module.exports = function init (self) { - return promisify((opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - const done = (err, res) => { - if (err) { - self.emit('error', err) - return callback(err) - } - - self.preStart((err) => { - if (err) { - self.emit('error', err) - return callback(err) - } - - self.state.initialized() - self.emit('init') - callback(null, res) - }) - } - - if (self.state.state() !== 'uninitialized') { - return done(new Error('Not able to init from state: ' + self.state.state())) - } - - self.state.init() - self.log('init') - - // An initialized, open repo was passed, use this one! - if (opts.repo) { - self._repo = opts.repo - return done(null, true) - } - - opts.emptyRepo = opts.emptyRepo || false - opts.bits = Number(opts.bits) || 2048 - opts.log = opts.log || function () {} - - const config = mergeOptions(defaultConfig(), self._options.config) - let privateKey - - waterfall([ - // Verify repo does not yet exist. - (cb) => self._repo.exists(cb), - (exists, cb) => { - self.log('repo exists?', exists) - if (exists === true) { - return cb(new Error('repo already exists')) - } - - if (opts.privateKey) { - self.log('using user-supplied private-key') - if (typeof opts.privateKey === 'object') { - cb(null, opts.privateKey) - } else { - peerId.createFromPrivKey(Buffer.from(opts.privateKey, 'base64'), cb) - } - } else { - // Generate peer identity keypair + transform to desired format + add to config. - opts.log(`generating ${opts.bits}-bit RSA keypair...`, false) - self.log('generating peer id: %s bits', opts.bits) - peerId.create({ bits: opts.bits }, cb) - } - }, - (peerId, cb) => { - self.log('identity generated') - config.Identity = { - PeerID: peerId.toB58String(), - PrivKey: peerId.privKey.bytes.toString('base64') - } - privateKey = peerId.privKey - if (opts.pass) { - config.Keychain = Keychain.generateOptions() - } - opts.log('done') - opts.log('peer identity: ' + config.Identity.PeerID) - - self._repo.init(config, cb) - }, - (_, cb) => self._repo.open(cb), - (cb) => { - self.log('repo opened') - if (opts.pass) { - self.log('creating keychain') - const keychainOptions = Object.assign({ passPhrase: opts.pass }, config.Keychain) - self._keychain = new Keychain(self._repo.keys, keychainOptions) - self._keychain.importPeer('self', { privKey: privateKey }, cb) - } else { - cb(null, true) - } - }, - // Setup the offline routing for IPNS. - // This is primarily used for offline ipns modifications, such as the initializeKeyspace feature. - (_, cb) => { - const offlineDatastore = new OfflineDatastore(self._repo) - - self._ipns = new IPNS(offlineDatastore, self._repo.datastore, self._peerInfo, self._keychain, self._options) - cb(null, true) - }, - // add empty unixfs dir object (go-ipfs assumes this exists) - (_, cb) => { - if (opts.emptyRepo) { - return cb(null, true) - } - - const tasks = [ - (cb) => { - waterfall([ - (cb) => { - try { - cb(null, DAGNode.create(new UnixFs('directory').marshal())) - } catch (err) { - cb(err) - } - }, - (node, cb) => self.dag.put(node, { - version: 0, - format: multicodec.DAG_PB, - hashAlg: multicodec.SHA2_256 - }).then( - (cid) => cb(null, cid), - (error) => cb(error) - ), - (cid, cb) => self._ipns.initializeKeyspace(privateKey, cid.toBaseEncodedString(), cb) - ], cb) - } - ] - - if (typeof addDefaultAssets === 'function') { - // addDefaultAssets is undefined on browsers. - // See package.json browser config - tasks.push((cb) => addDefaultAssets(self, opts.log, cb)) - } - - self.log('adding assets') - parallel(tasks, (err) => { - if (err) { - cb(err) - } else { - cb(null, true) - } - }) - } - ], done) - }) -} - -}).call(this,require("buffer").Buffer) -},{"../ipns":693,"../ipns/routing/offline-datastore":699,"../runtime/config-nodejs.js":705,"./init-assets":182,"async/parallel":141,"async/waterfall":152,"buffer":217,"ipfs-unixfs":592,"ipld-dag-pb":745,"libp2p-keychain":1086,"merge-options":1298,"multicodec":1325,"peer-id":1432,"promisify-es6":1443}],666:[function(require,module,exports){ -'use strict' - -module.exports = function isOnline (self) { - return () => { - return Boolean(self._bitswap && self.libp2p && self.libp2p.isStarted()) - } -} - -},{}],667:[function(require,module,exports){ -'use strict' - -// See https://github.com/ipfs/specs/tree/master/keystore - -const promisify = require('promisify-es6') - -module.exports = function key (self) { - return { - gen: promisify((name, opts, callback) => { - opts = opts || {} - self._keychain.createKey(name, opts.type, opts.size, callback) - }), - - info: promisify((name, callback) => { - self._keychain.findKeyByName(name, callback) - }), - - list: promisify((callback) => { - self._keychain.listKeys(callback) - }), - - rm: promisify((name, callback) => { - self._keychain.removeKey(name, callback) - }), - - rename: promisify((oldName, newName, callback) => { - self._keychain.renameKey(oldName, newName, (err, key) => { - if (err) return callback(err) - const result = { - was: oldName, - now: key.name, - id: key.id, - overwrite: false - } - callback(null, result) - }) - }), - - import: promisify((name, pem, password, callback) => { - self._keychain.importKey(name, pem, password, callback) - }), - - export: promisify((name, password, callback) => { - self._keychain.exportKey(name, password, callback) - }) - } -} - -},{"promisify-es6":1443}],668:[function(require,module,exports){ -'use strict' - -const get = require('dlv') -const mergeOptions = require('merge-options') -const errCode = require('err-code') -const ipnsUtils = require('../ipns/routing/utils') -const multiaddr = require('multiaddr') -const DelegatedPeerRouter = require('libp2p-delegated-peer-routing') -const DelegatedContentRouter = require('libp2p-delegated-content-routing') -const PubsubRouters = require('../runtime/libp2p-pubsub-routers-nodejs') - -module.exports = function libp2p (self, config) { - const options = self._options || {} - config = config || {} - - // Always create libp2p via a bundle function - const createBundle = typeof options.libp2p === 'function' - ? options.libp2p - : defaultBundle - - const { datastore } = self._repo - const peerInfo = self._peerInfo - const peerBook = self._peerInfoBook - const libp2p = createBundle({ options, config, datastore, peerInfo, peerBook }) - - libp2p.on('stop', () => { - // Clear our addresses so we can start clean - peerInfo.multiaddrs.clear() - }) - - libp2p.on('start', () => { - peerInfo.multiaddrs.forEach((ma) => { - self._print('Swarm listening on', ma.toString()) - }) - }) - - libp2p.on('peer:connect', peerInfo => peerBook.put(peerInfo)) - - return libp2p -} - -function defaultBundle ({ datastore, peerInfo, peerBook, options, config }) { - // Set up Delegate Routing based on the presence of Delegates in the config - let contentRouting - let peerRouting - const delegateHosts = get(options, 'config.Addresses.Delegates', - get(config, 'Addresses.Delegates', []) - ) - if (delegateHosts.length > 0) { - // Pick a random delegate host - const delegateString = delegateHosts[Math.floor(Math.random() * delegateHosts.length)] - const delegateAddr = multiaddr(delegateString).toOptions() - const delegatedApiOptions = { - host: delegateAddr.host, - // port is a string atm, so we need to convert for the check - protocol: parseInt(delegateAddr.port) === 443 ? 'https' : 'http', - port: delegateAddr.port - } - contentRouting = [new DelegatedContentRouter(peerInfo.id, delegatedApiOptions)] - peerRouting = [new DelegatedPeerRouter(delegatedApiOptions)] - } - - const getPubsubRouter = () => { - let router = get(config, 'Pubsub.Router', 'gossipsub') - - if (!router) { - router = 'gossipsub' - } - - if (!PubsubRouters[router]) { - throw errCode(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${router} router.`), 'ERR_NOT_SUPPORTED') - } - - return PubsubRouters[router] - } - - const libp2pDefaults = { - datastore, - peerInfo, - peerBook, - modules: { - contentRouting, - peerRouting, - pubsub: getPubsubRouter() - }, - config: { - peerDiscovery: { - mdns: { - enabled: get(options, 'config.Discovery.MDNS.Enabled', - get(config, 'Discovery.MDNS.Enabled', true)) - }, - webRTCStar: { - enabled: get(options, 'config.Discovery.webRTCStar.Enabled', - get(config, 'Discovery.webRTCStar.Enabled', true)) - }, - bootstrap: { - list: get(options, 'config.Bootstrap', - get(config, 'Bootstrap', [])) - } - }, - relay: { - enabled: get(options, 'relay.enabled', - get(config, 'relay.enabled', true)), - hop: { - enabled: get(options, 'relay.hop.enabled', - get(config, 'relay.hop.enabled', false)), - active: get(options, 'relay.hop.active', - get(config, 'relay.hop.active', false)) - } - }, - dht: { - kBucketSize: get(options, 'dht.kBucketSize', 20), - // enabled: !get(options, 'offline', false), // disable if offline, on by default - enabled: false, - randomWalk: { - enabled: false // disabled waiting for https://github.com/libp2p/js-libp2p-kad-dht/issues/86 - }, - validators: { - ipns: ipnsUtils.validator - }, - selectors: { - ipns: ipnsUtils.selector - } - }, - pubsub: { - enabled: get(config, 'Pubsub.Enabled', true) - } - }, - connectionManager: get(options, 'connectionManager', - { - maxPeers: get(config, 'Swarm.ConnMgr.HighWater'), - minPeers: get(config, 'Swarm.ConnMgr.LowWater') - }) - } - - const libp2pOptions = mergeOptions(libp2pDefaults, get(options, 'libp2p', {})) - // Required inline to reduce startup time - // Note: libp2p-nodejs gets replaced by libp2p-browser when webpacked/browserified - const Node = require('../runtime/libp2p-nodejs') - return new Node(libp2pOptions) -} - -},{"../ipns/routing/utils":701,"../runtime/libp2p-nodejs":709,"../runtime/libp2p-pubsub-routers-nodejs":710,"dlv":276,"err-code":315,"libp2p-delegated-content-routing":967,"libp2p-delegated-peer-routing":1002,"merge-options":1298,"multiaddr":1314}],669:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const errcode = require('err-code') -const promisify = require('promisify-es6') - -const IpnsPubsubDatastore = require('../ipns/routing/pubsub-datastore') - -const log = debug('ipfs:name-pubsub') -log.error = debug('ipfs:name-pubsub:error') - -// Is pubsub enabled -const isNamePubsubEnabled = (node) => { - try { - return Boolean(getPubsubRouting(node)) - } catch (err) { - return false - } -} - -// Get pubsub from IPNS routing -const getPubsubRouting = (node) => { - if (!node._ipns || !node._options.EXPERIMENTAL.ipnsPubsub) { - throw errcode(new Error('IPNS pubsub subsystem is not enabled'), 'ERR_IPNS_PUBSUB_NOT_ENABLED') - } - - // Only one store and it is pubsub - if (IpnsPubsubDatastore.isIpnsPubsubDatastore(node._ipns.routing)) { - return node._ipns.routing - } - - // Find in tiered - const pubsub = (node._ipns.routing.stores || []).find(s => IpnsPubsubDatastore.isIpnsPubsubDatastore(s)) - - if (!pubsub) { - throw errcode(new Error('IPNS pubsub datastore not found'), 'ERR_PUBSUB_DATASTORE_NOT_FOUND') - } - - return pubsub -} - -module.exports = function namePubsub (self) { - return { - /** - * Query the state of IPNS pubsub. - * - * @returns {Promise|void} - */ - state: promisify((callback) => { - callback(null, { - enabled: isNamePubsubEnabled(self) - }) - }), - /** - * Cancel a name subscription. - * - * @param {String} name subscription name. - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - cancel: promisify((name, callback) => { - let pubsub - try { - pubsub = getPubsubRouting(self) - } catch (err) { - return callback(err) - } - - pubsub.cancel(name, callback) - }), - /** - * Show current name subscriptions. - * - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - subs: promisify((callback) => { - let pubsub - try { - pubsub = getPubsubRouting(self) - } catch (err) { - return callback(err) - } - - pubsub.getSubscriptions(callback) - }) - } -} - -},{"../ipns/routing/pubsub-datastore":700,"debug":611,"err-code":315,"promisify-es6":1443}],670:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const promisify = require('promisify-es6') -const waterfall = require('async/waterfall') -const parallel = require('async/parallel') -const human = require('human-to-milliseconds') -const crypto = require('libp2p-crypto') -const errcode = require('err-code') -const mergeOptions = require('merge-options') -const mh = require('multihashes') -const isDomain = require('is-domain-name') - -const log = debug('ipfs:name') -log.error = debug('ipfs:name:error') - -const namePubsub = require('./name-pubsub') -const utils = require('../utils') -const path = require('../ipns/path') - -const keyLookup = (ipfsNode, kname, callback) => { - if (kname === 'self') { - return callback(null, ipfsNode._peerInfo.id.privKey) - } - - const pass = ipfsNode._options.pass - - waterfall([ - (cb) => ipfsNode._keychain.exportKey(kname, pass, cb), - (pem, cb) => crypto.keys.import(pem, pass, cb) - ], (err, privateKey) => { - if (err) { - log.error(err) - return callback(errcode(err, 'ERR_CANNOT_GET_KEY')) - } - - return callback(null, privateKey) - }) -} - -const appendRemainder = (cb, remainder) => { - return (err, result) => { - if (err) { - return cb(err) - } - if (remainder.length) { - return cb(null, result + '/' + remainder.join('/')) - } - return cb(null, result) - } -} - -/** - * @typedef { import("../index") } IPFS - */ - -/** - * IPNS - Inter-Planetary Naming System - * - * @param {IPFS} self - * @returns {Object} - */ -module.exports = function name (self) { - return { - /** - * IPNS is a PKI namespace, where names are the hashes of public keys, and - * the private key enables publishing new (signed) values. In both publish - * and resolve, the default name used is the node's own PeerID, - * which is the hash of its public key. - * - * @param {String} value ipfs path of the object to be published. - * @param {Object} options ipfs publish options. - * @param {boolean} options.resolve resolve given path before publishing. - * @param {String} options.lifetime time duration that the record will be valid for. - This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are - "ns", "ms", "s", "m", "h". Default is 24h. - * @param {String} options.ttl time duration this record should be cached for (NOT IMPLEMENTED YET). - * This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are - "ns", "ms", "s", "m", "h" (caution: experimental). - * @param {String} options.key name of the key to be used, as listed by 'ipfs key list -l'. - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - publish: promisify((value, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - const resolve = !(options.resolve === false) - const lifetime = options.lifetime || '24h' - const key = options.key || 'self' - - if (!self.isOnline()) { - return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR')) - } - - // TODO: params related logic should be in the core implementation - - // Normalize path value - try { - value = utils.normalizePath(value) - } catch (err) { - log.error(err) - return callback(err) - } - - let pubLifetime - try { - pubLifetime = human(lifetime) - - // Calculate lifetime with nanoseconds precision - pubLifetime = pubLifetime.toFixed(6) - } catch (err) { - log.error(err) - return callback(err) - } - - // TODO: ttl human for cache - - parallel([ - (cb) => keyLookup(self, key, cb), - // verify if the path exists, if not, an error will stop the execution - (cb) => resolve.toString() === 'true' ? path.resolvePath(self, value, cb) : cb() - ], (err, results) => { - if (err) { - log.error(err) - return callback(err) - } - - // Start publishing process - self._ipns.publish(results[0], value, pubLifetime, callback) - }) - }), - - /** - * Given a key, query the DHT for its best value. - * - * @param {String} name ipns name to resolve. Defaults to your node's peerID. - * @param {Object} options ipfs resolve options. - * @param {boolean} options.nocache do not use cached entries. - * @param {boolean} options.recursive resolve until the result is not an IPNS name. - * @param {function(Error)} [callback] - * @returns {Promise|void} - */ - resolve: promisify((name, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = mergeOptions({ - nocache: false, - recursive: true - }, options) - - const offline = self._options.offline - - // TODO: params related logic should be in the core implementation - if (offline && options.nocache) { - return callback(errcode(new Error('cannot specify both offline and nocache'), 'ERR_NOCACHE_AND_OFFLINE')) - } - - // Set node id as name for being resolved, if it is not received - if (!name) { - name = self._peerInfo.id.toB58String() - } - - if (!name.startsWith('/ipns/')) { - name = `/ipns/${name}` - } - - const [namespace, hash, ...remainder] = name.slice(1).split('/') - try { - mh.fromB58String(hash) - } catch (err) { - // lets check if we have a domain ex. /ipns/ipfs.io and resolve with dns - if (isDomain(hash)) { - return self.dns(hash, options, appendRemainder(callback, remainder)) - } - - log.error(err) - return callback(errcode(new Error('Invalid IPNS name'), 'ERR_IPNS_INVALID_NAME')) - } - - // multihash is valid lets resolve with IPNS - // IPNS resolve needs a online daemon - if (!self.isOnline() && !offline) { - return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR')) - } - - self._ipns.resolve(`/${namespace}/${hash}`, options, appendRemainder(callback, remainder)) - }), - pubsub: namePubsub(self) - } -} - -},{"../ipns/path":694,"../utils":714,"./name-pubsub":669,"async/parallel":141,"async/waterfall":152,"debug":611,"err-code":315,"human-to-milliseconds":447,"is-domain-name":770,"libp2p-crypto":905,"merge-options":1298,"multihashes":1331,"promisify-es6":1443}],671:[function(require,module,exports){ -'use strict' - -function fail () { - throw new Error('Key management requires \'--pass ...\' option') -} - -class NoKeychain { - static get options () { fail() } - - static generateOptions () { fail() } - - createKey () { fail() } - - listKeys () { fail() } - - findKeyById () { fail() } - - findKeyByName () { fail() } - - renameKey () { fail() } - - removeKey () { fail() } - - exportKey () { fail() } - - importKey () { fail() } - - importPeer () { fail() } - - get cms () { fail() } -} - -module.exports = NoKeychain - -},{}],672:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const waterfall = require('async/waterfall') -const parallel = require('async/parallel') -const setImmediate = require('async/setImmediate') -const promisify = require('promisify-es6') -const dagPB = require('ipld-dag-pb') -const DAGNode = dagPB.DAGNode -const DAGLink = dagPB.DAGLink -const CID = require('cids') -const mh = require('multihashes') -const multicodec = require('multicodec') -const Unixfs = require('ipfs-unixfs') -const errCode = require('err-code') - -function normalizeMultihash (multihash, enc) { - if (typeof multihash === 'string') { - if (enc === 'base58' || !enc) { - return multihash - } - - return Buffer.from(multihash, enc) - } else if (Buffer.isBuffer(multihash)) { - return multihash - } else if (CID.isCID(multihash)) { - return multihash.buffer - } else { - throw new Error('unsupported multihash') - } -} - -function parseBuffer (buf, encoding, callback) { - switch (encoding) { - case 'json': - return parseJSONBuffer(buf, callback) - case 'protobuf': - return parseProtoBuffer(buf, callback) - default: - callback(new Error(`unkown encoding: ${encoding}`)) - } -} - -function parseJSONBuffer (buf, callback) { - let data - let links - - try { - const parsed = JSON.parse(buf.toString()) - - links = (parsed.Links || []).map((link) => { - return new DAGLink( - link.Name || link.name, - link.Size || link.size, - mh.fromB58String(link.Hash || link.hash || link.multihash) - ) - }) - data = Buffer.from(parsed.Data) - } catch (err) { - return callback(new Error('failed to parse JSON: ' + err)) - } - - try { - callback(null, DAGNode.create(data, links)) - } catch (err) { - callback(err) - } -} - -function parseProtoBuffer (buf, callback) { - let obj - try { - obj = dagPB.util.deserialize(buf) - } catch (err) { - return callback(err) - } - callback(null, obj) -} - -function findLinks (node, links = []) { - for (const key in node) { - const val = node[key] - - if (key === '/' && Object.keys(node).length === 1) { - try { - links.push(new DAGLink('', 0, new CID(val))) - continue - } catch (_) { - // not a CID - } - } - - if (CID.isCID(val)) { - links.push(new DAGLink('', 0, val)) - - continue - } - - if (Array.isArray(val)) { - findLinks(val, links) - } - - if (typeof val === 'object' && !(val instanceof String)) { - findLinks(val, links) - } - } - - return links -} - -module.exports = function object (self) { - function editAndSave (edit) { - return (multihash, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - waterfall([ - (cb) => { - self.object.get(multihash, options, cb) - }, - (node, cb) => { - // edit applies the edit func passed to - // editAndSave - edit(node, (err, node) => { - if (err) { - return cb(err) - } - - self._ipld.put(node, multicodec.DAG_PB, { - cidVersion: 0, - hashAlg: multicodec.SHA2_256 - }).then( - (cid) => { - if (options.preload !== false) { - self._preload(cid) - } - - cb(null, cid) - }, - (error) => cb(error) - ) - }) - } - ], callback) - } - } - - return { - new: promisify((template, options, callback) => { - if (typeof template === 'function') { - callback = template - template = undefined - options = {} - } - - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - let data - - if (template) { - if (template !== 'unixfs-dir') { - return setImmediate(() => callback(new Error('unknown template'))) - } - data = (new Unixfs('directory')).marshal() - } else { - data = Buffer.alloc(0) - } - - let node - - try { - node = DAGNode.create(data) - } catch (err) { - return callback(err) - } - - self._ipld.put(node, multicodec.DAG_PB, { - cidVersion: 0, - hashAlg: multicodec.SHA2_256 - }).then( - (cid) => { - if (options.preload !== false) { - self._preload(cid) - } - - callback(null, cid) - }, - (error) => callback(error) - ) - }), - put: promisify((obj, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - const encoding = options.enc - let node - - if (Buffer.isBuffer(obj)) { - if (encoding) { - parseBuffer(obj, encoding, (err, _node) => { - if (err) { - return callback(err) - } - node = _node - next() - }) - } else { - try { - node = DAGNode.create(obj) - } catch (err) { - return callback(err) - } - - next() - } - } else if (DAGNode.isDAGNode(obj)) { - // already a dag node - node = obj - next() - } else if (typeof obj === 'object') { - try { - node = DAGNode.create(obj.Data, obj.Links) - } catch (err) { - return callback(err) - } - - next() - } else { - return callback(new Error('obj not recognized')) - } - - function next () { - self._gcLock.readLock((cb) => { - self._ipld.put(node, multicodec.DAG_PB, { - cidVersion: 0, - hashAlg: multicodec.SHA2_256 - }).then( - (cid) => { - if (options.preload !== false) { - self._preload(cid) - } - - cb(null, cid) - }, - cb - ) - }, callback) - } - }), - - get: promisify((multihash, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - let mh, cid - - try { - mh = normalizeMultihash(multihash, options.enc) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_MULTIHASH'))) - } - - try { - cid = new CID(mh) - } catch (err) { - return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID'))) - } - - if (options.cidVersion === 1) { - cid = cid.toV1() - } - - if (options.preload !== false) { - self._preload(cid) - } - - self._ipld.get(cid).then( - (node) => callback(null, node), - (error) => callback(error) - ) - }), - - data: promisify((multihash, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - self.object.get(multihash, options, (err, node) => { - if (err) { - return callback(err) - } - - callback(null, node.Data) - }) - }), - - links: promisify((multihash, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - const cid = new CID(multihash) - - self.dag.get(cid, options, (err, result) => { - if (err) { - return callback(err) - } - - if (cid.codec === 'raw') { - return callback(null, []) - } - - if (cid.codec === 'dag-pb') { - return callback(null, result.value.Links) - } - - if (cid.codec === 'dag-cbor') { - const links = findLinks(result) - - return callback(null, links) - } - - callback(new Error(`Cannot resolve links from codec ${cid.codec}`)) - }) - }), - - stat: promisify((multihash, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - waterfall([ - (cb) => self.object.get(multihash, options, cb), - (node, cb) => { - cb(null, { - node, - serialized: dagPB.util.serialize(node) - }) - }, - ({ node, serialized }, cb) => { - parallel({ - serialized: (next) => next(null, serialized), - cid: (next) => dagPB.util.cid(serialized, { - cidVersion: 0 - }).then((cid) => next(null, cid), next), - node: (next) => next(null, node) - }, cb) - } - ], (err, result) => { - if (err) { - return callback(err) - } - - const blockSize = result.serialized.length - const linkLength = result.node.Links.reduce((a, l) => a + l.Tsize, 0) - - callback(null, { - Hash: result.cid.toBaseEncodedString(), - NumLinks: result.node.Links.length, - BlockSize: blockSize, - LinksSize: blockSize - result.node.Data.length, - DataSize: result.node.Data.length, - CumulativeSize: blockSize + linkLength - }) - }) - }), - - patch: promisify({ - addLink (multihash, link, options, callback) { - editAndSave((node, cb) => { - DAGNode.addLink(node, link).then((node) => { - cb(null, node) - }, cb) - })(multihash, options, callback) - }, - - rmLink (multihash, linkRef, options, callback) { - editAndSave((node, cb) => { - linkRef = linkRef.Name || linkRef.name - - try { - node = DAGNode.rmLink(node, linkRef) - } catch (err) { - return cb(err) - } - - cb(null, node) - })(multihash, options, callback) - }, - - appendData (multihash, data, options, callback) { - editAndSave((node, cb) => { - const newData = Buffer.concat([node.Data, data]) - - try { - node = DAGNode.create(newData, node.Links) - } catch (err) { - return cb(err) - } - - cb(null, node) - })(multihash, options, callback) - }, - - setData (multihash, data, options, callback) { - editAndSave((node, cb) => { - try { - node = DAGNode.create(data, node.Links) - } catch (err) { - return cb(err) - } - - cb(null, node) - })(multihash, options, callback) - } - }) - } -} - -}).call(this,require("buffer").Buffer) -},{"async/parallel":141,"async/setImmediate":146,"async/waterfall":152,"buffer":217,"cids":222,"err-code":315,"ipfs-unixfs":592,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331,"promisify-es6":1443}],673:[function(require,module,exports){ -/* eslint max-nested-callbacks: ["error", 8] */ -'use strict' - -const promisify = require('promisify-es6') -const CID = require('cids') -const map = require('async/map') -const mapSeries = require('async/mapSeries') -const waterfall = require('async/waterfall') -const setImmediate = require('async/setImmediate') -const errCode = require('err-code') -const multibase = require('multibase') - -const { resolvePath } = require('../utils') -const PinManager = require('./pin/pin-manager') -const PinTypes = PinManager.PinTypes - -function toB58String (hash) { - return new CID(hash).toBaseEncodedString() -} - -module.exports = (self) => { - const dag = self.dag - const pinManager = new PinManager(self._repo, dag) - - const pin = { - add: promisify((paths, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - const recursive = options.recursive == null ? true : options.recursive - - resolvePath(self.object, paths, (err, mhs) => { - if (err) { return callback(err) } - - const pinAdd = (pinComplete) => { - // verify that each hash can be pinned - map(mhs, (multihash, cb) => { - const cid = new CID(multihash) - const key = cid.toBaseEncodedString() - - if (recursive) { - if (pinManager.recursivePins.has(key)) { - // it's already pinned recursively - return cb(null, key) - } - - // entire graph of nested links should be pinned, - // so make sure we have all the objects - pinManager.fetchCompleteDag(key, { preload: options.preload }, (err) => { - if (err) { return cb(err) } - // found all objects, we can add the pin - return cb(null, key) - }) - } else { - if (pinManager.recursivePins.has(key)) { - // recursive supersedes direct, can't have both - return cb(new Error(`${key} already pinned recursively`)) - } - if (pinManager.directPins.has(key)) { - // already directly pinned - return cb(null, key) - } - - // make sure we have the object - dag.get(cid, { preload: options.preload }, (err) => { - if (err) { return cb(err) } - // found the object, we can add the pin - return cb(null, key) - }) - } - }, (err, results) => { - if (err) { return pinComplete(err) } - - // update the pin sets in memory - const pinset = recursive ? pinManager.recursivePins : pinManager.directPins - results.forEach(key => pinset.add(key)) - - // persist updated pin sets to datastore - pinManager.flushPins((err, root) => { - if (err) { return pinComplete(err) } - pinComplete(null, results.map(hash => ({ hash }))) - }) - }) - } - - // When adding a file, we take a lock that gets released after pinning - // is complete, so don't take a second lock here - const lock = options.lock !== false - if (lock) { - self._gcLock.readLock(pinAdd, callback) - } else { - pinAdd(callback) - } - }) - }), - - rm: promisify((paths, options, callback) => { - if (typeof options === 'function') { - callback = options - } - - options = options || {} - - const recursive = options.recursive == null ? true : options.recursive - - if (options.cidBase && !multibase.names.includes(options.cidBase)) { - return setImmediate(() => { - callback(errCode(new Error('invalid multibase'), 'ERR_INVALID_MULTIBASE')) - }) - } - - resolvePath(self.object, paths, (err, mhs) => { - if (err) { return callback(err) } - - self._gcLock.readLock((lockCb) => { - // verify that each hash can be unpinned - map(mhs, (multihash, cb) => { - pinManager.isPinnedWithType(multihash, PinTypes.all, (err, res) => { - if (err) { return cb(err) } - const { pinned, reason } = res - const key = toB58String(multihash) - if (!pinned) { - return cb(new Error(`${key} is not pinned`)) - } - - switch (reason) { - case (PinTypes.recursive): - if (recursive) { - return cb(null, key) - } else { - return cb(new Error(`${key} is pinned recursively`)) - } - case (PinTypes.direct): - return cb(null, key) - default: - return cb(new Error( - `${key} is pinned indirectly under ${reason}` - )) - } - }) - }, (err, results) => { - if (err) { return lockCb(err) } - - // update the pin sets in memory - results.forEach(key => { - if (recursive && pinManager.recursivePins.has(key)) { - pinManager.recursivePins.delete(key) - } else { - pinManager.directPins.delete(key) - } - }) - - // persist updated pin sets to datastore - pinManager.flushPins((err, root) => { - if (err) { return lockCb(err) } - self.log(`Removed pins: ${results}`) - lockCb(null, results.map(hash => ({ hash }))) - }) - }) - }, callback) - }) - }), - - ls: promisify((paths, options, callback) => { - let type = PinTypes.all - if (typeof paths === 'function') { - callback = paths - options = {} - paths = null - } - if (typeof options === 'function') { - callback = options - } - if (paths && paths.type) { - options = paths - paths = null - } - - options = options || {} - - if (options.type) { - type = options.type - if (typeof options.type === 'string') { - type = options.type.toLowerCase() - } - const err = PinManager.checkPinType(type) - if (err) { - return setImmediate(() => callback(err)) - } - } - - if (paths) { - // check the pinned state of specific hashes - waterfall([ - (cb) => resolvePath(self.object, paths, cb), - (hashes, cb) => mapSeries(hashes, (hash, done) => pinManager.isPinnedWithType(hash, type, done), cb), - (results, cb) => { - results = results - .filter(result => result.pinned) - .map(({ key, reason }) => { - switch (reason) { - case PinTypes.direct: - case PinTypes.recursive: - return { - hash: key, - type: reason - } - default: - return { - hash: key, - type: `${PinTypes.indirect} through ${reason}` - } - } - }) - - if (!results.length) { - return cb(new Error(`path '${paths}' is not pinned`)) - } - - cb(null, results) - } - ], (err, results) => err ? callback(err) : callback(null, results)) // we don't want results equal [undefined] when err is present - } else { - // show all pinned items of type - let pins = [] - - if (type === PinTypes.direct || type === PinTypes.all) { - pins = pins.concat( - Array.from(pinManager.directPins).map(hash => ({ - type: PinTypes.direct, - hash - })) - ) - } - - if (type === PinTypes.recursive || type === PinTypes.all) { - pins = pins.concat( - Array.from(pinManager.recursivePins).map(hash => ({ - type: PinTypes.recursive, - hash - })) - ) - } - - if (type === PinTypes.indirect || type === PinTypes.all) { - pinManager.getIndirectKeys(options, (err, indirects) => { - if (err) { return callback(err) } - pins = pins - // if something is pinned both directly and indirectly, - // report the indirect entry - .filter(({ hash }) => - !indirects.includes(hash) || - (indirects.includes(hash) && !pinManager.directPins.has(hash)) - ) - .concat(indirects.map(hash => ({ - type: PinTypes.indirect, - hash - }))) - return callback(null, pins) - }) - } else { - callback(null, pins) - } - } - }), - - _isPinnedWithType: promisify(pinManager.isPinnedWithType.bind(pinManager)), - _getInternalBlocks: promisify(pinManager.getInternalBlocks.bind(pinManager)), - _load: promisify(pinManager.load.bind(pinManager)) - } - - return pin -} - -},{"../utils":714,"./pin/pin-manager":676,"async/map":137,"async/mapSeries":139,"async/setImmediate":146,"async/waterfall":152,"cids":222,"err-code":315,"multibase":1322,"promisify-es6":1443}],674:[function(require,module,exports){ -'use strict' - -const pull = require('pull-stream/pull') -const pullThrough = require('pull-stream/throughs/through') -const pullAsyncMap = require('pull-stream/throughs/async-map') -const Mutex = require('../../../utils/mutex') -const log = require('debug')('ipfs:gc:lock') - -class GCLock { - constructor (repoOwner, options = {}) { - this.mutex = new Mutex(repoOwner, { ...options, log }) - } - - readLock (lockedFn, cb) { - return this.mutex.readLock(lockedFn, cb) - } - - writeLock (lockedFn, cb) { - return this.mutex.writeLock(lockedFn, cb) - } - - pullReadLock (lockedPullFn) { - return this.pullLock('readLock', lockedPullFn) - } - - pullWriteLock (lockedPullFn) { - return this.pullLock('writeLock', lockedPullFn) - } - - pullLock (type, lockedPullFn) { - const pullLocker = new PullLocker(this.mutex, type) - - return pull( - pullLocker.take(), - lockedPullFn(), - pullLocker.release() - ) - } -} - -class PullLocker { - constructor (mutex, type) { - this.mutex = mutex - this.type = type - - // The function to call to release the lock. It is set when the lock is taken - this.releaseLock = null - } - - take () { - return pullAsyncMap((i, cb) => { - // Check if the lock has already been acquired. - // Note: new items will only come through the pull stream once the first - // item has acquired a lock. - if (this.releaseLock) { - // The lock has been acquired so return immediately - return cb(null, i) - } - - // Request the lock - this.mutex[this.type]() - .then(release => { - // Save the release function to be called when the stream completes - this.releaseLock = release - - // The lock has been granted, so run the locked piece of code - cb(null, i) - }, cb) - }) - } - - // Releases the lock - release () { - return pullThrough(null, (err) => { - // When the stream completes, release the lock - this.releaseLock(err) - }) - } -} - -module.exports = GCLock - -},{"../../../utils/mutex":716,"debug":611,"pull-stream/pull":1496,"pull-stream/throughs/async-map":1513,"pull-stream/throughs/through":1521}],675:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const promisify = require('promisify-es6') -const CID = require('cids') -const base32 = require('base32.js') -const parallel = require('async/parallel') -const mapLimit = require('async/mapLimit') -const expErr = require('explain-error') -const { cidToString } = require('../../../utils/cid') -const log = require('debug')('ipfs:gc') -// TODO: Use exported key from root when upgraded to ipfs-mfs@>=13 -// https://github.com/ipfs/js-ipfs-mfs/pull/58 -const { MFS_ROOT_KEY } = require('ipfs-mfs/src/core/utils/constants') - -// Limit on the number of parallel block remove operations -const BLOCK_RM_CONCURRENCY = 256 - -// Perform mark and sweep garbage collection -module.exports = function gc (self) { - return promisify((callback) => { - const start = Date.now() - log('Creating set of marked blocks') - - self._gcLock.writeLock((lockCb) => { - parallel([ - // Get all blocks keys from the blockstore - (cb) => self._repo.blocks.query({ keysOnly: true }, cb), - // Mark all blocks that are being used - (cb) => createMarkedSet(self, cb) - ], (err, [blockKeys, markedSet]) => { - if (err) { - log('GC failed to fetch all block keys and created marked set', err) - return lockCb(err) - } - - // Delete blocks that are not being used - deleteUnmarkedBlocks(self, markedSet, blockKeys, (err, res) => { - log(`Complete (${Date.now() - start}ms)`) - - if (err) { - log('GC failed to delete unmarked blocks', err) - return lockCb(err) - } - - lockCb(null, res) - }) - }) - }, callback) - }) -} - -// Get Set of CIDs of blocks to keep -function createMarkedSet (ipfs, callback) { - parallel([ - // All pins, direct and indirect - (cb) => ipfs.pin.ls((err, pins) => { - if (err) { - return cb(expErr(err, 'Could not list pinned blocks')) - } - log(`Found ${pins.length} pinned blocks`) - const cids = pins.map(p => new CID(p.hash)) - // log(' ' + cids.join('\n ')) - cb(null, cids) - }), - - // Blocks used internally by the pinner - (cb) => ipfs.pin._getInternalBlocks((err, cids) => { - if (err) { - return cb(expErr(err, 'Could not list pinner internal blocks')) - } - log(`Found ${cids.length} pinner internal blocks`) - // log(' ' + cids.join('\n ')) - cb(null, cids) - }), - - // The MFS root and all its descendants - (cb) => ipfs._repo.root.get(MFS_ROOT_KEY, (err, mh) => { - if (err) { - if (err.code === 'ERR_NOT_FOUND') { - log('No blocks in MFS') - return cb(null, []) - } - return cb(expErr(err, 'Could not get MFS root from datastore')) - } - - getDescendants(ipfs, new CID(mh), cb) - }) - ], (err, res) => { - if (err) { - return callback(err) - } - - const cids = [].concat(...res).map(cid => cidToString(cid, { base: 'base32' })) - return callback(null, new Set(cids)) - }) -} - -// Recursively get descendants of the given CID -function getDescendants (ipfs, cid, callback) { - ipfs.refs(cid, { recursive: true }, (err, refs) => { - if (err) { - return callback(expErr(err, 'Could not get MFS root descendants from store')) - } - const cids = [cid, ...refs.map(r => new CID(r.ref))] - log(`Found ${cids.length} MFS blocks`) - // log(' ' + cids.join('\n ')) - callback(null, cids) - }) -} - -// Delete all blocks that are not marked as in use -function deleteUnmarkedBlocks (ipfs, markedSet, blockKeys, callback) { - // Iterate through all blocks and find those that are not in the marked set - // The blockKeys variable has the form [ { key: Key() }, { key: Key() }, ... ] - const unreferenced = [] - const res = [] - let errCount = 0 - for (const { key: k } of blockKeys) { - try { - const cid = dsKeyToCid(k) - const b32 = cid.toV1().toString('base32') - if (!markedSet.has(b32)) { - unreferenced.push(cid) - } - } catch (err) { - errCount++ - const msg = `Could not convert block with key '${k}' to CID` - log(msg, err) - res.push({ err: new Error(msg + `: ${err.message}`) }) - } - } - - const msg = `Marked set has ${markedSet.size} unique blocks. Blockstore has ${blockKeys.length} blocks. ` + - `Deleting ${unreferenced.length} blocks.` + (errCount ? ` (${errCount} errors)` : '') - log(msg) - // log(' ' + unreferenced.join('\n ')) - - mapLimit(unreferenced, BLOCK_RM_CONCURRENCY, (cid, cb) => { - // Delete blocks from blockstore - ipfs._repo.blocks.delete(cid, (err) => { - const res = { - cid, - err: err && new Error(`Could not delete block with CID ${cid}: ${err.message}`) - } - cb(null, res) - }) - }, (_, delRes) => { - callback(null, res.concat(delRes)) - }) -} - -// TODO: Use exported utility when upgrade to ipfs-repo@>=0.27.1 -// https://github.com/ipfs/js-ipfs-repo/pull/206 -function dsKeyToCid (key) { - // Block key is of the form / - const decoder = new base32.Decoder() - const buff = decoder.write(key.toString().slice(1)).finalize() - return new CID(Buffer.from(buff)) -} - -}).call(this,require("buffer").Buffer) -},{"../../../utils/cid":715,"async/mapLimit":138,"async/parallel":141,"base32.js":160,"buffer":217,"cids":222,"debug":611,"explain-error":372,"ipfs-mfs/src/core/utils/constants":508,"promisify-es6":1443}],676:[function(require,module,exports){ -(function (Buffer){ -/* eslint max-nested-callbacks: ["error", 8] */ -'use strict' - -const { DAGNode, DAGLink } = require('ipld-dag-pb') -const CID = require('cids') -const series = require('async/series') -const parallel = require('async/parallel') -const eachLimit = require('async/eachLimit') -const waterfall = require('async/waterfall') -const detectLimit = require('async/detectLimit') -const queue = require('async/queue') -const { Key } = require('interface-datastore') -const errCode = require('err-code') -const multicodec = require('multicodec') -const debug = require('debug') -const { cidToString } = require('../../../utils/cid') - -const createPinSet = require('./pin-set') - -// arbitrary limit to the number of concurrent dag operations -const concurrencyLimit = 300 -const PIN_DS_KEY = new Key('/local/pins') - -function invalidPinTypeErr (type) { - const errMsg = `Invalid type '${type}', must be one of {direct, indirect, recursive, all}` - return errCode(new Error(errMsg), 'ERR_INVALID_PIN_TYPE') -} - -const PinTypes = { - direct: 'direct', - recursive: 'recursive', - indirect: 'indirect', - all: 'all' -} - -class PinManager { - constructor (repo, dag) { - this.repo = repo - this.dag = dag - this.log = debug('ipfs:pin') - this.pinset = createPinSet(dag) - this.directPins = new Set() - this.recursivePins = new Set() - } - - _walkDag ({ cid, preload = false, onCid = () => {} }, cb) { - const q = queue(({ cid }, done) => { - this.dag.get(cid, { preload }, (err, result) => { - if (err) { - return done(err) - } - - onCid(cid) - - if (result.value.Links) { - q.push(result.value.Links.map(link => ({ - cid: link.Hash - }))) - } - - done() - }) - }, concurrencyLimit) - q.drain = () => { - cb() - } - q.error = (err) => { - q.kill() - cb(err) - } - q.push({ cid }) - } - - directKeys () { - return Array.from(this.directPins, key => new CID(key).buffer) - } - - recursiveKeys () { - return Array.from(this.recursivePins, key => new CID(key).buffer) - } - - getIndirectKeys ({ preload }, callback) { - const indirectKeys = new Set() - eachLimit(this.recursiveKeys(), concurrencyLimit, (multihash, cb) => { - this._walkDag({ - cid: new CID(multihash), - preload: preload || false, - onCid: (cid) => { - cid = cid.toString() - - // recursive pins pre-empt indirect pins - if (!this.recursivePins.has(cid)) { - indirectKeys.add(cid) - } - } - }, cb) - }, (err) => { - if (err) { return callback(err) } - callback(null, Array.from(indirectKeys)) - }) - } - - // Encode and write pin key sets to the datastore: - // a DAGLink for each of the recursive and direct pinsets - // a DAGNode holding those as DAGLinks, a kind of root pin - flushPins (callback) { - let dLink, rLink, root - series([ - // create a DAGLink to the node with direct pins - cb => waterfall([ - cb => this.pinset.storeSet(this.directKeys(), cb), - ({ node, cid }, cb) => { - try { - cb(null, new DAGLink(PinTypes.direct, node.size, cid)) - } catch (err) { - cb(err) - } - }, - (link, cb) => { dLink = link; cb(null) } - ], cb), - - // create a DAGLink to the node with recursive pins - cb => waterfall([ - cb => this.pinset.storeSet(this.recursiveKeys(), cb), - ({ node, cid }, cb) => { - try { - cb(null, new DAGLink(PinTypes.recursive, node.size, cid)) - } catch (err) { - cb(err) - } - }, - (link, cb) => { rLink = link; cb(null) } - ], cb), - - // the pin-set nodes link to a special 'empty' node, so make sure it exists - cb => { - let empty - - try { - empty = DAGNode.create(Buffer.alloc(0)) - } catch (err) { - return cb(err) - } - - this.dag.put(empty, { - version: 0, - format: multicodec.DAG_PB, - hashAlg: multicodec.SHA2_256, - preload: false - }, cb) - }, - - // create a root node with DAGLinks to the direct and recursive DAGs - cb => { - let node - - try { - node = DAGNode.create(Buffer.alloc(0), [dLink, rLink]) - } catch (err) { - return cb(err) - } - - root = node - this.dag.put(root, { - version: 0, - format: multicodec.DAG_PB, - hashAlg: multicodec.SHA2_256, - preload: false - }, (err, cid) => { - if (!err) { - root.multihash = cid.buffer - } - cb(err) - }) - }, - - // save root to datastore under a consistent key - cb => this.repo.datastore.put(PIN_DS_KEY, root.multihash, cb) - ], (err, res) => { - if (err) { return callback(err) } - this.log(`Flushed pins with root: ${root}`) - return callback(null, root) - }) - } - - load (callback) { - waterfall([ - (cb) => this.repo.datastore.has(PIN_DS_KEY, cb), - (has, cb) => has ? cb() : cb(new Error('No pins to load')), - (cb) => this.repo.datastore.get(PIN_DS_KEY, cb), - (mh, cb) => { - this.dag.get(new CID(mh), '', { preload: false }, cb) - } - ], (err, pinRoot) => { - if (err) { - if (err.message === 'No pins to load') { - this.log('No pins to load') - return callback() - } else { - return callback(err) - } - } - - parallel([ - cb => this.pinset.loadSet(pinRoot.value, PinTypes.recursive, cb), - cb => this.pinset.loadSet(pinRoot.value, PinTypes.direct, cb) - ], (err, keys) => { - if (err) { return callback(err) } - const [rKeys, dKeys] = keys - - this.directPins = new Set(dKeys.map(k => cidToString(k))) - this.recursivePins = new Set(rKeys.map(k => cidToString(k))) - - this.log('Loaded pins from the datastore') - return callback(null) - }) - }) - } - - isPinnedWithType (multihash, type, callback) { - const key = cidToString(multihash) - const { recursive, direct, all } = PinTypes - - // recursive - if ((type === recursive || type === all) && this.recursivePins.has(key)) { - return callback(null, { - key, - pinned: true, - reason: recursive - }) - } - - if (type === recursive) { - return callback(null, { - key, - pinned: false - }) - } - - // direct - if ((type === direct || type === all) && this.directPins.has(key)) { - return callback(null, { - key, - pinned: true, - reason: direct - }) - } - - if (type === direct) { - return callback(null, { - key, - pinned: false - }) - } - - // indirect (default) - // check each recursive key to see if multihash is under it - // arbitrary limit, enables handling 1000s of pins. - detectLimit(this.recursiveKeys().map(key => new CID(key)), concurrencyLimit, (cid, cb) => { - waterfall([ - (done) => this.dag.get(cid, '', { preload: false }, done), - (result, done) => done(null, result.value), - (node, done) => this.pinset.hasDescendant(node, key, done) - ], cb) - }, (err, cid) => callback(err, { - key, - pinned: Boolean(cid), - reason: cid - })) - } - - // Gets CIDs of blocks used internally by the pinner - getInternalBlocks (callback) { - this.repo.datastore.get(PIN_DS_KEY, (err, mh) => { - if (err) { - if (err.code === 'ERR_NOT_FOUND') { - this.log('No pinned blocks') - return callback(null, []) - } - return callback(new Error(`Could not get pin sets root from datastore: ${err.message}`)) - } - - const cid = new CID(mh) - this.dag.get(cid, '', { preload: false }, (err, obj) => { - if (err) { - return callback(new Error(`Could not get pin sets from store: ${err.message}`)) - } - - // The pinner stores an object that has two links to pin sets: - // 1. The directly pinned CIDs - // 2. The recursively pinned CIDs - // If large enough, these pin sets may have links to buckets to hold - // the pins - this.pinset.getInternalCids(obj.value, (err, cids) => { - if (err) { - return callback(new Error(`Could not get pinner internal cids: ${err.message}`)) - } - - callback(null, cids.concat(cid)) - }) - }) - }) - } - - fetchCompleteDag (cid, options, callback) { - this._walkDag({ - cid, - preload: options.preload - }, callback) - } - - // Returns an error if the pin type is invalid - static checkPinType (type) { - if (typeof type !== 'string' || !Object.keys(PinTypes).includes(type)) { - return invalidPinTypeErr(type) - } - } -} - -PinManager.PinTypes = PinTypes - -module.exports = PinManager - -}).call(this,require("buffer").Buffer) -},{"../../../utils/cid":715,"./pin-set":677,"async/detectLimit":105,"async/eachLimit":107,"async/parallel":141,"async/queue":142,"async/series":145,"async/waterfall":152,"buffer":217,"cids":222,"debug":611,"err-code":315,"interface-datastore":458,"ipld-dag-pb":745,"multicodec":1325}],677:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const multihashes = require('multihashes') -const CID = require('cids') -const protobuf = require('protons') -const fnv1a = require('fnv1a') -const varint = require('varint') -const { DAGNode, DAGLink } = require('ipld-dag-pb') -const multicodec = require('multicodec') -const someSeries = require('async/someSeries') -const eachSeries = require('async/eachSeries') -const eachOfSeries = require('async/eachOfSeries') - -const pbSchema = require('./pin.proto') - -const emptyKeyHash = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n' -const emptyKey = multihashes.fromB58String(emptyKeyHash) -const defaultFanout = 256 -const maxItems = 8192 -const pb = protobuf(pbSchema) - -function toB58String (hash) { - return new CID(hash).toBaseEncodedString() -} - -function readHeader (rootNode) { - // rootNode.data should be a buffer of the format: - // < varint(headerLength) | header | itemData... > - const rootData = rootNode.Data - const hdrLength = varint.decode(rootData) - const vBytes = varint.decode.bytes - if (vBytes <= 0) { - throw new Error('Invalid Set header length') - } - if (vBytes + hdrLength > rootData.length) { - throw new Error('Impossibly large set header length') - } - const hdrSlice = rootData.slice(vBytes, hdrLength + vBytes) - const header = pb.Set.decode(hdrSlice) - if (header.version !== 1) { - throw new Error(`Unsupported Set version: ${header.version}`) - } - if (header.fanout > rootNode.Links.length) { - throw new Error('Impossibly large fanout') - } - return { - header: header, - data: rootData.slice(hdrLength + vBytes) - } -} - -function hash (seed, key) { - const buf = Buffer.alloc(4) - buf.writeUInt32LE(seed, 0) - const data = Buffer.concat([ - buf, Buffer.from(toB58String(key)) - ]) - return fnv1a(data.toString('binary')) -} - -exports = module.exports = function (dag) { - const pinSet = { - // should this be part of `object` API? - hasDescendant: (root, childhash, callback) => { - const seen = {} - - if (CID.isCID(childhash) || Buffer.isBuffer(childhash)) { - childhash = toB58String(childhash) - } - - return searchChildren(root, callback) - - function searchChildren (root, cb) { - someSeries(root.Links, (link, done) => { - const cid = link.Hash - const bs58Link = toB58String(cid) - - if (bs58Link === childhash) { - return done(null, true) - } - - if (bs58Link in seen) { - return done(null, false) - } - - seen[bs58Link] = true - - dag.get(cid, '', { preload: false }, (err, res) => { - if (err) { - return done(err) - } - - searchChildren(res.value, done) - }) - }, cb) - } - }, - - storeSet: (keys, callback) => { - const pins = keys.map(key => { - if (typeof key === 'string' || Buffer.isBuffer(key)) { - key = new CID(key) - } - - return { - key: key, - data: null - } - }) - - pinSet.storeItems(pins, (err, rootNode) => { - if (err) { return callback(err) } - - dag.put(rootNode, { - version: 0, - format: multicodec.DAG_PB, - hashAlg: multicodec.SHA2_256, - preload: false - }, (err, cid) => { - if (err) { return callback(err, cid) } - callback(null, { node: rootNode, cid }) - }) - }) - }, - - storeItems: (items, callback) => { - return storePins(items, 0, callback) - - function storePins (pins, depth, storePinsCb) { - const pbHeader = pb.Set.encode({ - version: 1, - fanout: defaultFanout, - seed: depth - }) - const headerBuf = Buffer.concat([ - Buffer.from(varint.encode(pbHeader.length)), pbHeader - ]) - const fanoutLinks = [] - for (let i = 0; i < defaultFanout; i++) { - fanoutLinks.push(new DAGLink('', 1, emptyKey)) - } - - if (pins.length <= maxItems) { - const nodes = pins - .map(item => { - return ({ - link: new DAGLink('', 1, item.key), - data: item.data || Buffer.alloc(0) - }) - }) - // sorting makes any ordering of `pins` produce the same DAGNode - .sort((a, b) => Buffer.compare(a.link.Hash.buffer, b.link.Hash.buffer)) - - const rootLinks = fanoutLinks.concat(nodes.map(item => item.link)) - const rootData = Buffer.concat( - [headerBuf].concat(nodes.map(item => item.data)) - ) - - let rootNode - - try { - rootNode = DAGNode.create(rootData, rootLinks) - } catch (err) { - return storePinsCb(err) - } - - return storePinsCb(null, rootNode) - } else { - // If the array of pins is > maxItems, we: - // - distribute the pins among `defaultFanout` bins - // - create a DAGNode for each bin - // - add each pin as a DAGLink to that bin - // - create a root DAGNode - // - add each bin as a DAGLink - // - send that root DAGNode via callback - // (using go-ipfs' "wasteful but simple" approach for consistency) - // https://github.com/ipfs/go-ipfs/blob/master/pin/set.go#L57 - - const bins = pins.reduce((bins, pin) => { - const n = hash(depth, pin.key) % defaultFanout - bins[n] = n in bins ? bins[n].concat([pin]) : [pin] - return bins - }, {}) - - eachOfSeries(bins, (bin, idx, eachCb) => { - storePins( - bin, - depth + 1, - (err, child) => storeChild(err, child, idx, eachCb) - ) - }, err => { - if (err) { return storePinsCb(err) } - - let rootNode - - try { - rootNode = DAGNode.create(headerBuf, fanoutLinks) - } catch (err) { - return storePinsCb(err) - } - - return storePinsCb(null, rootNode) - }) - } - - function storeChild (err, child, binIdx, cb) { - if (err) { return cb(err) } - - const opts = { - version: 0, - format: multicodec.DAG_PB, - hashAlg: multicodec.SHA2_256, - preload: false - } - - dag.put(child, opts, (err, cid) => { - if (err) { return cb(err) } - fanoutLinks[binIdx] = new DAGLink('', child.size, cid) - cb(null) - }) - } - } - }, - - loadSet: (rootNode, name, callback) => { - const link = rootNode.Links.find(l => l.Name === name) - if (!link) { - return callback(new Error('No link found with name ' + name)) - } - - dag.get(link.Hash, '', { preload: false }, (err, res) => { - if (err) { return callback(err) } - const keys = [] - const stepPin = link => keys.push(link.Hash.buffer) - pinSet.walkItems(res.value, { stepPin }, err => { - if (err) { return callback(err) } - return callback(null, keys) - }) - }) - }, - - walkItems: (node, { stepPin = () => {}, stepBin = () => {} }, callback) => { - let pbh - try { - pbh = readHeader(node) - } catch (err) { - return callback(err) - } - - eachOfSeries(node.Links, (link, idx, eachCb) => { - if (idx < pbh.header.fanout) { - // the first pbh.header.fanout links are fanout bins - // if a fanout bin is not 'empty', dig into and walk its DAGLinks - const linkHash = link.Hash.buffer - - if (!emptyKey.equals(linkHash)) { - stepBin(link, idx, pbh.data) - - // walk the links of this fanout bin - return dag.get(linkHash, '', { preload: false }, (err, res) => { - if (err) { return eachCb(err) } - pinSet.walkItems(res.value, { stepPin, stepBin }, eachCb) - }) - } - } else { - // otherwise, the link is a pin - stepPin(link, idx, pbh.data) - } - - eachCb(null) - }, callback) - }, - - getInternalCids: (rootNode, callback) => { - // "Empty block" used by the pinner - const cids = [new CID(emptyKey)] - - const stepBin = link => cids.push(link.Hash) - eachSeries(rootNode.Links, (topLevelLink, cb) => { - cids.push(topLevelLink.Hash) - - dag.get(topLevelLink.Hash, '', { preload: false }, (err, res) => { - if (err) { return cb(err) } - - pinSet.walkItems(res.value, { stepBin }, cb) - }) - }, (err) => callback(err, cids)) - } - } - return pinSet -} - -}).call(this,require("buffer").Buffer) -},{"./pin.proto":678,"async/eachOfSeries":110,"async/eachSeries":111,"async/someSeries":149,"buffer":217,"cids":222,"fnv1a":379,"ipld-dag-pb":745,"multicodec":1325,"multihashes":1331,"protons":1454,"varint":1785}],678:[function(require,module,exports){ -'use strict' - -/** - * Protobuf interface - * from go-ipfs/pin/internal/pb/header.proto - */ -module.exports = ` - syntax = "proto2"; - - package ipfs.pin; - - option go_package = "pb"; - - message Set { - optional uint32 version = 1; - optional uint32 fanout = 2; - optional fixed32 seed = 3; - } -` - -},{}],679:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR -const PeerId = require('peer-id') -const pull = require('pull-stream') -const Pushable = require('pull-pushable') - -const log = debug('ipfs:pingPullStream') -log.error = debug('ipfs:pingPullStream:error') - -module.exports = function pingPullStream (self) { - return (peerId, opts) => { - if (!self.isOnline()) { - return pull.error(new Error(OFFLINE_ERROR)) - } - - opts = Object.assign({ count: 10 }, opts) - - const source = Pushable() - - getPeer(self.libp2p, source, peerId, (err, peer) => { - if (err) { - log.error(err) - source.end(err) - return - } - - runPing(self.libp2p, source, opts.count, peer, (err) => { - if (err) { - log.error(err) - source.push(getPacket({ success: false, text: err.toString() })) - source.end() - } - }) - }) - - return source - } -} - -function getPacket (msg) { - // Default msg - const basePacket = { success: true, time: 0, text: '' } - return Object.assign(basePacket, msg) -} - -function getPeer (libp2pNode, statusStream, peerIdStr, cb) { - let peerId - - try { - peerId = PeerId.createFromB58String(peerIdStr) - } catch (err) { - return cb(err) - } - - let peerInfo - - try { - peerInfo = libp2pNode.peerBook.get(peerId) - } catch (err) { - log('Peer not found in peer book, trying peer routing') - - // Share lookup status just as in the go implemmentation - statusStream.push(getPacket({ text: `Looking up peer ${peerIdStr}` })) - return libp2pNode.peerRouting.findPeer(peerId, cb) - } - - cb(null, peerInfo) -} - -function runPing (libp2pNode, statusStream, count, peer, cb) { - libp2pNode.ping(peer, (err, p) => { - if (err) { return cb(err) } - - let packetCount = 0 - let totalTime = 0 - statusStream.push(getPacket({ text: `PING ${peer.id.toB58String()}` })) - - p.on('ping', (time) => { - statusStream.push(getPacket({ time })) - totalTime += time - packetCount++ - if (packetCount >= count) { - const average = totalTime / count - p.stop() - statusStream.push(getPacket({ text: `Average latency: ${average}ms` })) - statusStream.end() - } - }) - - p.on('error', (err) => { - log.error(err) - p.stop() - cb(err) - }) - - p.start() - }) -} - -},{"../utils":714,"debug":611,"peer-id":1432,"pull-pushable":1490,"pull-stream":1495}],680:[function(require,module,exports){ -'use strict' - -const toStream = require('pull-stream-to-stream') - -module.exports = function pingReadableStream (self) { - return (peerId, opts) => toStream.source(self.pingPullStream(peerId, opts)) -} - -},{"pull-stream-to-stream":1494}],681:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const pull = require('pull-stream/pull') - -module.exports = function ping (self) { - return promisify((peerId, opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - pull( - self.pingPullStream(peerId, opts), - pull.collect(callback) - ) - }) -} - -},{"promisify-es6":1443,"pull-stream/pull":1496}],682:[function(require,module,exports){ -'use strict' - -const peerId = require('peer-id') -const PeerInfo = require('peer-info') -const multiaddr = require('multiaddr') -const waterfall = require('async/waterfall') -const Keychain = require('libp2p-keychain') -const mergeOptions = require('merge-options') -const NoKeychain = require('./no-keychain') -/* - * Load stuff from Repo into memory - */ -module.exports = function preStart (self) { - return (callback) => { - self.log('pre-start') - - const pass = self._options.pass - waterfall([ - (cb) => self._repo.config.get(cb), - (config, cb) => { - if (!self._options.config) { - return cb(null, config) - } - - config = mergeOptions(config, self._options.config) - - self.config.replace(config, (err) => { - if (err) { - return cb(err) - } - - cb(null, config) - }) - }, - (config, cb) => { - // Create keychain configuration, if needed. - if (config.Keychain) { - return cb(null, config) - } - config.Keychain = Keychain.generateOptions() - self.config.set('Keychain', config.Keychain, (err) => { - self.log('using default keychain options') - cb(err, config) - }) - }, - (config, cb) => { - // Construct the keychain - if (self._keychain) { - // most likely an init or upgrade has happened - } else if (pass) { - const keychainOptions = Object.assign({ passPhrase: pass }, config.Keychain) - self._keychain = new Keychain(self._repo.keys, keychainOptions) - self.log('keychain constructed') - } else { - self._keychain = new NoKeychain() - self.log('no keychain, use --pass') - } - cb(null, config) - }, - (config, cb) => { - const privKey = config.Identity.PrivKey - - peerId.createFromPrivKey(privKey, (err, id) => { - cb(err, config, id) - }) - }, - (config, id, cb) => { - // Import the private key as 'self', if needed. - if (!pass) { - return cb(null, config, id) - } - self._keychain.findKeyByName('self', (err) => { - if (err) { - self.log('Creating "self" key') - return self._keychain.importPeer('self', id, (err) => cb(err, config, id)) - } - cb(null, config, id) - }) - }, - (config, id, cb) => { - self.log('peer created') - self._peerInfo = new PeerInfo(id) - - if (config.Addresses && config.Addresses.Swarm) { - config.Addresses.Swarm.forEach((addr) => { - let ma = multiaddr(addr) - - if (ma.getPeerId()) { - ma = ma.encapsulate('/ipfs/' + self._peerInfo.id.toB58String()) - } - - self._peerInfo.multiaddrs.add(ma) - }) - } - - cb() - }, - (cb) => self.pin._load(cb) - ], callback) - } -} - -},{"./no-keychain":671,"async/waterfall":152,"libp2p-keychain":1086,"merge-options":1298,"multiaddr":1314,"peer-id":1432,"peer-info":1433}],683:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const setImmediate = require('async/setImmediate') -const errCode = require('err-code') - -const errPubsubDisabled = () => { - return errCode(new Error('pubsub experiment is not enabled'), 'ERR_PUBSUB_DISABLED') -} - -module.exports = function pubsub (self) { - return { - subscribe: (topic, handler, options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - if (!self.libp2p.pubsub) { - return callback - ? setImmediate(() => callback(errPubsubDisabled())) - : Promise.reject(errPubsubDisabled()) - } - - if (!callback) { - return self.libp2p.pubsub.subscribe(topic, handler, options) - } - - self.libp2p.pubsub.subscribe(topic, handler, options, callback) - }, - - unsubscribe: (topic, handler, callback) => { - if (!self.libp2p.pubsub) { - return callback - ? setImmediate(() => callback(errPubsubDisabled())) - : Promise.reject(errPubsubDisabled()) - } - - if (!callback) { - return self.libp2p.pubsub.unsubscribe(topic, handler) - } - - self.libp2p.pubsub.unsubscribe(topic, handler, callback) - }, - - publish: promisify((topic, data, callback) => { - if (!self.libp2p.pubsub) { - return setImmediate(() => callback(errPubsubDisabled())) - } - self.libp2p.pubsub.publish(topic, data, callback) - }), - - ls: promisify((callback) => { - if (!self.libp2p.pubsub) { - return setImmediate(() => callback(errPubsubDisabled())) - } - self.libp2p.pubsub.ls(callback) - }), - - peers: promisify((topic, callback) => { - if (!self.libp2p.pubsub) { - return setImmediate(() => callback(errPubsubDisabled())) - } - self.libp2p.pubsub.peers(topic, callback) - }), - - setMaxListeners (n) { - if (!self.libp2p.pubsub) { - throw errPubsubDisabled() - } - self.libp2p.pubsub.setMaxListeners(n) - } - } -} - -},{"async/setImmediate":146,"err-code":315,"promisify-es6":1443}],684:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const repoVersion = require('ipfs-repo').repoVersion - -module.exports = function repo (self) { - return { - init: (bits, empty, callback) => { - // 1. check if repo already exists - }, - - /** - * If the repo has been initialized, report the current version. - * Otherwise report the version that would be initialized. - * - * @param {function(Error, Number)} [callback] - * @returns {undefined} - */ - version: promisify((callback) => { - self._repo._isInitialized(err => { - if (err) { - // TODO: (dryajov) This is really hacky, there must be a better way - const match = [ - /Key not found in database \[\/version\]/, - /ENOENT/, - /repo is not initialized yet/ - ].some((m) => { - return m.test(err.message) - }) - if (match) { - // this repo has not been initialized - return callback(null, repoVersion) - } - return callback(err) - } - - self._repo.version.get(callback) - }) - }), - - gc: require('./pin/gc')(self), - - stat: promisify((options, callback) => { - if (typeof options === 'function') { - callback = options - options = {} - } - - self._repo.stat(options, (err, stats) => { - if (err) return callback(err) - - callback(null, { - numObjects: stats.numObjects, - repoSize: stats.repoSize, - repoPath: stats.repoPath, - version: stats.version.toString(), - storageMax: stats.storageMax - }) - }) - }), - - path: () => self._repo.path - } -} - -},{"./pin/gc":675,"ipfs-repo":535,"promisify-es6":1443}],685:[function(require,module,exports){ -'use strict' - -const isIpfs = require('is-ipfs') -const CID = require('cids') -const nodeify = require('promise-nodeify') -const { cidToString } = require('../../utils/cid') - -/** - * @typedef { import("../index") } IPFS - */ - -/** - * @typedef {Object} ResolveOptions - * @prop {string} cidBase - Multibase codec name the CID in the resolved path will be encoded with - * @prop {boolean} [recursive=true] - Resolve until the result is an IPFS name - * - */ - -/** @typedef {(err: Error, path: string) => void} ResolveCallback */ - -/** - * @callback ResolveWrapper - This wrapper adds support for callbacks and promises - * @param {string} name - Path to resolve - * @param {ResolveOptions} opts - Options for resolve - * @param {ResolveCallback} [cb] - Optional callback function - * @returns {Promise | void} - When callback is provided nothing is returned - */ - -/** - * IPFS Resolve factory - * - * @param {IPFS} ipfs - * @returns {ResolveWrapper} - */ -module.exports = (ipfs) => { - /** - * IPFS Resolve - Resolve the value of names to IPFS - * - * @param {String} name - * @param {ResolveOptions} [opts={}] - * @returns {Promise} - */ - const resolve = async (name, opts = {}) => { - if (!isIpfs.path(name)) { - throw new Error('invalid argument ' + name) - } - - if (isIpfs.ipnsPath(name)) { - name = await ipfs.name.resolve(name, opts) - } - - const [, , hash, ...rest] = name.split('/') // ['', 'ipfs', 'hash', ...path] - const cid = new CID(hash) - - // nothing to resolve return the input - if (rest.length === 0) { - return `/ipfs/${cidToString(cid, { base: opts.cidBase })}` - } - - const path = rest.join('/') - const results = ipfs._ipld.resolve(cid, path) - let value = cid - let remainderPath = path - - for await (const result of results) { - if (CID.isCID(result.value)) { - value = result.value - remainderPath = result.remainderPath - } - } - - return `/ipfs/${cidToString(value, { base: opts.cidBase })}${remainderPath ? '/' + remainderPath : ''}` - } - - return (name, opts = {}, cb) => { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - return nodeify(resolve(name, opts), cb) - } -} - -},{"../../utils/cid":715,"cids":222,"is-ipfs":775,"promise-nodeify":1439}],686:[function(require,module,exports){ -'use strict' - -const series = require('async/series') -const Bitswap = require('ipfs-bitswap') -const setImmediate = require('async/setImmediate') -const promisify = require('promisify-es6') - -const IPNS = require('../ipns') -const routingConfig = require('../ipns/routing/config') -const createLibp2pBundle = require('./libp2p') - -module.exports = (self) => { - return promisify((callback) => { - const done = (err) => { - if (err) { - setImmediate(() => self.emit('error', err)) - return callback(err) - } - - self.state.started() - setImmediate(() => self.emit('start')) - callback() - } - - if (self.state.state() !== 'stopped') { - return done(new Error(`Not able to start from state: ${self.state.state()}`)) - } - - self.log('starting') - self.state.start() - - series([ - (cb) => { - // The repo may be closed if previously stopped - self._repo.closed - ? self._repo.open(cb) - : cb() - }, - (cb) => { - self._repo.config.get((err, config) => { - if (err) return cb(err) - - const libp2p = createLibp2pBundle(self, config) - - libp2p.start(err => { - if (err) return cb(err) - self.libp2p = libp2p - cb() - }) - }) - }, - (cb) => { - const ipnsRouting = routingConfig(self) - self._ipns = new IPNS(ipnsRouting, self._repo.datastore, self._peerInfo, self._keychain, self._options) - - self._bitswap = new Bitswap( - self.libp2p, - self._repo.blocks, - { statsEnabled: true } - ) - - self._bitswap.start() - self._blockService.setExchange(self._bitswap) - - self._preload.start() - self._ipns.republisher.start() - self._mfsPreload.start(cb) - } - ], done) - }) -} - -},{"../ipns":693,"../ipns/routing/config":698,"./libp2p":668,"async/series":145,"async/setImmediate":146,"ipfs-bitswap":477,"promisify-es6":1443}],687:[function(require,module,exports){ -(function (process){ -'use strict' - -const promisify = require('promisify-es6') -const Big = require('bignumber.js') -const Pushable = require('pull-pushable') -const human = require('human-to-milliseconds') -const toStream = require('pull-stream-to-stream') -const errCode = require('err-code') - -function bandwidthStats (self, opts) { - return new Promise((resolve, reject) => { - let stats - - if (opts.peer) { - stats = self.libp2p.stats.forPeer(opts.peer) - } else if (opts.proto) { - stats = self.libp2p.stats.forProtocol(opts.proto) - } else { - stats = self.libp2p.stats.global - } - - if (!stats) { - resolve({ - totalIn: new Big(0), - totalOut: new Big(0), - rateIn: new Big(0), - rateOut: new Big(0) - }) - return - } - - resolve({ - totalIn: stats.snapshot.dataReceived, - totalOut: stats.snapshot.dataSent, - rateIn: new Big(stats.movingAverages.dataReceived['60000'].movingAverage() / 60), - rateOut: new Big(stats.movingAverages.dataSent['60000'].movingAverage() / 60) - }) - }) -} - -module.exports = function stats (self) { - const _bwPullStream = (opts) => { - opts = opts || {} - let interval = null - const stream = Pushable(true, () => { - if (interval) { - clearInterval(interval) - } - }) - - if (opts.poll) { - let value - try { - value = human(opts.interval || '1s') - } catch (err) { - // Pull stream expects async work, so we need to simulate it. - process.nextTick(() => { - stream.end(errCode(err, 'ERR_INVALID_POLL_INTERVAL')) - }) - } - - interval = setInterval(() => { - bandwidthStats(self, opts) - .then((stats) => stream.push(stats)) - .catch((err) => { - if (interval) { - clearInterval(interval) - } - stream.end(err) - }) - }, value) - } else { - bandwidthStats(self, opts) - .then((stats) => { - stream.push(stats) - stream.end() - }) - .catch((err) => stream.end(err)) - } - - return stream.source - } - - return { - bitswap: require('./bitswap')(self).stat, - repo: require('./repo')(self).stat, - bw: promisify((opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - opts = opts || {} - - bandwidthStats(self, opts) - .then((stats) => callback(null, stats)) - .catch((err) => callback(err)) - }), - bwReadableStream: (opts) => toStream.source(_bwPullStream(opts)), - bwPullStream: _bwPullStream - } -} - -}).call(this,require('_process')) -},{"./bitswap":631,"./repo":684,"_process":1438,"bignumber.js":164,"err-code":315,"human-to-milliseconds":447,"promisify-es6":1443,"pull-pushable":1490,"pull-stream-to-stream":1494}],688:[function(require,module,exports){ -'use strict' - -const parallel = require('async/parallel') -const promisify = require('promisify-es6') - -module.exports = (self) => { - return promisify((callback) => { - callback = callback || function noop () {} - - self.log('stop') - - if (self.state.state() === 'stopped') { - return callback(new Error('Already stopped')) - } - - if (self.state.state() !== 'running') { - return callback(new Error('Not able to stop from state: ' + self.state.state())) - } - - self.state.stop() - self._blockService.unsetExchange() - self._bitswap.stop() - self._preload.stop() - - parallel([ - cb => self._ipns.republisher.stop(cb), - cb => self._mfsPreload.stop(cb), - cb => { - const libp2p = self.libp2p - self.libp2p = null - libp2p.stop(cb) - } - ], err => { - self._repo.close(closeErr => { - if (err || closeErr) { - self.emit('error', err || closeErr) - return callback(err || closeErr) - } - - self.state.stopped() - self.emit('stop') - callback() - }) - }) - }) -} - -},{"async/parallel":141,"promisify-es6":1443}],689:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') - -const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR - -module.exports = function swarm (self) { - return { - peers: promisify((opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - opts = opts || {} - - if (!self.isOnline()) { - return callback(new Error(OFFLINE_ERROR)) - } - - const verbose = opts.v || opts.verbose - // TODO: return latency and streams when verbose is set - // we currently don't have this information - - const peers = [] - - Object.values(self._peerInfoBook.getAll()).forEach((peer) => { - const connectedAddr = peer.isConnected() - - if (!connectedAddr) { return } - - const tupple = { - addr: connectedAddr, - peer: peer.id - } - if (verbose) { - tupple.latency = 'n/a' - } - - peers.push(tupple) - }) - - callback(null, peers) - }), - - // all the addrs we know - addrs: promisify((callback) => { - if (!self.isOnline()) { - return callback(new Error(OFFLINE_ERROR)) - } - - const peers = Object.values(self._peerInfoBook.getAll()) - - callback(null, peers) - }), - - localAddrs: promisify((callback) => { - if (!self.isOnline()) { - return callback(new Error(OFFLINE_ERROR)) - } - - callback(null, self.libp2p.peerInfo.multiaddrs.toArray()) - }), - - connect: promisify((maddr, callback) => { - if (!self.isOnline()) { - return callback(new Error(OFFLINE_ERROR)) - } - - self.libp2p.dial(maddr, callback) - }), - - disconnect: promisify((maddr, callback) => { - if (!self.isOnline()) { - return callback(new Error(OFFLINE_ERROR)) - } - - self.libp2p.hangUp(maddr, callback) - }), - - filters: promisify((callback) => callback(new Error('Not implemented'))) - } -} - -},{"../utils":714,"promisify-es6":1443}],690:[function(require,module,exports){ -'use strict' - -const pkg = require('../../../package.json') -const promisify = require('promisify-es6') - -// TODO add the commit hash of the current ipfs version to the response. -module.exports = function version (self) { - return promisify((opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - self.repo.version((err, repoVersion) => { - if (err) { - return callback(err) - } - - callback(null, { - version: pkg.version, - repo: repoVersion, - commit: '' - }) - }) - }) -} - -},{"../../../package.json":629,"promisify-es6":1443}],691:[function(require,module,exports){ -'use strict' - -const Multiaddr = require('multiaddr') -const mafmt = require('mafmt') -const { struct, superstruct } = require('superstruct') - -const { optional, union } = struct -const s = superstruct({ - types: { - multiaddr: v => { - if (v === null) { - return `multiaddr invalid, value must be a string, Buffer, or another Multiaddr got ${v}` - } - - try { - Multiaddr(v) - } catch (err) { - return `multiaddr invalid, ${err.message}` - } - - return true - }, - 'multiaddr-ipfs': v => mafmt.IPFS.matches(v) ? true : 'multiaddr IPFS invalid' - } -}) - -const configSchema = s({ - repo: optional(s('object|string')), - repoOwner: 'boolean?', - preload: s({ - enabled: 'boolean?', - addresses: optional(s(['multiaddr'])), - interval: 'number?' - }, { enabled: true, interval: 30 * 1000 }), - init: optional(union(['boolean', s({ - bits: 'number?', - emptyRepo: 'boolean?', - privateKey: optional(s('object|string')), // object should be a custom type for PeerId using 'kind-of' - pass: 'string?' - })])), - start: 'boolean?', - offline: 'boolean?', - pass: 'string?', - silent: 'boolean?', - relay: 'object?', // relay validates in libp2p - EXPERIMENTAL: optional(s({ - pubsub: 'boolean?', - ipnsPubsub: 'boolean?', - sharding: 'boolean?', - dht: 'boolean?' - })), - connectionManager: 'object?', - config: optional(s({ - API: 'object?', - Addresses: optional(s({ - Delegates: optional(s(['multiaddr'])), - Swarm: optional(s(['multiaddr'])), - API: optional(union([s('multiaddr'), s(['multiaddr'])])), - Gateway: optional(union([s('multiaddr'), s(['multiaddr'])])) - })), - Discovery: optional(s({ - MDNS: optional(s({ - Enabled: 'boolean?', - Interval: 'number?' - })), - webRTCStar: optional(s({ - Enabled: 'boolean?' - })) - })), - Bootstrap: optional(s(['multiaddr-ipfs'])), - Pubsub: optional(s({ - Router: 'string?', - Enabled: 'boolean?' - })), - Swarm: optional(s({ - ConnMgr: optional(s({ - LowWater: 'number?', - HighWater: 'number?' - })) - })) - })), - ipld: 'object?', - libp2p: optional(union(['function', 'object'])) // libp2p validates this -}, { - repoOwner: true -}) - -const validate = (opts) => { - const [err, options] = configSchema.validate(opts) - - if (err) { - throw err - } - - return options -} - -module.exports = { validate } - -},{"mafmt":1296,"multiaddr":1314,"superstruct":1743}],692:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const BlockService = require('ipfs-block-service') -const Ipld = require('ipld') -const PeerId = require('peer-id') -const PeerInfo = require('peer-info') -const crypto = require('libp2p-crypto') -const isIPFS = require('is-ipfs') -const multiaddr = require('multiaddr') -const multihash = require('multihashes') -const PeerBook = require('peer-book') -const multibase = require('multibase') -const multicodec = require('multicodec') -const multihashing = require('multihashing-async') -const CID = require('cids') -const debug = require('debug') -const mergeOptions = require('merge-options') -const EventEmitter = require('events') - -const config = require('./config') -const boot = require('./boot') -const components = require('./components') -const GCLock = require('./components/pin/gc-lock') - -// replaced by repo-browser when running in the browser -const defaultRepo = require('./runtime/repo-nodejs') -const preload = require('./preload') -const mfsPreload = require('./mfs-preload') -const ipldOptions = require('./runtime/ipld-nodejs') - -/** - * @typedef { import("./ipns/index") } IPNS - */ - -/** - * - * - * @class IPFS - * @extends {EventEmitter} - */ -class IPFS extends EventEmitter { - constructor (options) { - super() - - const defaults = { - init: true, - start: true, - EXPERIMENTAL: {}, - preload: { - enabled: true, - addresses: [ - '/dnsaddr/node0.preload.ipfs.io/https', - '/dnsaddr/node1.preload.ipfs.io/https' - ] - } - } - - options = config.validate(options || {}) - - this._options = mergeOptions(defaults, options) - - if (options.init === false) { - this._options.init = false - } - - if (!(options.start === false)) { - this._options.start = true - } - - if (typeof options.repo === 'string' || - options.repo === undefined) { - this._repo = defaultRepo(options.repo) - } else { - this._repo = options.repo - } - - // IPFS utils - this.log = debug('ipfs') - this.log.err = debug('ipfs:err') - - // IPFS Core Internals - // this._repo - assigned above - this._peerInfoBook = new PeerBook() - this._peerInfo = undefined - this._bitswap = undefined - this._blockService = new BlockService(this._repo) - this._ipld = new Ipld(ipldOptions(this._blockService, this._options.ipld, this.log)) - this._preload = preload(this) - this._mfsPreload = mfsPreload(this) - /** @type {IPNS} */ - this._ipns = undefined - // eslint-disable-next-line no-console - this._print = this._options.silent ? this.log : console.log - this._gcLock = new GCLock(this._options.repoOwner, { - // Make sure GCLock is specific to repo, for tests where there are - // multiple instances of IPFS - morticeId: this._repo.path - }) - - // IPFS Core exposed components - // - for booting up a node - this.init = components.init(this) - this.preStart = components.preStart(this) - this.start = components.start(this) - this.stop = components.stop(this) - this.shutdown = this.stop - this.isOnline = components.isOnline(this) - // - interface-ipfs-core defined API - Object.assign(this, components.filesRegular(this)) - this.version = components.version(this) - this.id = components.id(this) - this.repo = components.repo(this) - this.bootstrap = components.bootstrap(this) - this.config = components.config(this) - this.block = components.block(this) - this.object = components.object(this) - this.dag = components.dag(this) - this.files = components.filesMFS(this) - this.libp2p = null // assigned on start - this.swarm = components.swarm(this) - this.name = components.name(this) - this.bitswap = components.bitswap(this) - this.pin = components.pin(this) - this.ping = components.ping(this) - this.pingPullStream = components.pingPullStream(this) - this.pingReadableStream = components.pingReadableStream(this) - this.pubsub = components.pubsub(this) - this.dht = components.dht(this) - this.dns = components.dns(this) - this.key = components.key(this) - this.stats = components.stats(this) - this.resolve = components.resolve(this) - - if (this._options.EXPERIMENTAL.ipnsPubsub) { - this.log('EXPERIMENTAL IPNS pubsub is enabled') - } - if (this._options.EXPERIMENTAL.sharding) { - this.log('EXPERIMENTAL sharding is enabled') - } - - this.state = require('./state')(this) - - const onReady = () => { - this.removeListener('error', onError) - this._ready = true - } - - const onError = err => { - this.removeListener('ready', onReady) - this._readyError = err - } - - this.once('ready', onReady).once('error', onError) - - boot(this) - } - - get ready () { - return new Promise((resolve, reject) => { - if (this._ready) return resolve(this) - if (this._readyError) return reject(this._readyError) - this.once('ready', () => resolve(this)) - this.once('error', reject) - }) - } -} - -module.exports = IPFS - -// Note: We need to do this to force browserify to load the Buffer module -const BufferImpl = Buffer -Object.assign(module.exports, { crypto, isIPFS, Buffer: BufferImpl, CID, multiaddr, multibase, multihash, multihashing, multicodec, PeerId, PeerInfo }) - -module.exports.createNode = (options) => { - return new IPFS(options) -} - -module.exports.create = (options) => { - return new IPFS(options).ready -} - -}).call(this,require("buffer").Buffer) -},{"./boot":630,"./components":664,"./components/pin/gc-lock":674,"./config":691,"./mfs-preload":702,"./preload":703,"./runtime/ipld-nodejs":708,"./runtime/repo-nodejs":712,"./state":713,"buffer":217,"cids":222,"debug":611,"events":370,"ipfs-block-service":490,"ipld":757,"is-ipfs":775,"libp2p-crypto":905,"merge-options":1298,"multiaddr":1314,"multibase":1322,"multicodec":1325,"multihashes":1331,"multihashing-async":1336,"peer-book":1431,"peer-id":1432,"peer-info":1433}],693:[function(require,module,exports){ -'use strict' - -const { createFromPrivKey } = require('peer-id') -const series = require('async/series') - -const errcode = require('err-code') -const debug = require('debug') -const log = debug('ipfs:ipns') -log.error = debug('ipfs:ipns:error') - -const IpnsPublisher = require('./publisher') -const IpnsRepublisher = require('./republisher') -const IpnsResolver = require('./resolver') -const path = require('./path') -const { normalizePath } = require('../utils') -const TLRU = require('../../utils/tlru') -const defaultRecordTtl = 60 * 1000 - -class IPNS { - constructor (routing, datastore, peerInfo, keychain, options) { - this.publisher = new IpnsPublisher(routing, datastore) - this.republisher = new IpnsRepublisher(this.publisher, datastore, peerInfo, keychain, options) - this.resolver = new IpnsResolver(routing) - this.cache = new TLRU(1000) - this.routing = routing - } - - // Publish - publish (privKey, value, lifetime = IpnsPublisher.defaultRecordLifetime, callback) { - try { - value = normalizePath(value) - } catch (err) { - log.error(err) - return callback(err) - } - - series([ - (cb) => createFromPrivKey(privKey.bytes, cb), - (cb) => this.publisher.publishWithEOL(privKey, value, lifetime, cb) - ], (err, results) => { - if (err) { - log.error(err) - return callback(err) - } - - log(`IPNS value ${value} was published correctly`) - - // // Add to cache - const id = results[0].toB58String() - const ttEol = parseFloat(lifetime) - const ttl = (ttEol < defaultRecordTtl) ? ttEol : defaultRecordTtl - - this.cache.set(id, value, ttl) - - log(`IPNS value ${value} was cached correctly`) - - callback(null, { - name: id, - value: value - }) - }) - } - - // Resolve - resolve (name, options, callback) { - if (typeof name !== 'string') { - return callback(errcode(new Error('name received is not valid'), 'ERR_INVALID_NAME')) - } - - if (typeof options === 'function') { - callback = options - options = {} - } - - options = options || {} - - // If recursive, we should not try to get the cached value - if (!options.nocache && !options.recursive) { - // Try to get the record from cache - const id = name.split('/')[2] - const result = this.cache.get(id) - - if (result) { - return callback(null, result) - } - } - - this.resolver.resolve(name, options, (err, result) => { - if (err) { - log.error(err) - return callback(err) - } - - log(`IPNS record from ${name} was resolved correctly`) - - callback(null, result) - }) - } - - // Initialize keyspace - // sets the ipns record for the given key to point to an empty directory - initializeKeyspace (privKey, value, callback) { - this.publish(privKey, value, IpnsPublisher.defaultRecordLifetime, callback) - } -} - -IPNS.path = path - -module.exports = IPNS - -},{"../../utils/tlru":717,"../utils":714,"./path":694,"./publisher":695,"./republisher":696,"./resolver":697,"async/series":145,"debug":611,"err-code":315,"peer-id":1432}],694:[function(require,module,exports){ -'use strict' - -const isIPFS = require('is-ipfs') - -const debug = require('debug') -const log = debug('ipfs:ipns:path') -log.error = debug('ipfs:ipns:path:error') - -// resolves the given path by parsing out protocol-specific entries -// (e.g. /ipns/) and then going through the /ipfs/ entries and returning the final node -const resolvePath = (ipfsNode, name, callback) => { - // ipns path - if (isIPFS.ipnsPath(name)) { - log(`resolve ipns path ${name}`) - - return ipfsNode._ipns.resolve(name, callback) - } - - // ipfs path - ipfsNode.dag.get(name.substring('/ipfs/'.length), (err, value) => { - if (err) { - return callback(err) - } - - return callback(null, value) - }) -} - -module.exports = { - resolvePath -} - -},{"debug":611,"is-ipfs":775}],695:[function(require,module,exports){ -'use strict' - -const PeerId = require('peer-id') -const { Key } = require('interface-datastore') -const series = require('async/series') -const errcode = require('err-code') - -const debug = require('debug') -const log = debug('ipfs:ipns:publisher') -log.error = debug('ipfs:ipns:publisher:error') - -const ipns = require('ipns') - -const defaultRecordLifetime = 60 * 60 * 1000 - -// IpnsPublisher is capable of publishing and resolving names to the IPFS routing system. -class IpnsPublisher { - constructor (routing, datastore) { - this._routing = routing - this._datastore = datastore - } - - // publish record with a eol - publishWithEOL (privKey, value, lifetime, callback) { - if (!privKey || !privKey.bytes) { - return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY')) - } - - PeerId.createFromPrivKey(privKey.bytes, (err, peerId) => { - if (err) { - return callback(err) - } - - this._updateOrCreateRecord(privKey, value, lifetime, peerId, (err, record) => { - if (err) { - return callback(err) - } - - this._putRecordToRouting(record, peerId, callback) - }) - }) - } - - // Accepts a keypair, as well as a value (ipfsPath), and publishes it out to the routing system - publish (privKey, value, callback) { - this.publishWithEOL(privKey, value, defaultRecordLifetime, callback) - } - - _putRecordToRouting (record, peerId, callback) { - if (!(PeerId.isPeerId(peerId))) { - const errMsg = 'peerId received is not valid' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) - } - const publicKey = peerId._pubKey - - ipns.embedPublicKey(publicKey, record, (err, embedPublicKeyRecord) => { - if (err) { - return callback(err) - } - - let keys - try { - keys = ipns.getIdKeys(peerId.toBytes()) - } catch (err) { - log.error(err) - return callback(err) - } - - series([ - (cb) => this._publishEntry(keys.routingKey, embedPublicKeyRecord || record, peerId, cb), - // Publish the public key to support old go-ipfs nodes that are looking for it in the routing - // We will be able to deprecate this part in the future, since the public keys will be only - // in IPNS record and the peerId. - (cb) => this._publishPublicKey(keys.routingPubKey, publicKey, peerId, cb) - ], (err) => { - if (err) { - log.error(err) - return callback(err) - } - - callback(null, embedPublicKeyRecord || record) - }) - }) - } - - _publishEntry (key, entry, peerId, callback) { - if (!(Key.isKey(key))) { - const errMsg = 'datastore key does not have a valid format' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY')) - } - - let entryData - try { - // Marshal record - entryData = ipns.marshal(entry) - } catch (err) { - log.error(err) - return callback(err) - } - - // Add record to routing (buffer key) - this._routing.put(key.toBuffer(), entryData, (err, res) => { - if (err) { - const errMsg = `ipns record for ${key.toString('base64')} could not be stored in the routing` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')) - } - - log(`ipns record for ${key.toString('base64')} was stored in the routing`) - callback(null, res) - }) - } - - _publishPublicKey (key, publicKey, peerId, callback) { - if ((!Key.isKey(key))) { - const errMsg = 'datastore key does not have a valid format' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY')) - } - - if (!publicKey || !publicKey.bytes) { - const errMsg = 'one or more of the provided parameters are not defined' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_UNDEFINED_PARAMETER')) - } - - // Add public key to routing (buffer key) - this._routing.put(key.toBuffer(), publicKey.bytes, (err, res) => { - if (err) { - const errMsg = `public key for ${key.toString('base64')} could not be stored in the routing` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING')) - } - - log(`public key for ${key.toString('base64')} was stored in the routing`) - callback(null, res) - }) - } - - // Returns the record this node has published corresponding to the given peer ID. - // If `checkRouting` is true and we have no existing record, this method will check the routing system for any existing records. - _getPublished (peerId, options, callback) { - if (!(PeerId.isPeerId(peerId))) { - const errMsg = 'peerId received is not valid' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) - } - - options = options || {} - const checkRouting = options.checkRouting !== false - - this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => { - if (err) { - if (err.code !== 'ERR_NOT_FOUND') { - const errMsg = `unexpected error getting the ipns record ${peerId.id} from datastore` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_UNEXPECTED_DATASTORE_RESPONSE')) - } - - if (!checkRouting) { - return callback((errcode(err))) - } - - // Try to get from routing - let keys - try { - keys = ipns.getIdKeys(peerId.toBytes()) - } catch (err) { - log.error(err) - return callback(err) - } - - this._routing.get(keys.routingKey.toBuffer(), (err, res) => { - if (err) { - return callback(err) - } - - // unmarshal data - this._unmarshalData(res, callback) - }) - } else { - // unmarshal data - this._unmarshalData(dsVal, callback) - } - }) - } - - _unmarshalData (data, callback) { - let result - try { - result = ipns.unmarshal(data) - } catch (err) { - log.error(err) - return callback(errcode(err, 'ERR_INVALID_RECORD_DATA')) - } - - callback(null, result) - } - - _updateOrCreateRecord (privKey, value, validity, peerId, callback) { - if (!(PeerId.isPeerId(peerId))) { - const errMsg = 'peerId received is not valid' - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID')) - } - - const getPublishedOptions = { - checkRouting: true - } - - this._getPublished(peerId, getPublishedOptions, (err, record) => { - if (err) { - if (err.code !== 'ERR_NOT_FOUND') { - const errMsg = `unexpected error when determining the last published IPNS record for ${peerId.id}` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_DETERMINING_PUBLISHED_RECORD')) - } - } - - // Determinate the record sequence number - let seqNumber = 0 - if (record && record.sequence !== undefined) { - seqNumber = record.value.toString() !== value ? record.sequence + 1 : record.sequence - } - - // Create record - ipns.create(privKey, value, seqNumber, validity, (err, entryData) => { - if (err) { - const errMsg = `ipns record for ${value} could not be created` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_CREATING_IPNS_RECORD')) - } - - // TODO IMPROVEMENT - set ttl (still experimental feature for go) - - // Marshal record - const data = ipns.marshal(entryData) - - // Store the new record - this._datastore.put(ipns.getLocalKey(peerId.id), data, (err, res) => { - if (err) { - const errMsg = `ipns record for ${value} could not be stored in the datastore` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_STORING_IN_DATASTORE')) - } - - log(`ipns record for ${value} was stored in the datastore`) - callback(null, entryData) - }) - }) - }) - } -} - -IpnsPublisher.defaultRecordLifetime = defaultRecordLifetime -exports = module.exports = IpnsPublisher - -},{"async/series":145,"debug":611,"err-code":315,"interface-datastore":458,"ipns":763,"peer-id":1432}],696:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const ipns = require('ipns') -const crypto = require('libp2p-crypto') -const PeerId = require('peer-id') -const errcode = require('err-code') - -const debug = require('debug') -const each = require('async/each') -const waterfall = require('async/waterfall') -const log = debug('ipfs:ipns:republisher') -log.error = debug('ipfs:ipns:republisher:error') - -const minute = 60 * 1000 -const hour = 60 * minute - -const defaultBroadcastInterval = 4 * hour -const defaultRecordLifetime = 24 * hour - -class IpnsRepublisher { - constructor (publisher, datastore, peerInfo, keychain, options) { - this._publisher = publisher - this._datastore = datastore - this._peerInfo = peerInfo - this._keychain = keychain - this._options = options - this._republishHandle = null - } - - start () { - if (this._republishHandle) { - throw errcode(new Error('republisher is already running'), 'ERR_REPUBLISH_ALREADY_RUNNING') - } - - // TODO: this handler should be isolated in another module - const republishHandle = { - _onCancel: null, - _timeoutId: null, - runPeriodically: (fn, period) => { - republishHandle._timeoutId = setTimeout(() => { - republishHandle._timeoutId = null - - fn((nextPeriod) => { - // Was republish cancelled while fn was being called? - if (republishHandle._onCancel) { - return republishHandle._onCancel() - } - // Schedule next - republishHandle.runPeriodically(fn, nextPeriod || period) - }) - }, period) - }, - cancel: (cb) => { - // Not currently running a republish, can callback immediately - if (republishHandle._timeoutId) { - clearTimeout(republishHandle._timeoutId) - return cb() - } - // Wait for republish to finish then call callback - republishHandle._onCancel = cb - } - } - - const { privKey } = this._peerInfo.id - const { pass } = this._options - - republishHandle.runPeriodically((done) => { - this._republishEntries(privKey, pass, () => done(defaultBroadcastInterval)) - }, minute) - - this._republishHandle = republishHandle - } - - stop (callback) { - const republishHandle = this._republishHandle - - if (!republishHandle) { - return callback(errcode(new Error('republisher is not running'), 'ERR_REPUBLISH_NOT_RUNNING')) - } - - this._republishHandle = null - republishHandle.cancel(callback) - } - - _republishEntries (privateKey, pass, callback) { - // TODO: Should use list of published entries. - // We can't currently *do* that because go uses this method for now. - this._republishEntry(privateKey, (err) => { - if (err) { - const errMsg = 'cannot republish entry for the node\'s private key' - - log.error(errMsg) - return - } - - // keychain needs pass to get the cryptographic keys - if (pass) { - this._keychain.listKeys((err, list) => { - if (err) { - log.error(err) - return - } - - each(list, (key, cb) => { - waterfall([ - (cb) => this._keychain.exportKey(key.name, pass, cb), - (pem, cb) => crypto.keys.import(pem, pass, cb) - ], (err, privKey) => { - if (err) { - log.error(err) - return - } - - this._republishEntry(privKey, cb) - }) - }, (err) => { - if (err) { - log.error(err) - } - callback(null) - }) - }) - } else { - callback(null) - } - }) - } - - _republishEntry (privateKey, callback) { - if (!privateKey || !privateKey.bytes) { - return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY')) - } - - waterfall([ - (cb) => PeerId.createFromPrivKey(privateKey.bytes, cb), - (peerId, cb) => this._getPreviousValue(peerId, cb) - ], (err, value) => { - if (err) { - return callback(err.code === 'ERR_NO_ENTRY_FOUND' ? null : err) - } - - this._publisher.publishWithEOL(privateKey, value, defaultRecordLifetime, callback) - }) - } - - _getPreviousValue (peerId, callback) { - if (!(PeerId.isPeerId(peerId))) { - return callback(errcode(new Error('invalid peer ID'), 'ERR_INVALID_PEER_ID')) - } - - this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => { - // error handling - // no need to republish - if (err && err.notFound) { - return callback(errcode(new Error(`no previous entry for record with id: ${peerId.id}`), 'ERR_NO_ENTRY_FOUND')) - } else if (err) { - return callback(err) - } - - if (!Buffer.isBuffer(dsVal)) { - return callback(errcode(new Error("found ipns record that we couldn't process"), 'ERR_INVALID_IPNS_RECORD')) - } - - // unmarshal data - let record - try { - record = ipns.unmarshal(dsVal) - } catch (err) { - log.error(err) - return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_IPNS_RECORD')) - } - - callback(null, record.value) - }) - } -} - -exports = module.exports = IpnsRepublisher - -}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")}) -},{"../../../../is-buffer/index.js":766,"async/each":106,"async/waterfall":152,"debug":611,"err-code":315,"ipns":763,"libp2p-crypto":905,"peer-id":1432}],697:[function(require,module,exports){ -'use strict' - -const ipns = require('ipns') -const crypto = require('libp2p-crypto') -const PeerId = require('peer-id') -const errcode = require('err-code') - -const debug = require('debug') -const log = debug('ipfs:ipns:resolver') -log.error = debug('ipfs:ipns:resolver:error') - -const defaultMaximumRecursiveDepth = 32 - -class IpnsResolver { - constructor (routing) { - this._routing = routing - } - - resolve (name, options, callback) { - if (typeof options === 'function') { - callback = options - options = {} - } - - if (typeof name !== 'string') { - return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME')) - } - - options = options || {} - const recursive = options.recursive && options.recursive.toString() === 'true' - - const nameSegments = name.split('/') - - if (nameSegments.length !== 3 || nameSegments[0] !== '') { - return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME')) - } - - const key = nameSegments[2] - - // Define a maximum depth if recursive option enabled - let depth - - if (recursive) { - depth = defaultMaximumRecursiveDepth - } - - this.resolver(key, depth, (err, res) => { - if (err) { - return callback(err) - } - - log(`${name} was locally resolved correctly`) - callback(null, res) - }) - } - - // Recursive resolver according to the specified depth - resolver (name, depth, callback) { - // Exceeded recursive maximum depth - if (depth === 0) { - const errMsg = `could not resolve name (recursion limit of ${defaultMaximumRecursiveDepth} exceeded)` - - log.error(errMsg) - return callback(errcode(new Error(errMsg), 'ERR_RESOLVE_RECURSION_LIMIT')) - } - - this._resolveName(name, (err, res) => { - if (err) { - return callback(err) - } - - const nameSegments = res.split('/') - - // If obtained a ipfs cid or recursive option is disabled - if (nameSegments[1] === 'ipfs' || !depth) { - return callback(null, res) - } - - // continue recursively until depth equals 0 - this.resolver(nameSegments[2], depth - 1, callback) - }) - } - - // resolve ipns entries from the provided routing - _resolveName (name, callback) { - let peerId - - try { - peerId = PeerId.createFromB58String(name) - } catch (err) { - return callback(err) - } - - const { routingKey, routingPubKey } = ipns.getIdKeys(peerId.toBytes()) - - this._routing.get(routingKey.toBuffer(), (err, record) => { - if (err) { - log.error(err) - if (err.code !== 'ERR_NOT_FOUND') { - return callback(errcode(new Error(`unexpected error getting the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_RECORD')) - } - return callback(errcode(new Error(`record requested was not found for ${name} (${routingKey}) in the network`), 'ERR_NO_RECORD_FOUND')) - } - - // IPNS entry - let ipnsEntry - try { - ipnsEntry = ipns.unmarshal(record) - } catch (err) { - log.error(err) - return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_RECORD_RECEIVED')) - } - - // if the record has a public key validate it - if (ipnsEntry.pubKey) { - return this._validateRecord(peerId, ipnsEntry, callback) - } - - // Otherwise, try to get the public key from routing - this._routing.get(routingKey.toBuffer(), (err, pubKey) => { - if (err) { - log.error(err) - if (err.code !== 'ERR_NOT_FOUND') { - return callback(errcode(new Error(`unexpected error getting the public key for the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_PUB_KEY')) - } - return callback(errcode(new Error(`public key requested was not found for ${name} (${routingPubKey}) in the network`), 'ERR_NO_RECORD_FOUND')) - } - - try { - // Insert it into the peer id, in order to be validated by IPNS validator - peerId.pubKey = crypto.keys.unmarshalPublicKey(pubKey) - } catch (err) { - log.error(err) - return callback(errcode(new Error('found public key record that we couldn\'t convert to a value'), 'ERR_INVALID_PUB_KEY_RECEIVED')) - } - - this._validateRecord(peerId, ipnsEntry, callback) - }) - }) - } - - // validate a resolved record - _validateRecord (peerId, ipnsEntry, callback) { - ipns.extractPublicKey(peerId, ipnsEntry, (err, pubKey) => { - if (err) { - return callback(err) - } - - // IPNS entry validation - ipns.validate(pubKey, ipnsEntry, (err) => { - if (err) { - return callback(err) - } - - callback(null, ipnsEntry.value.toString()) - }) - }) - } -} - -exports = module.exports = IpnsResolver - -},{"debug":611,"err-code":315,"ipns":763,"libp2p-crypto":905,"peer-id":1432}],698:[function(require,module,exports){ -'use strict' - -const { TieredDatastore } = require('datastore-core') -const get = require('dlv') - -const PubsubDatastore = require('./pubsub-datastore') -const OfflineDatastore = require('./offline-datastore') - -module.exports = (ipfs) => { - // Setup online routing for IPNS with a tiered routing composed by a DHT and a Pubsub router (if properly enabled) - const ipnsStores = [] - - // Add IPNS pubsub if enabled - let pubsubDs - if (get(ipfs._options, 'EXPERIMENTAL.ipnsPubsub', false)) { - const pubsub = ipfs.libp2p.pubsub - const localDatastore = ipfs._repo.datastore - const peerId = ipfs._peerInfo.id - - pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId) - ipnsStores.push(pubsubDs) - } - - // DHT should not be added as routing if we are offline or it is disabled - if (get(ipfs._options, 'offline') || !get(ipfs._options, 'libp2p.config.dht.enabled', false)) { - const offlineDatastore = new OfflineDatastore(ipfs._repo) - ipnsStores.push(offlineDatastore) - } else { - ipnsStores.push(ipfs.libp2p.dht) - } - - // Create ipns routing with a set of datastores - return new TieredDatastore(ipnsStores) -} - -},{"./offline-datastore":699,"./pubsub-datastore":700,"datastore-core":238,"dlv":276}],699:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const { Key } = require('interface-datastore') -const { Record } = require('libp2p-record') -const { encodeBase32 } = require('./utils') - -const errcode = require('err-code') -const debug = require('debug') -const log = debug('ipfs:ipns:offline-datastore') -log.error = debug('ipfs:ipns:offline-datastore:error') - -// Offline datastore aims to mimic the same encoding as routing when storing records -// to the local datastore -class OfflineDatastore { - constructor (repo) { - this._repo = repo - } - - /** - * Put a value to the local datastore indexed by the received key properly encoded. - * @param {Buffer} key identifier of the value. - * @param {Buffer} value value to be stored. - * @param {function(Error)} callback - * @returns {void} - */ - put (key, value, callback) { - if (!Buffer.isBuffer(key)) { - return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY')) - } - - if (!Buffer.isBuffer(value)) { - return callback(errcode(new Error('Offline datastore value must be a buffer'), 'ERR_INVALID_VALUE')) - } - - let routingKey - - try { - routingKey = this._routingKey(key) - } catch (err) { - log.error(err) - return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')) - } - - // Marshal to libp2p record as the DHT does - const record = new Record(key, value) - - this._repo.datastore.put(routingKey, record.serialize(), callback) - } - - /** - * Get a value from the local datastore indexed by the received key properly encoded. - * @param {Buffer} key identifier of the value to be obtained. - * @param {function(Error, Buffer)} callback - * @returns {void} - */ - get (key, callback) { - if (!Buffer.isBuffer(key)) { - return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY')) - } - - let routingKey - - try { - routingKey = this._routingKey(key) - } catch (err) { - log.error(err) - return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY')) - } - - this._repo.datastore.get(routingKey, (err, res) => { - if (err) { - return callback(err) - } - - // Unmarshal libp2p record as the DHT does - let record - try { - record = Record.deserialize(res) - } catch (err) { - log.error(err) - return callback(err) - } - - callback(null, record.value) - }) - } - - // encode key properly - base32(/ipns/{cid}) - _routingKey (key) { - return new Key('/' + encodeBase32(key), false) - } -} - -exports = module.exports = OfflineDatastore - -}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"./utils":701,"debug":611,"err-code":315,"interface-datastore":458,"libp2p-record":1109}],700:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const ipns = require('ipns') -const { fromB58String, toB58String } = require('multihashes') -const PubsubDatastore = require('datastore-pubsub') - -const withIs = require('class-is') - -const errcode = require('err-code') -const debug = require('debug') -const log = debug('ipfs:ipns:pubsub') -log.error = debug('ipfs:ipns:pubsub:error') - -// Pubsub datastore aims to manage the pubsub subscriptions for IPNS -class IpnsPubsubDatastore { - constructor (pubsub, localDatastore, peerId) { - this._pubsub = pubsub - this._subscriptions = {} - - // Bind _handleSubscriptionKey function, which is called by PubsubDatastore. - this._handleSubscriptionKey = this._handleSubscriptionKey.bind(this) - this._pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId, ipns.validator, this._handleSubscriptionKey) - } - - /** - * Put a value to the pubsub datastore indexed by the received key properly encoded. - * @param {Buffer} key identifier of the value. - * @param {Buffer} value value to be stored. - * @param {function(Error)} callback - * @returns {void} - */ - put (key, value, callback) { - this._pubsubDs.put(key, value, callback) - } - - /** - * Get a value from the pubsub datastore indexed by the received key properly encoded. - * Moreover, the identifier topic is subscribed and the pubsub datastore records will be - * updated once new publishes occur. - * @param {Buffer} key identifier of the value to be obtained. - * @param {function(Error, Buffer)} callback - * @returns {void} - */ - get (key, callback) { - this._pubsubDs.get(key, (err, res) => { - // Add topic subscribed - const ns = key.slice(0, ipns.namespaceLength) - - if (ns.toString() === ipns.namespace) { - const stringifiedTopic = key.toString() - const id = toB58String(key.slice(ipns.namespaceLength)) - - this._subscriptions[stringifiedTopic] = id - - log(`subscribed pubsub ${stringifiedTopic}: ${id}`) - } - - // If no data was obtained, after storing the subscription, return the error. - if (err) { - return callback(err) - } - - callback(null, res) - }) - } - - // Modify subscription key to have a proper encoding - _handleSubscriptionKey (key, callback) { - const subscriber = this._subscriptions[key] - - if (!subscriber) { - return callback(errcode(new Error(`key ${key} does not correspond to a subscription`), 'ERR_INVALID_KEY')) - } - - let keys - try { - keys = ipns.getIdKeys(fromB58String(subscriber)) - } catch (err) { - log.error(err) - return callback(err) - } - - callback(null, keys.routingKey.toBuffer()) - } - - /** - * Get pubsub subscriptions related to ipns. - * @param {function(Error, Object)} callback - * @returns {void} - */ - getSubscriptions (callback) { - const subscriptions = Object.values(this._subscriptions).filter(Boolean) - - return callback(null, subscriptions.map((sub) => `${ipns.namespace}${sub}`)) - } - - /** - * Cancel pubsub subscriptions related to ipns. - * @param {String} name ipns path to cancel the pubsub subscription. - * @param {function(Error, Object)} callback - * @returns {void} - */ - cancel (name, callback) { - if (typeof name !== 'string') { - return callback(errcode(new Error('invalid subscription name'), 'ERR_INVALID_SUBSCRIPTION_NAME')) - } - - // Trim /ipns/ prefix from the name - if (name.startsWith(ipns.namespace)) { - name = name.substring(ipns.namespaceLength) - } - - const stringifiedTopic = Object.keys(this._subscriptions).find((key) => this._subscriptions[key] === name) - - // Not found topic - if (!stringifiedTopic) { - return callback(null, { - canceled: false - }) - } - - // Unsubscribe topic - try { - const bufTopic = Buffer.from(stringifiedTopic) - - this._pubsubDs.unsubscribe(bufTopic) - } catch (err) { - return callback(err) - } - - this._subscriptions[stringifiedTopic] = undefined - log(`unsubscribed pubsub ${stringifiedTopic}: ${name}`) - - callback(null, { - canceled: true - }) - } -} - -exports = module.exports = withIs(IpnsPubsubDatastore, { className: 'IpnsPubsubDatastore', symbolName: '@js-ipfs/ipns/IpnsPubsubDatastore' }) - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"class-is":224,"datastore-pubsub":251,"debug":611,"err-code":315,"ipns":763,"multihashes":1331}],701:[function(require,module,exports){ -'use strict' - -const multibase = require('multibase') -const ipns = require('ipns') - -module.exports = { - encodeBase32: (buf) => { - const m = multibase.encode('base32', buf).slice(1) // slice off multibase codec - - return m.toString().toUpperCase() // should be uppercase for interop with go - }, - validator: { - func: (key, record, cb) => ipns.validator.validate(record, key, cb) - }, - selector: (k, records) => ipns.validator.select(records[0], records[1]) -} - -},{"ipns":763,"multibase":1322}],702:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const setImmediate = require('async/setImmediate') -const log = debug('ipfs:mfs-preload') -log.error = debug('ipfs:mfs-preload:error') - -module.exports = (self) => { - const options = self._options.preload || {} - options.interval = options.interval || 30 * 1000 - - if (!options.enabled) { - log('MFS preload disabled') - return { - start: (cb) => setImmediate(cb), - stop: (cb) => setImmediate(cb) - } - } - - let rootCid - let timeoutId - - const preloadMfs = () => { - self.files.stat('/', (err, stats) => { - if (err) { - timeoutId = setTimeout(preloadMfs, options.interval) - return log.error('failed to stat MFS root for preload', err) - } - - if (rootCid !== stats.hash) { - log(`preloading updated MFS root ${rootCid} -> ${stats.hash}`) - - return self._preload(stats.hash, (err) => { - timeoutId = setTimeout(preloadMfs, options.interval) - if (err) return log.error(`failed to preload MFS root ${stats.hash}`, err) - rootCid = stats.hash - }) - } - - timeoutId = setTimeout(preloadMfs, options.interval) - }) - } - - return { - start (cb) { - self.files.stat('/', (err, stats) => { - if (err) return cb(err) - rootCid = stats.hash - log(`monitoring MFS root ${rootCid}`) - timeoutId = setTimeout(preloadMfs, options.interval) - cb() - }) - }, - stop (cb) { - clearTimeout(timeoutId) - cb() - } - } -} - -},{"async/setImmediate":146,"debug":611}],703:[function(require,module,exports){ -'use strict' - -const setImmediate = require('async/setImmediate') -const retry = require('async/retry') -const toUri = require('multiaddr-to-uri') -const debug = require('debug') -const CID = require('cids') -const shuffle = require('array-shuffle') -const preload = require('./runtime/preload-nodejs') - -const log = debug('ipfs:preload') -log.error = debug('ipfs:preload:error') - -const noop = (err) => { if (err) log.error(err) } - -module.exports = self => { - const options = self._options.preload || {} - options.enabled = Boolean(options.enabled) - options.addresses = options.addresses || [] - - if (!options.enabled || !options.addresses.length) { - log('preload disabled') - const api = (_, callback) => { - if (callback) { - setImmediate(() => callback()) - } - } - api.start = () => {} - api.stop = () => {} - return api - } - - let stopped = true - let requests = [] - const apiUris = options.addresses.map(toUri) - - const api = (path, callback) => { - callback = callback || noop - - if (typeof path !== 'string') { - try { - path = new CID(path).toBaseEncodedString() - } catch (err) { - return setImmediate(() => callback(err)) - } - } - - const fallbackApiUris = shuffle(apiUris) - let request - const now = Date.now() - - retry({ times: fallbackApiUris.length }, (cb) => { - if (stopped) return cb(new Error(`preload aborted for ${path}`)) - - // Remove failed request from a previous attempt - requests = requests.filter(r => r !== request) - - const apiUri = fallbackApiUris.shift() - - request = preload(`${apiUri}/api/v0/refs?r=true&arg=${encodeURIComponent(path)}`, cb) - requests = requests.concat(request) - }, (err) => { - requests = requests.filter(r => r !== request) - - if (err) { - return callback(err) - } - - log(`preloaded ${path} in ${Date.now() - now}ms`) - callback() - }) - } - - api.start = () => { - stopped = false - } - - api.stop = () => { - stopped = true - log(`canceling ${requests.length} pending preload request(s)`) - requests.forEach(r => r.cancel()) - requests = [] - } - - return api -} - -},{"./runtime/preload-nodejs":711,"array-shuffle":54,"async/retry":144,"async/setImmediate":146,"cids":222,"debug":611,"multiaddr-to-uri":1311}],704:[function(require,module,exports){ -'use strict' - -const callbackify = require('callbackify') - -module.exports = () => { - return callbackify(() => { - throw new Error('not available in the browser') - }) -} - -},{"callbackify":219}],705:[function(require,module,exports){ -'use strict' - -module.exports = () => ({ - Addresses: { - Swarm: [ - ], - API: '', - Gateway: '', - Delegates: [] - }, - Discovery: { - MDNS: { - Enabled: false, - Interval: 10 - }, - webRTCStar: { - Enabled: true - } - }, - Bootstrap: [ - '/dns4/ams-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd', - '/dns4/lon-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3', - '/dns4/sfo-3.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM', - '/dns4/sgp-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu', - '/dns4/nyc-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm', - '/dns4/nyc-2.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64', - '/dns4/node0.preload.ipfs.io/tcp/443/wss/ipfs/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic', - '/dns4/node1.preload.ipfs.io/tcp/443/wss/ipfs/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6' - ], - Pubsub: { - Enabled: true - }, - Swarm: { - ConnMgr: { - LowWater: 200, - HighWater: 500 - } - } -}) - -},{}],706:[function(require,module,exports){ -/* global self */ -'use strict' - -module.exports = (domain, opts, callback) => { - if (typeof opts === 'function') { - callback = opts - opts = {} - } - - opts = opts || {} - - domain = encodeURIComponent(domain) - let url = `https://ipfs.io/api/v0/dns?arg=${domain}` - - Object.keys(opts).forEach(prop => { - url += `&${encodeURIComponent(prop)}=${encodeURIComponent(opts[prop])}` - }) - - self.fetch(url, { mode: 'cors' }) - .then((response) => { - return response.json() - }) - .then((response) => { - if (response.Path) { - return callback(null, response.Path) - } else { - return callback(new Error(response.Message)) - } - }) - .catch((error) => { - callback(error) - }) -} - -},{}],707:[function(require,module,exports){ -/* eslint-env browser */ -'use strict' -module.exports = fetch - -},{}],708:[function(require,module,exports){ -'use strict' -const mergeOptions = require('merge-options') -const ipldDagCbor = require('ipld-dag-cbor') -const ipldDagPb = require('ipld-dag-pb') -const ipldRaw = require('ipld-raw') - -module.exports = (blockService, options = {}) => { - return mergeOptions.call( - // ensure we have the defaults formats even if the user overrides `formats: []` - { concatArrays: true }, - { - blockService: blockService, - formats: [ipldDagCbor, ipldDagPb, ipldRaw] - }, options) -} - -},{"ipld-dag-cbor":725,"ipld-dag-pb":745,"ipld-raw":756,"merge-options":1298}],709:[function(require,module,exports){ -'use strict' - -const WS = require('libp2p-websockets') -const WebRTCStar = require('libp2p-webrtc-star') -const WebSocketStarMulti = require('libp2p-websocket-star-multi') -const Multiplex = require('pull-mplex') -const SECIO = require('libp2p-secio') -const Bootstrap = require('libp2p-bootstrap') -const KadDHT = require('libp2p-kad-dht') -const GossipSub = require('libp2p-gossipsub') -const libp2p = require('libp2p') -const mergeOptions = require('merge-options') -const multiaddr = require('multiaddr') - -class Node extends libp2p { - constructor (_options) { - const wrtcstar = new WebRTCStar({ id: _options.peerInfo.id }) - - // this can be replaced once optional listening is supported with the below code. ref: https://github.com/libp2p/interface-transport/issues/41 - // const wsstar = new WebSocketStar({ id: _options.peerInfo.id }) - const wsstarServers = _options.peerInfo.multiaddrs.toArray().map(String).filter(addr => addr.includes('p2p-websocket-star')) - _options.peerInfo.multiaddrs.replace(wsstarServers.map(multiaddr), '/p2p-websocket-star') // the ws-star-multi module will replace this with the chosen ws-star servers - const wsstar = new WebSocketStarMulti({ servers: wsstarServers, id: _options.peerInfo.id, ignore_no_online: !wsstarServers.length || _options.wsStarIgnoreErrors }) - - const defaults = { - switch: { - denyTTL: 2 * 60 * 1e3, // 2 minute base - denyAttempts: 5, // back off 5 times - maxParallelDials: 100, - maxColdCalls: 25, - dialTimeout: 20e3 - }, - modules: { - transport: [ - WS, - wrtcstar, - wsstar - ], - streamMuxer: [ - Multiplex - ], - connEncryption: [ - SECIO - ], - peerDiscovery: [ - wrtcstar.discovery, - wsstar.discovery, - Bootstrap - ], - dht: KadDHT, - pubsub: GossipSub - }, - config: { - peerDiscovery: { - autoDial: true, - bootstrap: { - enabled: true - }, - webRTCStar: { - enabled: true - }, - websocketStar: { - enabled: true - } - }, - dht: { - enabled: false - }, - pubsub: { - enabled: true, - emitSelf: true - } - } - } - - super(mergeOptions(defaults, _options)) - } -} - -module.exports = Node - -},{"libp2p":1183,"libp2p-bootstrap":877,"libp2p-gossipsub":1011,"libp2p-kad-dht":1029,"libp2p-secio":1135,"libp2p-webrtc-star":1141,"libp2p-websocket-star-multi":1146,"libp2p-websockets":1157,"merge-options":1298,"multiaddr":1314,"pull-mplex":1485}],710:[function(require,module,exports){ -'use strict' - -module.exports = { - gossipsub: require('libp2p-gossipsub') -} - -},{"libp2p-gossipsub":1011}],711:[function(require,module,exports){ -/* eslint-env browser */ -'use strict' - -const debug = require('debug') - -const log = debug('ipfs:preload') -log.error = debug('ipfs:preload:error') - -module.exports = function preload (url, callback) { - log(url) - - const controller = new AbortController() - const signal = controller.signal - - fetch(url, { signal }) - .then(res => { - if (!res.ok) { - log.error('failed to preload', url, res.status, res.statusText) - throw new Error(`failed to preload ${url}`) - } - return res.text() - }) - .then(() => callback()) - .catch(callback) - - return { - cancel: () => controller.abort() - } -} - -},{"debug":611}],712:[function(require,module,exports){ -'use strict' - -const IPFSRepo = require('ipfs-repo') - -module.exports = (dir) => { - const repoPath = dir || 'ipfs' - return new IPFSRepo(repoPath) -} - -},{"ipfs-repo":535}],713:[function(require,module,exports){ -'use strict' - -const debug = require('debug') -const log = debug('ipfs:state') -log.error = debug('ipfs:state:error') - -const fsm = require('fsm-event') - -module.exports = (self) => { - const s = fsm('uninitialized', { - uninitialized: { - init: 'initializing', - initialized: 'stopped' - }, - initializing: { - initialized: 'stopped' - }, - stopped: { - start: 'starting' - }, - starting: { - started: 'running' - }, - running: { - stop: 'stopping' - }, - stopping: { - stopped: 'stopped' - } - }) - - // log events - s.on('error', (err) => log.error(err)) - s.on('done', () => log('-> ' + s._state)) - - // -- Actions - - s.init = () => { - s('init') - } - - s.initialized = () => { - s('initialized') - } - - s.stop = () => { - s('stop') - } - - s.stopped = () => { - s('stopped') - } - - s.start = () => { - s('start') - } - - s.started = () => { - s('started') - } - - s.state = () => s._state - - return s -} - -},{"debug":611,"fsm-event":383}],714:[function(require,module,exports){ -'use strict' - -const promisify = require('promisify-es6') -const map = require('async/map') -const isIpfs = require('is-ipfs') -const CID = require('cids') - -const ERR_BAD_PATH = 'ERR_BAD_PATH' -exports.OFFLINE_ERROR = 'This command must be run in online mode. Try running \'ipfs daemon\' first.' - -/** - * Break an ipfs-path down into it's hash and an array of links. - * - * examples: - * b58Hash -> { hash: 'b58Hash', links: [] } - * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']} - * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] } - * - * @param {String} ipfsPath An ipfs-path - * @return {Object} { hash: base58 string, links: [string], ?err: Error } - * @throws on an invalid @param ipfsPath - */ -function parseIpfsPath (ipfsPath) { - const invalidPathErr = new Error('invalid ipfs ref path') - ipfsPath = ipfsPath.replace(/^\/ipfs\//, '') - const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/) - if (!matched) { - throw invalidPathErr - } - - const [hash, ...links] = matched[1].split('/') - - // check that a CID can be constructed with the hash - if (isIpfs.cid(hash)) { - return { hash, links } - } else { - throw invalidPathErr - } -} - -/** - * Returns a well-formed ipfs Path. - * The returned path will always be prefixed with /ipfs/ or /ipns/. - * If the received string is not a valid ipfs path, an error will be returned - * examples: - * b58Hash -> { hash: 'b58Hash', links: [] } - * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']} - * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] } - * - * @param {String} pathStr An ipfs-path, or ipns-path or a cid - * @return {String} ipfs-path or ipns-path - * @throws on an invalid @param ipfsPath - */ -const normalizePath = (pathStr) => { - if (isIpfs.cid(pathStr)) { - return `/ipfs/${pathStr}` - } else if (isIpfs.path(pathStr)) { - return pathStr - } else { - throw Object.assign(new Error(`invalid ${pathStr} path`), { code: ERR_BAD_PATH }) - } -} - -/** - * Resolve various styles of an ipfs-path to the hash of the target node. - * Follows links in the path. - * - * Accepts formats: - * - - * - /link/to/venus - * - /ipfs//link/to/pluto - * - multihash Buffer - * - Arrays of the above - * - * @param {IPFS} objectAPI The IPFS object api - * @param {Described above} ipfsPaths A single or collection of ipfs-paths - * @param {Function} callback res is Array - * if no callback is passed, returns a Promise - * @return {Promise|void} - */ -const resolvePath = promisify(function (objectAPI, ipfsPaths, callback) { - if (!Array.isArray(ipfsPaths)) { - ipfsPaths = [ipfsPaths] - } - - map(ipfsPaths, (path, cb) => { - if (typeof path !== 'string') { - let cid - - try { - cid = new CID(path) - } catch (err) { - return cb(err) - } - - return cb(null, cid.buffer) - } - - let parsedPath - try { - parsedPath = exports.parseIpfsPath(path) - } catch (err) { - return cb(err) - } - - const rootHash = new CID(parsedPath.hash) - const rootLinks = parsedPath.links - - if (!rootLinks.length) { - return cb(null, rootHash.buffer) - } - - objectAPI.get(rootHash, follow.bind(null, rootHash, rootLinks)) - - // recursively follow named links to the target node - function follow (cid, links, err, obj) { - if (err) { - return cb(err) - } - - if (!links.length) { - // done tracing, obj is the target node - return cb(null, cid.buffer) - } - - const linkName = links[0] - const nextObj = obj.Links.find(link => link.Name === linkName) - - if (!nextObj) { - return cb(new Error(`no link named "${linkName}" under ${cid}`)) - } - - objectAPI.get(nextObj.Hash, follow.bind(null, nextObj.Hash, links.slice(1))) - } - }, callback) -}) - -exports.normalizePath = normalizePath -exports.parseIpfsPath = parseIpfsPath -exports.resolvePath = resolvePath - -},{"async/map":137,"cids":222,"is-ipfs":775,"promisify-es6":1443}],715:[function(require,module,exports){ -'use strict' - -const CID = require('cids') - -/** -* Stringify a CID encoded in the requested base, upgrading to v1 if necessary. -* -* Setting upgrade to false will disable automatic CID upgrading from v0 to v1 -* which is necessary if the multibase is something other than base58btc. Note -* that it will also not apply the encoding (since v0 CIDs can only be encoded -* as base58btc). -* -* @param {CID|Buffer|String} cid The CID to encode -* @param {Object} [options] Optional options -* @param {String} [options.base] Name of multibase codec to encode the CID with -* @param {Boolean} [options.upgrade] Automatically upgrade v0 CIDs to v1 when -* necessary. Default: true. -* @returns {String} -*/ -exports.cidToString = (cid, options) => { - options = options || {} - options.upgrade = options.upgrade !== false - - if (!CID.isCID(cid)) { - cid = new CID(cid) - } - - if (cid.version === 0 && options.base && options.base !== 'base58btc') { - if (!options.upgrade) return cid.toString() - cid = cid.toV1() - } - - return cid.toBaseEncodedString(options.base) -} - -},{"cids":222}],716:[function(require,module,exports){ -'use strict' - -const assert = require('assert') -const mortice = require('mortice') -const noop = () => {} - -// Wrap mortice to present a callback interface -class Mutex { - constructor (repoOwner, options = {}) { - this.mutex = mortice(options.morticeId, { - singleProcess: repoOwner - }) - - this.log = options.log || noop - this.lockId = 0 - } - - readLock (lockedFn, cb) { - if (lockedFn && cb) { - this._lock('readLock').then(release => { - lockedFn((err, res) => { - release() - - cb(err, res) - }) - }, cb) - return - } - - return this._lock('readLock') - } - - writeLock (lockedFn, cb) { - if (lockedFn && cb) { - this._lock('writeLock').then(release => { - lockedFn((err, res) => { - release() - - cb(err, res) - }) - }, cb) - return - } - - return this._lock('writeLock') - } - - /** - * Request a read or write lock - * - * @param {String} type The type of lock: readLock / writeLock - * @returns {Promise} - */ - async _lock (type) { - assert(typeof type === 'string', `first argument to Mutex.${type}() must be a string, got ${typeof type}`) - - const lockId = this.lockId++ - this.log(`[${lockId}] ${type} requested`) - - // Get a Promise for the lock, wrap it for logging - const release = await this.mutex[type]() - - this.log(`[${lockId}] ${type} started`) - - return () => { - this.log(`[${lockId}] ${type} released`) - release() - } - } -} - -module.exports = Mutex - -},{"assert":78,"mortice":1307}],717:[function(require,module,exports){ -'use strict' -const hashlru = require('hashlru') - -/** - * Time Aware Least Recent Used Cache - * @see https://arxiv.org/pdf/1801.00390 - * @todo move this to ipfs-utils or it's own package - * - * @class TLRU - */ -class TLRU { - /** - * Creates an instance of TLRU. - * - * @param {number} maxSize - * @memberof TLRU - */ - constructor (maxSize) { - this.lru = hashlru(maxSize) - } - - /** - * Get the value from the a key - * - * @param {string} key - * @returns {any} - * @memberof TLRU - */ - get (key) { - const value = this.lru.get(key) - if (value) { - if ((value.expire) && (value.expire < Date.now())) { - this.lru.remove(key) - return undefined - } - } - return value.value - } - - /** - * Set a key value pair - * - * @param {string} key - * @param {any} value - * @param {number} ttl - in miliseconds - * @memberof TLRU - */ - set (key, value, ttl) { - this.lru.set(key, { value, expire: Date.now() + ttl }) - } - - /** - * Find if the cache has the key - * - * @param {string} key - * @returns {boolean} - * @memberof TLRU - */ - has (key) { - const value = this.get(key) - if (value) { - return true - } - return false - } - - /** - * Remove key - * - * @param {string} key - * @memberof TLRU - */ - remove (key) { - this.lru.remove(key) - } - - /** - * Clears the cache - * - * @memberof TLRU - */ - clear () { - this.lru.clear() - } -} - -module.exports = TLRU - -},{"hashlru":436}],718:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],719:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],720:[function(require,module,exports){ -arguments[4][554][0].apply(exports,arguments) -},{"blakejs":168,"buffer":217,"dup":554}],721:[function(require,module,exports){ -arguments[4][555][0].apply(exports,arguments) -},{"./blake":720,"./sha":723,"./utils":724,"buffer":217,"dup":555,"js-sha3":719,"murmurhash3js-revisited":1352}],722:[function(require,module,exports){ -arguments[4][556][0].apply(exports,arguments) -},{"./crypto":721,"buffer":217,"dup":556,"err-code":718,"multihashes":1331}],723:[function(require,module,exports){ -arguments[4][557][0].apply(exports,arguments) -},{"buffer":217,"dup":557}],724:[function(require,module,exports){ -arguments[4][558][0].apply(exports,arguments) -},{"buffer":217,"dup":558}],725:[function(require,module,exports){ -'use strict' - -exports.util = require('./util.js') -exports.resolver = require('./resolver.js') -exports.codec = exports.util.codec -exports.defaultHashAlg = exports.util.defaultHashAlg - -},{"./resolver.js":726,"./util.js":727}],726:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') - -const util = require('./util') - -/** - * Resolves a path within a CBOR block. - * - * Returns the value or a link and the partial mising path. This way the - * IPLD Resolver can fetch the link and continue to resolve. - * - * @param {Buffer} binaryBlob - Binary representation of a CBOR block - * @param {string} [path='/'] - Path that should be resolved - * @returns {Object} result - Result of the path it it was resolved successfully - * @returns {*} result.value - Value the path resolves to - * @returns {string} result.remainderPath - If the path resolves half-way to a - * link, then the `remainderPath` is the part after the link that can be used - * for further resolving - */ -exports.resolve = (binaryBlob, path) => { - let node = util.deserialize(binaryBlob) - - const parts = path.split('/').filter(Boolean) - while (parts.length) { - const key = parts.shift() - if (node[key] === undefined) { - throw new Error(`Object has no property '${key}'`) - } - - node = node[key] - if (CID.isCID(node)) { - return { - value: node, - remainderPath: parts.join('/') - } - } - } - - return { - value: node, - remainderPath: '' - } -} - -const traverse = function * (node, path) { - // Traverse only objects and arrays - if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' || - node === null) { - return - } - for (const item of Object.keys(node)) { - const nextpath = path === undefined ? item : path + '/' + item - yield nextpath - yield * traverse(node[item], nextpath) - } -} - -/** - * Return all available paths of a block. - * - * @generator - * @param {Buffer} binaryBlob - Binary representation of a CBOR block - * @yields {string} - A single path - */ -exports.tree = function * (binaryBlob) { - const node = util.deserialize(binaryBlob) - - yield * traverse(node) -} - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./util":727,"cids":222}],727:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const cbor = require('borc') -const multicodec = require('multicodec') -const multihashing = require('multihashing-async') -const CID = require('cids') -const isCircular = require('is-circular') - -// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692 -const CID_CBOR_TAG = 42 - -function tagCID (cid) { - if (typeof cid === 'string') { - cid = new CID(cid).buffer - } else if (CID.isCID(cid)) { - cid = cid.buffer - } - - return new cbor.Tagged(CID_CBOR_TAG, Buffer.concat([ - Buffer.from('00', 'hex'), // thanks jdag - cid - ])) -} - -function replaceCIDbyTAG (dagNode) { - let circular - try { - circular = isCircular(dagNode) - } catch (e) { - circular = false - } - if (circular) { - throw new Error('The object passed has circular references') - } - - function transform (obj) { - if (!obj || Buffer.isBuffer(obj) || typeof obj === 'string') { - return obj - } - - if (Array.isArray(obj)) { - return obj.map(transform) - } - - if (CID.isCID(obj)) { - return tagCID(obj) - } - - const keys = Object.keys(obj) - - if (keys.length > 0) { - // Recursive transform - const out = {} - keys.forEach((key) => { - if (typeof obj[key] === 'object') { - out[key] = transform(obj[key]) - } else { - out[key] = obj[key] - } - }) - return out - } else { - return obj - } - } - - return transform(dagNode) -} - -exports = module.exports - -exports.codec = multicodec.DAG_CBOR -exports.defaultHashAlg = multicodec.SHA2_256 - -const defaultTags = { - [CID_CBOR_TAG]: (val) => { - // remove that 0 - val = val.slice(1) - return new CID(val) - } -} -const defaultSize = 64 * 1024 // current decoder heap size, 64 Kb -let currentSize = defaultSize -const defaultMaxSize = 64 * 1024 * 1024 // max heap size when auto-growing, 64 Mb -let maxSize = defaultMaxSize -let decoder = null - -/** - * Configure the underlying CBOR decoder. - * - * @param {Object} [options] - The options the decoder takes. The decoder will reset to the defaul values if no options are given. - * @param {number} [options.size=65536] - The current heap size used in CBOR parsing, this may grow automatically as larger blocks are encountered up to `maxSize` - * @param {number} [options.maxSize=67108864] - The maximum size the CBOR parsing heap is allowed to grow to before `dagCBOR.util.deserialize()` returns an error - * @param {Object} [options.tags] - An object whose keys are CBOR tag numbers and values are transform functions that accept a `value` and return a decoded representation of that `value` - */ -exports.configureDecoder = (options) => { - let tags = defaultTags - - if (options) { - if (typeof options.size === 'number') { - currentSize = options.size - } - if (typeof options.maxSize === 'number') { - maxSize = options.maxSize - } - if (options.tags) { - tags = Object.assign({}, defaultTags, options && options.tags) - } - } else { - // no options, reset to defaults - currentSize = defaultSize - maxSize = defaultMaxSize - } - - let decoderOptions = { - tags: tags, - size: currentSize - } - - decoder = new cbor.Decoder(decoderOptions) - // borc edits opts.size in-place so we can capture _actual_ size - currentSize = decoderOptions.size -} - -exports.configureDecoder() // Setup default cbor.Decoder - -/** - * Serialize internal representation into a binary CBOR block. - * - * @param {Object} node - Internal representation of a CBOR block - * @returns {Buffer} - The encoded binary representation - */ -exports.serialize = (node) => { - const nodeTagged = replaceCIDbyTAG(node) - const serialized = cbor.encode(nodeTagged) - - return serialized -} - -/** - * Deserialize CBOR block into the internal representation. - * - * @param {Buffer} data - Binary representation of a CBOR block - * @returns {Object} - An object that conforms to the IPLD Data Model - */ -exports.deserialize = (data) => { - if (data.length > currentSize && data.length <= maxSize) { - exports.configureDecoder({ size: data.length }) - } - - if (data.length > currentSize) { - throw new Error('Data is too large to deserialize with current decoder') - } - - const deserialized = decoder.decodeFirst(data) - - return deserialized -} - -/** - * Calculate the CID of the binary blob. - * - * @param {Object} binaryBlob - Encoded IPLD Node - * @param {Object} [userOptions] - Options to create the CID - * @param {number} [userOptions.cidVersion=1] - CID version number - * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format - * @returns {Promise.} - */ -exports.cid = async (binaryBlob, userOptions) => { - const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg } - const options = Object.assign(defaultOptions, userOptions) - - const multihash = await multihashing(binaryBlob, options.hashAlg) - const codecName = multicodec.print[exports.codec] - const cid = new CID(options.cidVersion, codecName, multihash) - - return cid -} - -}).call(this,require("buffer").Buffer) -},{"borc":177,"buffer":217,"cids":222,"is-circular":768,"multicodec":1325,"multihashing-async":722}],728:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],729:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],730:[function(require,module,exports){ -arguments[4][554][0].apply(exports,arguments) -},{"blakejs":168,"buffer":217,"dup":554}],731:[function(require,module,exports){ -arguments[4][555][0].apply(exports,arguments) -},{"./blake":730,"./sha":733,"./utils":734,"buffer":217,"dup":555,"js-sha3":729,"murmurhash3js-revisited":1352}],732:[function(require,module,exports){ -arguments[4][556][0].apply(exports,arguments) -},{"./crypto":731,"buffer":217,"dup":556,"err-code":728,"multihashes":1331}],733:[function(require,module,exports){ -arguments[4][557][0].apply(exports,arguments) -},{"buffer":217,"dup":557}],734:[function(require,module,exports){ -arguments[4][558][0].apply(exports,arguments) -},{"buffer":217,"dup":558}],735:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') -const assert = require('assert') -const withIs = require('class-is') -const visibility = require('../visibility') - -// Link represents an IPFS Merkle DAG Link between Nodes. -class DAGLink { - constructor (name, size, cid) { - assert(cid, 'A link requires a cid to point to') - // assert(size, 'A link requires a size') - // note - links should include size, but this assert is disabled - // for now to maintain consistency with go-ipfs pinset - - this._name = name || '' - this._nameBuf = null - this._size = size - this._cid = new CID(cid) - - // Make sure we have a nice public API that can be used by an IPLD resolver - visibility.hidePrivateFields(this) - visibility.addEnumerableGetters(this, ['Hash', 'Name', 'Tsize']) - } - - toString () { - return `DAGLink <${this._cid.toBaseEncodedString()} - name: "${this.Name}", size: ${this.Tsize}>` - } - - toJSON () { - if (!this._json) { - this._json = Object.freeze({ - name: this.Name, - size: this.Tsize, - cid: this.Hash.toBaseEncodedString() - }) - } - - return Object.assign({}, this._json) - } - - get Name () { - return this._name - } - - // Memoize the Buffer representation of name - // We need this to sort the links, otherwise - // we will reallocate new buffers every time - get nameAsBuffer () { - if (this._nameBuf !== null) { - return this._nameBuf - } - - this._nameBuf = Buffer.from(this._name) - return this._nameBuf - } - - set Name (name) { - throw new Error("Can't set property: 'name' is immutable") - } - - get Tsize () { - return this._size - } - - set Tsize (size) { - throw new Error("Can't set property: 'size' is immutable") - } - - get Hash () { - return this._cid - } - - set Hash (cid) { - throw new Error("Can't set property: 'cid' is immutable") - } -} - -exports = module.exports = withIs(DAGLink, { className: 'DAGLink', symbolName: '@ipld/js-ipld-dag-pb/daglink' }) -exports.util = require('./util') - -}).call(this,require("buffer").Buffer) -},{"../visibility":748,"./util":736,"assert":78,"buffer":217,"cids":222,"class-is":224}],736:[function(require,module,exports){ -'use strict' - -const DAGLink = require('./index') - -function createDagLinkFromB58EncodedHash (link) { - return new DAGLink( - link.Name || link.name || '', - link.Tsize || link.Size || link.size || 0, - link.Hash || link.hash || link.multihash || link.cid - ) -} - -exports = module.exports -exports.createDagLinkFromB58EncodedHash = createDagLinkFromB58EncodedHash - -},{"./index":735}],737:[function(require,module,exports){ -'use strict' - -const dagNodeUtil = require('./util') -const cloneLinks = dagNodeUtil.cloneLinks -const cloneData = dagNodeUtil.cloneData -const toDAGLink = dagNodeUtil.toDAGLink -const DAGLink = require('../dag-link') -const DAGNode = require('./index') -const create = require('./create') - -const asDAGLink = async (link) => { - if (DAGLink.isDAGLink(link)) { - // It's a DAGLink instance - // no need to do anything - return link - } - - if (DAGNode.isDAGNode(link)) { - // It's a DAGNode instance - // convert to link - return toDAGLink(link, {}) - } - - // It's a Object with name, multihash/hash/cid and size - return new DAGLink(link.Name || link.name, link.Tsize || link.size, link.Hash || link.multihash || link.hash || link.cid) -} - -const addLink = async (node, link) => { - const links = cloneLinks(node) - const data = cloneData(node) - - const dagLink = await asDAGLink(link) - links.push(dagLink) - return create(data, links) -} - -module.exports = addLink - -},{"../dag-link":735,"./create":740,"./index":741,"./util":743}],738:[function(require,module,exports){ -'use strict' - -/** - * Adds a link with its name as property to an object. - * - * The link won't be added if its name is empty or matches one of the existing - * properties. - * - * @param {Object} object - The object that contains an array of links - * @param {string} name - The name of the link to add - * @param {numner} position - The position within the array of links - */ -const addNamedLink = (object, name, position) => { - const skipNames = ['', ...Object.keys(object)] - if (skipNames.includes(name)) { - return - } - Object.defineProperty(object, name, { - enumerable: true, - configurable: true, - get: () => object._links[position].Hash - }) -} - -module.exports = addNamedLink - -},{}],739:[function(require,module,exports){ -'use strict' - -const dagNodeUtil = require('./util') -const cloneLinks = dagNodeUtil.cloneLinks -const cloneData = dagNodeUtil.cloneData -const create = require('./create') - -function clone (dagNode) { - const data = cloneData(dagNode) - const links = cloneLinks(dagNode) - return create(data, links) -} - -module.exports = clone - -},{"./create":740,"./util":743}],740:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const sort = require('stable') -const { - serialize -} = require('../util.js') -const dagNodeUtil = require('./util.js') -const linkSort = dagNodeUtil.linkSort -const DAGNode = require('./index.js') -const DAGLink = require('../dag-link') - -const create = (data, links = []) => { - if (typeof data === 'string') { - data = Buffer.from(data) - } - - if (!Buffer.isBuffer(data)) { - throw new Error('Passed \'data\' is not a buffer or a string!') - } - links = links.map((link) => { - return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link) - }) - links = sort(links, linkSort) - - const serialized = serialize({ - Data: data, - Links: links - }) - - return new DAGNode(data, links, serialized.length) -} - -module.exports = create - -}).call(this,require("buffer").Buffer) -},{"../dag-link":735,"../util.js":747,"./index.js":741,"./util.js":743,"buffer":217,"stable":1714}],741:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const assert = require('assert') -const withIs = require('class-is') -const addNamedLink = require('./addNamedLink') -const visibility = require('../visibility') - -class DAGNode { - constructor (data, links, serializedSize) { - if (serializedSize !== 0) { - assert(serializedSize, 'A DAGNode requires it\'s serialized size') - } - - this._data = data || Buffer.alloc(0) - this._links = links - this._serializedSize = serializedSize - - // Make sure we have a nice public API that can be used by an IPLD resolver - visibility.hidePrivateFields(this) - visibility.addEnumerableGetters(this, ['Data', 'Links']) - - // Add getters for existing links by the name of the link - // This is how paths are traversed in IPFS. Links with names won't - // override existing fields like `data` or `links`. - links.forEach((link, position) => { - addNamedLink(this, link.Name, position) - }) - } - - toJSON () { - if (!this._json) { - this._json = Object.freeze({ - data: this.Data, - links: this._links.map((l) => l.toJSON()), - size: this.size - }) - } - - return Object.assign({}, this._json) - } - - toString () { - return `DAGNode ` - } - - get size () { - if (this._size === undefined) { - this._size = this._links.reduce((sum, l) => sum + l.Tsize, this._serializedSize) - } - - return this._size - } - - set size (size) { - throw new Error("Can't set property: 'size' is immutable") - } - - // Getters for backwards compatible path resolving - get Data () { - return this._data - } - set Data (_) { - throw new Error("Can't set property: 'Data' is immutable") - } - get Links () { - return this._links.map((link) => { - return { - Name: link.Name, - Tsize: link.Tsize, - Hash: link.Hash - } - }) - } - set Links (_) { - throw new Error("Can't set property: 'Links' is immutable") - } -} - -exports = module.exports = withIs(DAGNode, { className: 'DAGNode', symbolName: '@ipld/js-ipld-dag-pb/dagnode' }) -exports.create = require('./create') -exports.clone = require('./clone') -exports.addLink = require('./addLink') -exports.rmLink = require('./rmLink') - -}).call(this,require("buffer").Buffer) -},{"../visibility":748,"./addLink":737,"./addNamedLink":738,"./clone":739,"./create":740,"./rmLink":742,"assert":78,"buffer":217,"class-is":224}],742:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const dagNodeUtil = require('./util') -const cloneLinks = dagNodeUtil.cloneLinks -const cloneData = dagNodeUtil.cloneData -const create = require('./create') -const CID = require('cids') - -const rmLink = (dagNode, nameOrCid) => { - const data = cloneData(dagNode) - let links = cloneLinks(dagNode) - - if (typeof nameOrCid === 'string') { - links = links.filter((link) => link.Name !== nameOrCid) - } else if (Buffer.isBuffer(nameOrCid) || CID.isCID(nameOrCid)) { - links = links.filter((link) => !link.Hash.equals(nameOrCid)) - } else { - throw new Error('second arg needs to be a name or CID') - } - - return create(data, links) -} - -module.exports = rmLink - -}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) -},{"../../../is-buffer/index.js":766,"./create":740,"./util":743,"cids":222}],743:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const DAGLink = require('./../dag-link') -const { - cid, - serialize -} = require('../util') - -exports = module.exports - -function cloneData (dagNode) { - let data - - if (dagNode.Data && dagNode.Data.length > 0) { - data = Buffer.alloc(dagNode.Data.length) - dagNode.Data.copy(data) - } else { - data = Buffer.alloc(0) - } - - return data -} - -function cloneLinks (dagNode) { - return dagNode.Links.slice() -} - -function linkSort (a, b) { - return Buffer.compare(a.nameAsBuffer, b.nameAsBuffer) -} - -/* - * toDAGLink converts a DAGNode to a DAGLink - */ -const toDAGLink = async (node, options = {}) => { - const serialized = serialize(node) - const nodeCid = await cid(serialized) - return new DAGLink(options.name || '', serialized.length, nodeCid) -} - -exports.cloneData = cloneData -exports.cloneLinks = cloneLinks -exports.linkSort = linkSort -exports.toDAGLink = toDAGLink - -}).call(this,require("buffer").Buffer) -},{"../util":747,"./../dag-link":735,"buffer":217}],744:[function(require,module,exports){ -'use strict' - -module.exports = `// An IPFS MerkleDAG Link -message PBLink { - - // multihash of the target object - optional bytes Hash = 1; - - // utf string name. should be unique per object - optional string Name = 2; - - // cumulative size of target object - optional uint64 Tsize = 3; -} - -// An IPFS MerkleDAG Node -message PBNode { - - // refs to other objects - repeated PBLink Links = 2; - - // opaque user data - optional bytes Data = 1; -}` - -},{}],745:[function(require,module,exports){ -'use strict' - -exports.DAGNode = require('./dag-node') -exports.DAGLink = require('./dag-link') - -/* - * Functions to fulfil IPLD Format interface - * https://github.com/ipld/interface-ipld-format - */ -exports.resolver = require('./resolver') -exports.util = require('./util') -exports.codec = exports.util.codec -exports.defaultHashAlg = exports.util.defaultHashAlg - -},{"./dag-link":735,"./dag-node":741,"./resolver":746,"./util":747}],746:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') - -const util = require('./util') - -/** - * Resolves a path within a PB block. - * - * Returns the value or a link and the partial mising path. This way the - * IPLD Resolver can fetch the link and continue to resolve. - * - * @param {Buffer} binaryBlob - Binary representation of a PB block - * @param {string} [path='/'] - Path that should be resolved - * @returns {Object} result - Result of the path it it was resolved successfully - * @returns {*} result.value - Value the path resolves to - * @returns {string} result.remainderPath - If the path resolves half-way to a - * link, then the `remainderPath` is the part after the link that can be used - * for further resolving - */ -exports.resolve = (binaryBlob, path) => { - let node = util.deserialize(binaryBlob) - - const parts = path.split('/').filter(Boolean) - while (parts.length) { - const key = parts.shift() - if (node[key] === undefined) { - throw new Error(`Object has no property '${key}'`) - } - - node = node[key] - if (CID.isCID(node)) { - return { - value: node, - remainderPath: parts.join('/') - } - } - } - - return { - value: node, - remainderPath: '' - } -} - -const traverse = function * (node, path) { - // Traverse only objects and arrays - if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' || - node === null) { - return - } - for (const item of Object.keys(node)) { - const nextpath = path === undefined ? item : path + '/' + item - yield nextpath - yield * traverse(node[item], nextpath) - } -} - -/** - * Return all available paths of a block. - * - * @generator - * @param {Buffer} binaryBlob - Binary representation of a PB block - * @yields {string} - A single path - */ -exports.tree = function * (binaryBlob) { - const node = util.deserialize(binaryBlob) - - yield * traverse(node) -} - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./util":747,"cids":222}],747:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const CID = require('cids') -const protons = require('protons') -const proto = protons(require('./dag.proto.js')) -const DAGLink = require('./dag-link') -const DAGNode = require('./dag-node') -const multicodec = require('multicodec') -const multihashing = require('multihashing-async') - -exports = module.exports - -exports.codec = multicodec.DAG_PB -exports.defaultHashAlg = multicodec.SHA2_256 - -/** - * Calculate the CID of the binary blob. - * - * @param {Object} binaryBlob - Encoded IPLD Node - * @param {Object} [userOptions] - Options to create the CID - * @param {number} [userOptions.cidVersion=1] - CID version number - * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format - * @returns {Promise.} - */ -const cid = async (binaryBlob, userOptions) => { - const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg } - const options = Object.assign(defaultOptions, userOptions) - - const multihash = await multihashing(binaryBlob, options.hashAlg) - const codecName = multicodec.print[exports.codec] - const cid = new CID(options.cidVersion, codecName, multihash) - - return cid -} - -/** - * Serialize internal representation into a binary PB block. - * - * @param {Object} node - Internal representation of a CBOR block - * @returns {Buffer} - The encoded binary representation - */ -const serialize = (node) => { - let data = node.Data - let links = node.Links || [] - - // If the node is not an instance of a DAGNode, the link.hash might be a Base58 encoded string; decode it - if (!DAGNode.isDAGNode(node) && links) { - links = links.map((link) => { - return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link) - }) - } - - const serialized = proto.PBNode.encode(toProtoBuf({ - Data: data, - Links: links - })) - - return serialized -} - -/** - * Deserialize PB block into the internal representation. - * - * @param {Buffer} buffer - Binary representation of a PB block - * @returns {Object} - An object that conforms to the IPLD Data Model - */ -const deserialize = (buffer) => { - const pbn = proto.PBNode.decode(buffer) - - const links = pbn.Links.map((link) => { - return new DAGLink(link.Name, link.Tsize, link.Hash) - }) - - const data = pbn.Data == null ? Buffer.alloc(0) : pbn.Data - - return new DAGNode(data, links, buffer.length) -} - -function toProtoBuf (node) { - const pbn = {} - - if (node.Data && node.Data.length > 0) { - pbn.Data = node.Data - } else { - // NOTE: this has to be null in order to match go-ipfs serialization `null !== new Buffer(0)` - pbn.Data = null - } - - if (node.Links && node.Links.length > 0) { - pbn.Links = node.Links - .map((link) => ({ - Hash: link.Hash.buffer, - Name: link.Name, - Tsize: link.Tsize - })) - } else { - pbn.Links = null - } - - return pbn -} - -exports.serialize = serialize -exports.deserialize = deserialize -exports.cid = cid - -}).call(this,require("buffer").Buffer) -},{"./dag-link":735,"./dag-node":741,"./dag.proto.js":744,"buffer":217,"cids":222,"multicodec":1325,"multihashing-async":732,"protons":1454}],748:[function(require,module,exports){ -'use strict' - -/** - * Make certain getters enumnerable - * - * This can be used to add additional getters that are enumerable and hence - * show up on an `Object.keys()` call. - * - * @param {Object} object - The object it should be applied to - * @param {Array.} fields - The fields that should be made enumnerable - */ -const addEnumerableGetters = (object, fields) => { - for (const field of fields) { - let prop - let proto = object - // Walk up the proottype chain until a property with the given name is - // found - while (prop === undefined) { - proto = Object.getPrototypeOf(proto) - if (proto === null) { - throw new Error(`no getter named '${field}' found`) - } - prop = Object.getOwnPropertyDescriptor(proto, field) - } - - // There is a property with the correct name, but it's not a getter - if (prop.get === undefined) { - throw new Error(`no getter named '${field}' found`) - } - Object.defineProperty(object, field, { - enumerable: true, - get: prop.get - }) - } -} - -/** - * Makes all properties with a leading underscore non-enumerable. - * - * @param {Object} object - The object it should be applied to - */ -const hidePrivateFields = (object) => { - for (const key in object) { - if (key[0] === '_') { - Object.defineProperty(object, key, { enumerable: false }) - } - } -} - -module.exports = { - addEnumerableGetters, - hidePrivateFields -} - -},{}],749:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],750:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],751:[function(require,module,exports){ -arguments[4][554][0].apply(exports,arguments) -},{"blakejs":168,"buffer":217,"dup":554}],752:[function(require,module,exports){ -arguments[4][555][0].apply(exports,arguments) -},{"./blake":751,"./sha":754,"./utils":755,"buffer":217,"dup":555,"js-sha3":750,"murmurhash3js-revisited":1352}],753:[function(require,module,exports){ -arguments[4][556][0].apply(exports,arguments) -},{"./crypto":752,"buffer":217,"dup":556,"err-code":749,"multihashes":1331}],754:[function(require,module,exports){ -arguments[4][557][0].apply(exports,arguments) -},{"buffer":217,"dup":557}],755:[function(require,module,exports){ -arguments[4][558][0].apply(exports,arguments) -},{"buffer":217,"dup":558}],756:[function(require,module,exports){ -'use strict' -const CID = require('cids') -const multihashing = require('multihashing-async') -const multicodec = require('multicodec') - -// binary resolver -module.exports = { - codec: multicodec.RAW, - defaultHashAlg: multicodec.SHA2_256, - resolver: { - /** - * Resolves a path within a Raw block. - * - * Always returns the raw data as value without any remainderPath. - * - * @param {Buffer} binaryBlob - Binary representation of a PB block - * @param {string} [path='/'] - Path that should be resolved (that value is ignored) - * @returns {Object} result - Result of the path it it was resolved successfully - * @returns {*} result.value - The raw data - * @returns {string} result.remainderPath - An empty string - */ - resolve: (binaryBlob, path) => { - return { - value: binaryBlob, - remainderPath: '' - } - }, - /** - * Return all available paths of a block. - * - * @generator - * @param {Buffer} binaryBlob - The raw data - * @returns {Object} - Finished generator with `done: true` - */ - tree: (binaryBlob) => { - return { - done: true - } - } - }, - util: { - deserialize: (data) => { - return data - }, - serialize: (data) => { - return data - }, - /** - * Calculate the CID of the binary blob. - * - * @param {Object} binaryBlob - Encoded IPLD Node - * @param {Object} [userOptions] - Options to create the CID - * @param {number} [userOptions.cidVersion=1] - CID version number - * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format - * @returns {Promise.} - */ - cid: async (binaryBlob, userOptions) => { - const defaultOptions = { cidVersion: 1, hashAlg: module.exports.defaultHashAlg } - const options = Object.assign(defaultOptions, userOptions) - - const multihash = await multihashing(binaryBlob, options.hashAlg) - const codecName = multicodec.print[module.exports.codec] - const cid = new CID(options.cidVersion, codecName, multihash) - - return cid - } - } -} - -},{"cids":222,"multicodec":1325,"multihashing-async":753}],757:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Block = require('ipfs-block') -const CID = require('cids') -const mergeOptions = require('merge-options') -const ipldDagCbor = require('ipld-dag-cbor') -const ipldDagPb = require('ipld-dag-pb') -const ipldRaw = require('ipld-raw') -const multicodec = require('multicodec') -const promisify = require('promisify-es6') -const typical = require('typical') -const { extendIterator } = require('./util') - -class IPLDResolver { - constructor (userOptions) { - const options = mergeOptions(IPLDResolver.defaultOptions, userOptions) - - if (!options.blockService) { - throw new Error('Missing blockservice') - } - this.bs = options.blockService - - // Object with current list of active resolvers - this.resolvers = {} - - if (typeof options.loadFormat !== 'function') { - this.loadFormat = async (codec) => { - const codecName = multicodec.print[codec] - throw new Error(`No resolver found for codec "${codecName}"`) - } - } else { - this.loadFormat = options.loadFormat - } - - // Enable all supplied formats - for (const format of options.formats) { - this.addFormat(format) - } - } - - /** - * Add support for an IPLD Format. - * - * @param {Object} format - The implementation of an IPLD Format. - * @returns {this} - */ - addFormat (format) { - const codec = format.codec - if (this.resolvers[format.format]) { - const codecName = multicodec.print[codec] - throw new Error(`Resolver already exists for codec "${codecName}"`) - } - - this.resolvers[codec] = format - - return this - } - - /** - * Remove support for an IPLD Format. - * - * @param {number} codec - The codec of the IPLD Format to remove. - * @returns {this} - */ - removeFormat (codec) { - if (this.resolvers[codec]) { - delete this.resolvers[codec] - } - - return this - } - - /** - * Retrieves IPLD Nodes along the `path` that is rooted at `cid`. - * - * @param {CID} cid - the CID the resolving starts. - * @param {string} path - the path that should be resolved. - * @returns {Iterable.>} - Returns an async iterator of all the IPLD Nodes that were traversed during the path resolving. Every element is an object with these fields: - * - `remainderPath`: the part of the path that wasn’t resolved yet. - * - `value`: the value where the resolved path points to. If further traversing is possible, then the value is a CID object linking to another IPLD Node. If it was possible to fully resolve the path, value is the value the path points to. So if you need the CID of the IPLD Node you’re currently at, just take the value of the previously returned IPLD Node. - */ - resolve (cid, path) { - if (!CID.isCID(cid)) { - throw new Error('`cid` argument must be a CID') - } - if (typeof path !== 'string') { - throw new Error('`path` argument must be a string') - } - - const generator = async function * () { - // End iteration if there isn't a CID to follow anymore - while (cid !== null) { - const format = await this._getFormat(cid.codec) - - // get block - // use local resolver - // update path value - const block = await promisify(this.bs.get.bind(this.bs))(cid) - const result = format.resolver.resolve(block.data, path) - - // Prepare for the next iteration if there is a `remainderPath` - path = result.remainderPath - let value = result.value - // NOTE vmx 2018-11-29: Not all IPLD Formats return links as - // CIDs yet. Hence try to convert old style links to CIDs - if (Object.keys(value).length === 1 && '/' in value) { - try { - value = new CID(value['/']) - } catch (_error) { - value = null - } - } - cid = CID.isCID(value) ? value : null - - yield { - remainderPath: path, - value - } - } - }.bind(this) - - return extendIterator(generator()) - } - - /** - * Get a node by CID. - * - * @param {CID} cid - The CID of the IPLD Node that should be retrieved. - * @returns {Promise.} - Returns a Promise with the IPLD Node that correspond to the given `cid`. - */ - async get (cid) { - const block = await promisify(this.bs.get.bind(this.bs))(cid) - const format = await this._getFormat(block.cid.codec) - const node = format.util.deserialize(block.data) - - return node - } - - /** - * Get multiple nodes back from an array of CIDs. - * - * @param {Iterable.} cids - The CIDs of the IPLD Nodes that should be retrieved. - * @returns {Iterable.>} - Returns an async iterator with the IPLD Nodes that correspond to the given `cids`. - */ - getMany (cids) { - if (!typical.isIterable(cids) || typeof cids === 'string' || - Buffer.isBuffer(cids)) { - throw new Error('`cids` must be an iterable of CIDs') - } - - const generator = async function * () { - for await (const cid of cids) { - yield this.get(cid) - } - }.bind(this) - - return extendIterator(generator()) - } - - /** - * Stores the given IPLD Node of a recognized IPLD Format. - * - * @param {Object} node - The deserialized IPLD node that should be inserted. - * @param {number} format - The multicodec of the format that IPLD Node should be encoded in. - * @param {Object} [userOptions] - Options is an object with the following properties. - * @param {number} [userOtions.hashAlg=hash algorithm of the given multicodec] - The hashing algorithm that is used to calculate the CID. - * @param {number} [userOptions.cidVersion=1] - The CID version to use. - * @param {boolean} [userOptions.onlyHash=false] - If true the serialized form of the IPLD Node will not be passed to the underlying block store. - * @returns {Promise.} - Returns the CID of the serialized IPLD Nodes. - */ - async put (node, format, userOptions) { - if (format === undefined) { - throw new Error('`put` requires a format') - } - if (typeof format !== 'number') { - throw new Error('`format` parameter must be number (multicodec)') - } - - const formatImpl = await this._getFormat(format) - const defaultOptions = { - hashAlg: formatImpl.defaultHashAlg, - cidVersion: 1, - onlyHash: false - } - const options = mergeOptions(defaultOptions, userOptions) - - const cidOptions = { - cidVersion: options.cidVersion, - hashAlg: options.hashAlg, - onlyHash: options.onlyHash - } - const serialized = formatImpl.util.serialize(node) - const cid = await formatImpl.util.cid(serialized, cidOptions) - - if (!options.onlyHash) { - const block = new Block(serialized, cid) - await promisify(this.bs.put.bind(this.bs))(block) - } - - return cid - } - - /** - * Stores the given IPLD Nodes of a recognized IPLD Format. - * - * @param {Iterable.} nodes - Deserialized IPLD nodes that should be inserted. - * @param {number} format - The multicodec of the format that IPLD Node should be encoded in. - * @param {Object} [userOptions] - Options are applied to any of the `nodes` and is an object with the following properties. - * @param {number} [userOtions.hashAlg=hash algorithm of the given multicodec] - The hashing algorithm that is used to calculate the CID. - * @param {number} [userOptions.cidVersion=1] - The CID version to use. - * @param {boolean} [userOptions.onlyHash=false] - If true the serialized form of the IPLD Node will not be passed to the underlying block store. - * @returns {Iterable.>} - Returns an async iterator with the CIDs of the serialized IPLD Nodes. - */ - putMany (nodes, format, userOptions) { - if (!typical.isIterable(nodes) || typeof nodes === 'string' || - Buffer.isBuffer(nodes)) { - throw new Error('`nodes` must be an iterable') - } - if (format === undefined) { - throw new Error('`put` requires a format') - } - if (typeof format !== 'number') { - throw new Error('`format` parameter must be number (multicodec)') - } - - let options - let formatImpl - - const generator = async function * () { - for await (const node of nodes) { - // Lazy load the options not when the iterator is initialized, but - // when we hit the first iteration. This way the constructor can be - // a synchronous function. - if (options === undefined) { - formatImpl = await this._getFormat(format) - const defaultOptions = { - hashAlg: formatImpl.defaultHashAlg, - cidVersion: 1, - onlyHash: false - } - options = mergeOptions(defaultOptions, userOptions) - } - - yield this.put(node, format, options) - } - }.bind(this) - - return extendIterator(generator()) - } - - /** - * Remove an IPLD Node by the given CID. - * - * @param {CID} cid - The CID of the IPLD Node that should be removed. - * @return {Promise.} The CID of the removed IPLD Node. - */ - async remove (cid) { - return promisify(this.bs.delete.bind(this.bs))(cid) - } - - /** - * Remove IPLD Nodes by the given CIDs. - * - * Throws an error if any of the Blocks can’t be removed. This operation is - * *not* atomic, some Blocks might have already been removed. - * - * @param {Iterable.} cids - The CIDs of the IPLD Nodes that should be removed. - * @return {Iterable.>} Returns an async iterator with the CIDs of the removed IPLD Nodes. - */ - removeMany (cids) { - if (!typical.isIterable(cids) || typeof cids === 'string' || - Buffer.isBuffer(cids)) { - throw new Error('`cids` must be an iterable of CIDs') - } - - const generator = async function * () { - for await (const cid of cids) { - yield this.remove(cid) - } - }.bind(this) - - return extendIterator(generator()) - } - - /** - * Returns all the paths that can be resolved into. - * - * @param {Object} cid - The ID to get the paths from - * @param {string} [offsetPath=''] - the path to start to retrieve the other paths from. - * @param {Object} [userOptions] - * @param {number} [userOptions.recursive=false] - whether to get the paths recursively or not. `false` resolves only the paths of the given CID. - * @returns {Iterable.>} - Returns an async iterator with paths that can be resolved into - */ - tree (cid, offsetPath, userOptions) { - if (typeof offsetPath === 'object') { - userOptions = offsetPath - offsetPath = undefined - } - offsetPath = offsetPath || '' - - const defaultOptions = { - recursive: false - } - const options = mergeOptions(defaultOptions, userOptions) - - // If a path is a link then follow it and return its CID - const maybeRecurse = async (block, treePath) => { - // A treepath we might want to follow recursively - const format = await this._getFormat(block.cid.codec) - const result = format.resolver.resolve(block.data, treePath) - // Something to follow recusively, hence push it into the queue - if (CID.isCID(result.value)) { - return result.value - } else { - return null - } - } - - const generator = async function * () { - // The list of paths that will get returned - const treePaths = [] - // The current block, needed to call `isLink()` on every interation - let block - // The list of items we want to follow recursively. The items are - // an object consisting of the CID and the currently already resolved - // path - const queue = [{ cid, basePath: '' }] - // The path that was already traversed - let basePath - - // End of iteration if there aren't any paths left to return or - // if we don't want to traverse recursively and have already - // returne the first level - while (treePaths.length > 0 || queue.length > 0) { - // There aren't any paths left, get them from the given CID - if (treePaths.length === 0 && queue.length > 0) { - ({ cid, basePath } = queue.shift()) - const format = await this._getFormat(cid.codec) - block = await promisify(this.bs.get.bind(this.bs))(cid) - - const paths = format.resolver.tree(block.data) - treePaths.push(...paths) - } - - const treePath = treePaths.shift() - let fullPath = basePath + treePath - - // Only follow links if recursion is intended - if (options.recursive) { - cid = await maybeRecurse(block, treePath) - if (cid !== null) { - queue.push({ cid, basePath: fullPath + '/' }) - } - } - - // Return it if it matches the given offset path, but is not the - // offset path itself - if (fullPath.startsWith(offsetPath) && - fullPath.length > offsetPath.length) { - if (offsetPath.length > 0) { - fullPath = fullPath.slice(offsetPath.length + 1) - } - - yield fullPath - } - } - }.bind(this) - - return extendIterator(generator()) - } - - /* */ - /* internals */ - /* */ - async _getFormat (codec) { - // TODO vmx 2019-01-24: Once all CIDs support accessing the codec code - // instead of the name, remove this part - if (typeof codec === 'string') { - const constantName = codec.toUpperCase().replace(/-/g, '_') - codec = multicodec[constantName] - } - - if (this.resolvers[codec]) { - return this.resolvers[codec] - } - - // If not supported, attempt to dynamically load this format - const format = await this.loadFormat(codec) - this.addFormat(format) - return format - } -} - -/** - * Default options for IPLD. - */ -IPLDResolver.defaultOptions = { - formats: [ipldDagCbor, ipldDagPb, ipldRaw] -} - -module.exports = IPLDResolver - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./util":758,"cids":222,"ipfs-block":491,"ipld-dag-cbor":725,"ipld-dag-pb":745,"ipld-raw":756,"merge-options":1298,"multicodec":1325,"promisify-es6":1443,"typical":1764}],758:[function(require,module,exports){ -'use strict' - -exports.first = async (iterator) => { - for await (const value of iterator) { - return value - } -} - -exports.last = async (iterator) => { - let value - for await (value of iterator) { - // Intentionally empty - } - return value -} - -exports.all = async (iterator) => { - const values = [] - for await (const value of iterator) { - values.push(value) - } - return values -} - -exports.extendIterator = (iterator) => { - iterator.first = () => exports.first(iterator) - iterator.last = () => exports.last(iterator) - iterator.all = () => exports.all(iterator) - return iterator -} - -},{}],759:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":760,"_process":1438,"dup":247}],760:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":761}],761:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],762:[function(require,module,exports){ -'use strict' - -exports.ERR_IPNS_EXPIRED_RECORD = 'ERR_IPNS_EXPIRED_RECORD' -exports.ERR_UNRECOGNIZED_VALIDITY = 'ERR_UNRECOGNIZED_VALIDITY' -exports.ERR_SIGNATURE_CREATION = 'ERR_SIGNATURE_CREATION' -exports.ERR_SIGNATURE_VERIFICATION = 'ERR_SIGNATURE_VERIFICATION' -exports.ERR_UNRECOGNIZED_FORMAT = 'ERR_UNRECOGNIZED_FORMAT' -exports.ERR_PEER_ID_FROM_PUBLIC_KEY = 'ERR_PEER_ID_FROM_PUBLIC_KEY' -exports.ERR_PUBLIC_KEY_FROM_ID = 'ERR_PUBLIC_KEY_FROM_ID' -exports.ERR_UNDEFINED_PARAMETER = 'ERR_UNDEFINED_PARAMETER' - -},{}],763:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const base32Encode = require('base32-encode') -const NanoDate = require('timestamp-nano') -const { Key } = require('interface-datastore') -const crypto = require('libp2p-crypto') -const PeerId = require('peer-id') -const multihash = require('multihashes') - -const debug = require('debug') -const log = debug('jsipns') -log.error = debug('jsipns:error') - -const ipnsEntryProto = require('./pb/ipns.proto') -const { parseRFC3339 } = require('./utils') -const ERRORS = require('./errors') - -const ID_MULTIHASH_CODE = multihash.names.id - -const namespace = '/ipns/' - -/** - * Creates a new ipns entry and signs it with the given private key. - * The ipns entry validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision. - * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`. - * - * @param {Object} privateKey private key for signing the record. - * @param {string} value value to be stored in the record. - * @param {number} seq number representing the current version of the record. - * @param {number|string} lifetime lifetime of the record (in milliseconds). - * @param {function(Error, entry)} [callback] - */ -const create = (privateKey, value, seq, lifetime, callback) => { - // Validity in ISOString with nanoseconds precision and validity type EOL - const isoValidity = new NanoDate(Date.now() + Number(lifetime)).toString() - const validityType = ipnsEntryProto.ValidityType.EOL - _create(privateKey, value, seq, isoValidity, validityType, callback) -} - -/** - * Same as create(), but instead of generating a new Date, it receives the intended expiration time - * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided. - * @param {Object} privateKey private key for signing the record. - * @param {string} value value to be stored in the record. - * @param {number} seq number representing the current version of the record. - * @param {string} expiration expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision. - * @param {function(Error, entry)} [callback] - */ -const createWithExpiration = (privateKey, value, seq, expiration, callback) => { - const validityType = ipnsEntryProto.ValidityType.EOL - _create(privateKey, value, seq, expiration, validityType, callback) -} - -const _create = (privateKey, value, seq, isoValidity, validityType, callback) => { - sign(privateKey, value, validityType, isoValidity, (error, signature) => { - if (error) { - log.error('record signature creation failed') - return callback(Object.assign(new Error('record signature verification failed'), { code: ERRORS.ERR_SIGNATURE_CREATION })) - } - - const entry = { - value: value, - signature: signature, - validityType: validityType, - validity: isoValidity, - sequence: seq - } - - log(`ipns entry for ${value} created`) - return callback(null, entry) - }) -} - -/** - * Validates the given ipns entry against the given public key. - * - * @param {Object} publicKey public key for validating the record. - * @param {Object} entry ipns entry record. - * @param {function(Error)} [callback] - */ -const validate = (publicKey, entry, callback) => { - const { value, validityType, validity } = entry - const dataForSignature = ipnsEntryDataForSig(value, validityType, validity) - - // Validate Signature - publicKey.verify(dataForSignature, entry.signature, (err, isValid) => { - if (err || !isValid) { - log.error('record signature verification failed') - return callback(Object.assign(new Error('record signature verification failed'), { code: ERRORS.ERR_SIGNATURE_VERIFICATION })) - } - - // Validate according to the validity type - if (validityType === ipnsEntryProto.ValidityType.EOL) { - let validityDate - - try { - validityDate = parseRFC3339(validity.toString()) - } catch (e) { - log.error('unrecognized validity format (not an rfc3339 format)') - return callback(Object.assign(new Error('unrecognized validity format (not an rfc3339 format)'), { code: ERRORS.ERR_UNRECOGNIZED_FORMAT })) - } - - if (validityDate < Date.now()) { - log.error('record has expired') - return callback(Object.assign(new Error('record has expired'), { code: ERRORS.ERR_IPNS_EXPIRED_RECORD })) - } - } else if (validityType) { - log.error('unrecognized validity type') - return callback(Object.assign(new Error('unrecognized validity type'), { code: ERRORS.ERR_UNRECOGNIZED_VALIDITY })) - } - - log(`ipns entry for ${value} is valid`) - return callback(null, null) - }) -} - -/** - * Embed the given public key in the given entry. While not strictly required, - * some nodes (eg. DHT servers) may reject IPNS entries that don't embed their - * public keys as they may not be able to validate them efficiently. - * As a consequence of nodes needing to validade a record upon receipt, they need - * the public key associated with it. For olde RSA keys, it is easier if we just - * send this as part of the record itself. For newer ed25519 keys, the public key - * can be embedded in the peerId. - * - * @param {Object} publicKey public key to embed. - * @param {Object} entry ipns entry record. - * @param {function(Error)} [callback] - * @return {Void} - */ -const embedPublicKey = (publicKey, entry, callback) => { - if (!publicKey || !publicKey.bytes || !entry) { - const error = 'one or more of the provided parameters are not defined' - - log.error(error) - return callback(Object.assign(new Error(error), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) - } - - // Create a peer id from the public key. - PeerId.createFromPubKey(publicKey.bytes, (err, peerId) => { - if (err) { - log.error(err) - return callback(Object.assign(new Error(err), { code: ERRORS.ERR_PEER_ID_FROM_PUBLIC_KEY })) - } - - // Try to extract the public key from the ID. If we can, no need to embed it - let extractedPublicKey - try { - extractedPublicKey = extractPublicKeyFromId(peerId) - } catch (err) { - log.error(err) - return callback(Object.assign(new Error(err), { code: ERRORS.ERR_PUBLIC_KEY_FROM_ID })) - } - - if (extractedPublicKey) { - return callback(null, null) - } - - // If we failed to extract the public key from the peer ID, embed it in the record. - try { - entry.pubKey = crypto.keys.marshalPublicKey(publicKey) - } catch (err) { - log.error(err) - return callback(err) - } - callback(null, entry) - }) -} - -/** - * Extracts a public key matching `pid` from the ipns record. - * - * @param {Object} peerId peer identifier object. - * @param {Object} entry ipns entry record. - * @param {function(Error)} [callback] - * @return {Void} - */ -const extractPublicKey = (peerId, entry, callback) => { - if (!entry || !peerId) { - const error = 'one or more of the provided parameters are not defined' - - log.error(error) - return callback(Object.assign(new Error(error), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) - } - - if (entry.pubKey) { - let pubKey - try { - pubKey = crypto.keys.unmarshalPublicKey(entry.pubKey) - } catch (err) { - log.error(err) - return callback(err) - } - return callback(null, pubKey) - } - - if (peerId.pubKey) { - callback(null, peerId.pubKey) - } else { - callback(Object.assign(new Error('no public key is available'), { code: ERRORS.ERR_UNDEFINED_PARAMETER })) - } -} - -// rawStdEncoding with RFC4648 -const rawStdEncoding = (key) => base32Encode(key, 'RFC4648', { padding: false }) - -/** - * Get key for storing the record locally. - * Format: /ipns/${base32()} - * - * @param {Buffer} key peer identifier object. - * @returns {string} - */ -const getLocalKey = (key) => new Key(`/ipns/${rawStdEncoding(key)}`) - -/** - * Get key for sharing the record in the routing mechanism. - * Format: ${base32(/ipns/)}, ${base32(/pk/)} - * - * @param {Buffer} pid peer identifier represented by the multihash of the public key as Buffer. - * @returns {Object} containing the `nameKey` and the `ipnsKey`. - */ -const getIdKeys = (pid) => { - const pkBuffer = Buffer.from('/pk/') - const ipnsBuffer = Buffer.from('/ipns/') - - return { - routingPubKey: new Key(Buffer.concat([pkBuffer, pid])), // Added on https://github.com/ipfs/js-ipns/pull/8#issue-213857876 (pkKey will be deprecated in a future release) - pkKey: new Key(rawStdEncoding(Buffer.concat([pkBuffer, pid]))), - routingKey: new Key(Buffer.concat([ipnsBuffer, pid])), // Added on https://github.com/ipfs/js-ipns/pull/6#issue-213631461 (ipnsKey will be deprecated in a future release) - ipnsKey: new Key(rawStdEncoding(Buffer.concat([ipnsBuffer, pid]))) - } -} - -// Sign ipns record data -const sign = (privateKey, value, validityType, validity, callback) => { - const dataForSignature = ipnsEntryDataForSig(value, validityType, validity) - - privateKey.sign(dataForSignature, (err, signature) => { - if (err) { - return callback(err) - } - return callback(null, signature) - }) -} - -// Utility for getting the validity type code name of a validity -const getValidityType = (validityType) => { - if (validityType.toString() === '0') { - return 'EOL' - } else { - const error = `unrecognized validity type ${validityType.toString()}` - log.error(error) - throw Object.assign(new Error(error), { code: ERRORS.ERR_UNRECOGNIZED_VALIDITY }) - } -} - -// Utility for creating the record data for being signed -const ipnsEntryDataForSig = (value, validityType, validity) => { - const valueBuffer = Buffer.from(value) - const validityTypeBuffer = Buffer.from(getValidityType(validityType)) - const validityBuffer = Buffer.from(validity) - - return Buffer.concat([valueBuffer, validityBuffer, validityTypeBuffer]) -} - -// Utility for extracting the public key from a peer-id -const extractPublicKeyFromId = (peerId) => { - const decodedId = multihash.decode(peerId.id) - - if (decodedId.code !== ID_MULTIHASH_CODE) { - return null - } - - return crypto.keys.unmarshalPublicKey(decodedId.digest) -} - -const marshal = ipnsEntryProto.encode - -const unmarshal = ipnsEntryProto.decode - -const validator = { - validate: (marshalledData, key, callback) => { - const receivedEntry = unmarshal(marshalledData) - const bufferId = key.slice('/ipns/'.length) - let peerId - - try { - peerId = PeerId.createFromBytes(bufferId) - } catch (err) { - return callback(err) - } - - // extract public key - extractPublicKey(peerId, receivedEntry, (err, pubKey) => { - if (err) { - return callback(err) - } - - // Record validation - validate(pubKey, receivedEntry, (err) => { - if (err) { - return callback(err) - } - - callback(null, true) - }) - }) - }, - select: (dataA, dataB, callback) => { - const entryA = unmarshal(dataA) - const entryB = unmarshal(dataB) - - const index = entryA.sequence > entryB.sequence ? 0 : 1 - - if (typeof callback !== 'function') { - return index - } - - callback(null, index) - } -} - -module.exports = { - // create ipns entry record - create, - // create ipns entry record specifying the expiration time - createWithExpiration, - // validate ipns entry record - validate, - // embed public key in the record - embedPublicKey, - // extract public key from the record - extractPublicKey, - // get key for storing the entry locally - getLocalKey, - // get keys for routing - getIdKeys, - // marshal - marshal, - // unmarshal - unmarshal, - // validator - validator, - // namespace - namespace, - namespaceLength: namespace.length -} - -}).call(this,require("buffer").Buffer) -},{"./errors":762,"./pb/ipns.proto":764,"./utils":765,"base32-encode":159,"buffer":217,"debug":759,"interface-datastore":458,"libp2p-crypto":905,"multihashes":1331,"peer-id":1432,"timestamp-nano":1750}],764:[function(require,module,exports){ -'use strict' - -const protons = require('protons') - -/* eslint-disable no-tabs */ -const message = ` -message IpnsEntry { - enum ValidityType { - EOL = 0; // setting an EOL says "this record is valid until..." - } - - required bytes value = 1; - required bytes signature = 2; - - optional ValidityType validityType = 3; - optional bytes validity = 4; - - optional uint64 sequence = 5; - - optional uint64 ttl = 6; - - // in order for nodes to properly validate a record upon receipt, they need the public - // key associated with it. For old RSA keys, its easiest if we just send this as part of - // the record itself. For newer ed25519 keys, the public key can be embedded in the - // peerID, making this field unnecessary. - optional bytes pubKey = 7; -} -` - -module.exports = protons(message).IpnsEntry - -},{"protons":1454}],765:[function(require,module,exports){ -'use strict' - -/** - * Convert a JavaScript date into an `RFC3339Nano` formatted - * string. - * - * @param {Date} time - * @returns {string} - */ -module.exports.toRFC3339 = (time) => { - const year = time.getUTCFullYear() - const month = String(time.getUTCMonth() + 1).padStart(2, '0') - const day = String(time.getUTCDate()).padStart(2, '0') - const hour = String(time.getUTCHours()).padStart(2, '0') - const minute = String(time.getUTCMinutes()).padStart(2, '0') - const seconds = String(time.getUTCSeconds()).padStart(2, '0') - const milliseconds = time.getUTCMilliseconds() - const nanoseconds = milliseconds * 1000 * 1000 - - return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z` -} - -/** - * Parses a date string formatted as `RFC3339Nano` into a - * JavaScript Date object. - * - * @param {string} time - * @returns {Date} - */ -module.exports.parseRFC3339 = (time) => { - const rfc3339Matcher = new RegExp( - // 2006-01-02T - '(\\d{4})-(\\d{2})-(\\d{2})T' + - // 15:04:05 - '(\\d{2}):(\\d{2}):(\\d{2})' + - // .999999999Z - '\\.(\\d+)Z' - ) - const m = String(time).trim().match(rfc3339Matcher) - - if (!m) { - throw new Error('Invalid format') - } - - const year = parseInt(m[1], 10) - const month = parseInt(m[2], 10) - 1 - const date = parseInt(m[3], 10) - const hour = parseInt(m[4], 10) - const minute = parseInt(m[5], 10) - const second = parseInt(m[6], 10) - const millisecond = parseInt(m[7].slice(0, -6), 10) - - return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond)) -} - -},{}],766:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],767:[function(require,module,exports){ -'use strict'; - -var fnToStr = Function.prototype.toString; - -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } catch (e) { - return false; // not a function - } -}; - -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { return false; } - fnToStr.call(value); - return true; - } catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isCallable(value) { - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - if (typeof value === 'function' && !value.prototype) { return true; } - if (hasToStringTag) { return tryFunctionObject(value); } - if (isES6ClassFn(value)) { return false; } - var strClass = toStr.call(value); - return strClass === fnClass || strClass === genClass; -}; - -},{}],768:[function(require,module,exports){ -var Node = require('./lib/node') - -module.exports = isCircular - -/** - * checks whether the object is circular - * @param {object} obj - object to check circularity for - * @return {Boolean} true if obj is circular, false if it is not - */ -function isCircular (obj) { - if (!(obj instanceof Object)) { - throw new TypeError('"obj" must be an object (or inherit from it)') - } - return _isCircular(obj) -} - -/** - * @private - * checks whether the object is circular - * @param {object} obj - object to check circularity for - * @param {Node} parentList - linked-list that contains all the object's parents - * @return {Boolean} true if obj is circular, false if it is not - */ -function _isCircular (obj, parentList) { - parentList = new Node(obj, parentList) - - // breadth-first search for circular object - for (var key in obj) { - var val = obj[key] - if (val instanceof Object) { - if (parentList.contains(val) || _isCircular(val, parentList)) { - return true - } - } - } - - return false -} - -},{"./lib/node":769}],769:[function(require,module,exports){ -module.exports = Node - -/** - * a linked-list node - * @class - * @param {any} value - node's value - * @param {Node} next - next node - */ -function Node (value, next) { - this.value = value - this.next = next -} - -/** - * checks if this node or any of its children has the value - * @param {any} value - value to check if linked-list contains - * @return {boolean} true if the list contains the value; false if not - */ -Node.prototype.contains = function (value) { - var cursor = this - - while (cursor) { - if (cursor.value === value) return true - cursor = cursor.next - } - - return false -} - -},{}],770:[function(require,module,exports){ -'use strict' - -// Adapted from RFC 2181 (See section 11) -// -// The RFC defines a Domain Name to be at most 255 chars including seperators -// between labels. -// Subdomains are labels plus a seperator. A label is a string starting and -// ending with an alphanum, with dashes allowed in the middle. It is between 1 and 63 chars. -// -// We make some assumptions below that go beyond the RFC. We assume the TLD -// to be at least 2 chars. The regex also allows domains longer than 255 chars, -// but allows at most 127 subdomains, as assuming a lower-bound of one char per -// subdomain will yield 252, and adding a TLD of 2 chars sums to 254. -/* -(?: // Group 1: This is for subdomain, which is composed of a label and a seperator (length = [1, 63] + 1) - [a-z0-9] - (?: - [a-z0-9\-]{0,61} // Limited to 61 chars as we have at least two chars if we reach this group (61 + 2 = 63 which is the limit) - [a-z0-9] - )? - \. // Label seperator -){0,126} // If we assume the lower-bound of 1 char labels, we can at most have 126 groups before approaching the total limit of 255 chars -(?: // Group 2: Assume that the TLD is at least 2 chars (for sanity) - [a-z0-9] - [a-z0-9\-]{0,61} - [a-z0-9] -) -\.? // Some consider a trailing dot to be considered valid as it signifies the root of the domain tree - */ -var domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i - -/** - * Test whether a string is a valid domain name, optionally checking for a root dot as well - * @param {String} domainName - * @param {Boolean} rootDot Check for a root dot eg. 'example.com.'. Defaults to false - * @return {Boolean} - */ -module.exports = function isDomainName (domainName, rootDot) { - if (rootDot == null) rootDot = false - - if (domainName.length < 2) return false - if (domainName.length > 255) return false - - var lastChar = domainName[domainName.length - 1] - if (rootDot) { - if (lastChar !== '.') return false - } else { - if (lastChar === '.') return false - } - - return domainNameRegex.test(domainName) -} - -},{}],771:[function(require,module,exports){ -'use strict'; -var toString = Object.prototype.toString; - -module.exports = function (x) { - return toString.call(x) === '[object Function]'; -}; - -},{}],772:[function(require,module,exports){ -module.exports = isFunction - -var toString = Object.prototype.toString - -function isFunction (fn) { - var string = toString.call(fn) - return string === '[object Function]' || - (typeof fn === 'function' && string !== '[object RegExp]') || - (typeof window !== 'undefined' && - // IE8 and below - (fn === window.setTimeout || - fn === window.alert || - fn === window.confirm || - fn === window.prompt)) -}; - -},{}],773:[function(require,module,exports){ -/** - * Returns a `Boolean` on whether or not the a `String` starts with '0x' - * @param {String} str the string input value - * @return {Boolean} a boolean if it is or is not hex prefixed - * @throws if the str input is not a string - */ -module.exports = function isHexPrefixed(str) { - if (typeof str !== 'string') { - throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); - } - - return str.slice(0, 2) === '0x'; -} - -},{}],774:[function(require,module,exports){ -'use strict'; -const ipRegex = require('ip-regex'); - -const isIp = module.exports = x => ipRegex({exact: true}).test(x); -isIp.v4 = x => ipRegex.v4({exact: true}).test(x); -isIp.v6 = x => ipRegex.v6({exact: true}).test(x); - -},{"ip-regex":462}],775:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const base58 = require('bs58') -const multihash = require('multihashes') -const multibase = require('multibase') -const Multiaddr = require('multiaddr') -const mafmt = require('mafmt') -const CID = require('cids') - -const urlPattern = /^https?:\/\/[^/]+\/(ip(f|n)s)\/((\w+).*)/ -const pathPattern = /^\/(ip(f|n)s)\/((\w+).*)/ -const defaultProtocolMatch = 1 -const defaultHashMath = 4 - -const fqdnPattern = /^https?:\/\/([^/]+)\.(ip(?:f|n)s)\.[^/]+/ -const fqdnHashMatch = 1 -const fqdnProtocolMatch = 2 - -function isMultihash (hash) { - const formatted = convertToString(hash) - try { - const buffer = Buffer.from(base58.decode(formatted)) - multihash.decode(buffer) - return true - } catch (e) { - return false - } -} - -function isMultibase (hash) { - try { - return multibase.isEncoded(hash) - } catch (e) { - return false - } -} - -function isCID (hash) { - try { - new CID(hash) // eslint-disable-line no-new - return true - } catch (e) { - return false - } -} - -function isMultiaddr (input) { - if (!input) return false - if (Multiaddr.isMultiaddr(input)) return true - try { - new Multiaddr(input) // eslint-disable-line no-new - return true - } catch (e) { - return false - } -} - -function isPeerMultiaddr (input) { - return isMultiaddr(input) && mafmt.IPFS.matches(input) -} - -function isIpfs (input, pattern, protocolMatch = defaultProtocolMatch, hashMatch = defaultHashMath) { - const formatted = convertToString(input) - if (!formatted) { - return false - } - - const match = formatted.match(pattern) - if (!match) { - return false - } - - if (match[protocolMatch] !== 'ipfs') { - return false - } - - let hash = match[hashMatch] - - if (hash && pattern === fqdnPattern) { - // when doing checks for subdomain context - // ensure hash is case-insensitive - // (browsers force-lowercase authority compotent anyway) - hash = hash.toLowerCase() - } - - return isCID(hash) -} - -function isIpns (input, pattern, protocolMatch = defaultProtocolMatch, hashMatch) { - const formatted = convertToString(input) - if (!formatted) { - return false - } - const match = formatted.match(pattern) - if (!match) { - return false - } - - if (match[protocolMatch] !== 'ipns') { - return false - } - - if (hashMatch && pattern === fqdnPattern) { - let hash = match[hashMatch] - // when doing checks for subdomain context - // ensure hash is case-insensitive - // (browsers force-lowercase authority compotent anyway) - hash = hash.toLowerCase() - return isCID(hash) - } - - return true -} - -function isString (input) { - return typeof input === 'string' -} - -function convertToString (input) { - if (Buffer.isBuffer(input)) { - return base58.encode(input) - } - - if (isString(input)) { - return input - } - - return false -} - -const ipfsSubdomain = (url) => isIpfs(url, fqdnPattern, fqdnProtocolMatch, fqdnHashMatch) -const ipnsSubdomain = (url) => isIpns(url, fqdnPattern, fqdnProtocolMatch, fqdnHashMatch) - -module.exports = { - multihash: isMultihash, - multiaddr: isMultiaddr, - peerMultiaddr: isPeerMultiaddr, - cid: isCID, - base32cid: (cid) => (isMultibase(cid) === 'base32' && isCID(cid)), - ipfsSubdomain: ipfsSubdomain, - ipnsSubdomain: ipnsSubdomain, - subdomain: (url) => (ipfsSubdomain(url) || ipnsSubdomain(url)), - subdomainPattern: fqdnPattern, - ipfsUrl: (url) => isIpfs(url, urlPattern), - ipnsUrl: (url) => isIpns(url, urlPattern), - url: (url) => (isIpfs(url, urlPattern) || isIpns(url, urlPattern)), - urlPattern: urlPattern, - ipfsPath: (path) => isIpfs(path, pathPattern), - ipnsPath: (path) => isIpns(path, pathPattern), - path: (path) => (isIpfs(path, pathPattern) || isIpns(path, pathPattern)), - pathPattern: pathPattern, - urlOrPath: (x) => (isIpfs(x, urlPattern) || isIpns(x, urlPattern) || isIpfs(x, pathPattern) || isIpns(x, pathPattern)), - cidPath: path => isString(path) && !isCID(path) && isIpfs(`/ipfs/${path}`, pathPattern) -} - -}).call(this,require("buffer").Buffer) -},{"bs58":213,"buffer":217,"cids":222,"mafmt":1296,"multiaddr":1314,"multibase":1322,"multihashes":1331}],776:[function(require,module,exports){ -'use strict'; -var toString = Object.prototype.toString; - -module.exports = function (x) { - var prototype; - return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); -}; - -},{}],777:[function(require,module,exports){ -module.exports = isPromise; - -function isPromise(obj) { - return obj && typeof obj.then === 'function'; -} -},{}],778:[function(require,module,exports){ - -function isFunction (f) { - return 'function' === typeof f -} - -function isDuplex (d) { - return 'object' === typeof d && isSource(d.source) && isSink(d.sink) -} - -function isSource (s) { - return isFunction(s) && s.length === 2 -} - -function isSink (s) { - return isFunction(s) && s.length === 1 -} - -exports.isDuplex = isDuplex -exports.isSource = isSource -exports.isSink = isSink -//can't do is through, it will appear as a sink til you git it a source. - - -},{}],779:[function(require,module,exports){ -module.exports = isTypedArray -isTypedArray.strict = isStrictTypedArray -isTypedArray.loose = isLooseTypedArray - -var toString = Object.prototype.toString -var names = { - '[object Int8Array]': true - , '[object Int16Array]': true - , '[object Int32Array]': true - , '[object Uint8Array]': true - , '[object Uint8ClampedArray]': true - , '[object Uint16Array]': true - , '[object Uint32Array]': true - , '[object Float32Array]': true - , '[object Float64Array]': true -} - -function isTypedArray(arr) { - return ( - isStrictTypedArray(arr) - || isLooseTypedArray(arr) - ) -} - -function isStrictTypedArray(arr) { - return ( - arr instanceof Int8Array - || arr instanceof Int16Array - || arr instanceof Int32Array - || arr instanceof Uint8Array - || arr instanceof Uint8ClampedArray - || arr instanceof Uint16Array - || arr instanceof Uint32Array - || arr instanceof Float32Array - || arr instanceof Float64Array - ) -} - -function isLooseTypedArray(arr) { - return names[toString.call(arr)] -} - -},{}],780:[function(require,module,exports){ -arguments[4][420][0].apply(exports,arguments) -},{"dup":420}],781:[function(require,module,exports){ -'use strict'; - -const crypto = self.crypto || self.msCrypto; -const { Buffer } = require('buffer'); - -// limit of Crypto.getRandomValues() -// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues -const MAX_BYTES = 65536; - -function oldBrowser() { - throw new Error( - 'Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11' - ); -} - -if (crypto && crypto.getRandomValues) { - module.exports = randomBytes; -} else { - module.exports = oldBrowser; -} - -function randomBytes(size) { - const bytes = new Uint8Array(size); - let generated = 0; - - if (size > 0) { - // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { - while (generated < size) { - if (generated + MAX_BYTES > size) { - crypto.getRandomValues( - bytes.subarray(generated, generated + (size - generated)) - ); - generated += size - generated; - } else { - crypto.getRandomValues( - bytes.subarray(generated, generated + MAX_BYTES) - ); - generated += MAX_BYTES; - } - } - } else { - crypto.getRandomValues(bytes); - } - } - - return Buffer.from(bytes); -} - -},{"buffer":217}],782:[function(require,module,exports){ -const http = require('./lib/http') -const https = http -const URL = self.URL - -module.exports = { - http, - https, - getRequest: (options, cb) => { - let protocol = 'http:' - - if (typeof options === 'string') { - const url = new URL(options) - protocol = url.protocol - } else if (options.protocol) { - protocol = options.protocol - } - - return protocol === 'http:' ? http.request(options, cb) : https.request(options, cb) - } -} - -},{"./lib/http":784}],783:[function(require,module,exports){ -function isFunction (value) { - return typeof value === 'function' -} - -module.exports = { - fetch: 'fetch' in self && isFunction(self.fecth), - writableStream: 'WritableStream' in self && isFunction(self.WritableStream), - abortController: 'AbortController' in self && isFunction(self.AbortController), - arrayBuffer: 'ArrayBuffer' in self -} -},{}],784:[function(require,module,exports){ -(function (global){ -var ClientRequest = require('./request') -var IncomingMessage = require('./incoming-message') -var statusCodes = require('builtin-status-codes') -var URL = self.URL - - -const request = (opts, cb) => { - if (typeof opts === 'string') { - - opts = new URL(opts, self.location.protocol + '//' +self.location.host) - opts.path = opts.pathname + opts.search - opts.auth = (opts.username && opts.password) ? opts.username + ':' + opts.password : null - } else { - opts = Object.assign({}, opts) - } - - // Normally, the page is loaded from http or https, so not specifying a protocol - // will result in a (valid) protocol-relative url. However, this won't work if - // the protocol is something else, like 'file:' - var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' - - var protocol = opts.protocol || defaultProtocol - var host = opts.hostname || opts.host - var port = opts.port - var path = opts.path || '/' - - // Necessary for IPv6 addresses - if (host && host.indexOf(':') !== -1) - host = '[' + host + ']' - - // This may be a relative url. The browser should always be able to interpret it correctly. - opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path - opts.method = (opts.method || 'GET').toUpperCase() - opts.headers = opts.headers || {} - - // Also valid opts.auth, opts.mode - - var req = new ClientRequest(opts) - if (cb) - req.on('response', cb) - return req -} - -const get = (opts, cb) => { - var req = request(opts, cb) - req.end() - return req -} - -const Agent = function () {} -Agent.defaultMaxSockets = 4 - -const METHODS = [ - 'CHECKOUT', - 'CONNECT', - 'COPY', - 'DELETE', - 'GET', - 'HEAD', - 'LOCK', - 'M-SEARCH', - 'MERGE', - 'MKACTIVITY', - 'MKCOL', - 'MOVE', - 'NOTIFY', - 'OPTIONS', - 'PATCH', - 'POST', - 'PROPFIND', - 'PROPPATCH', - 'PURGE', - 'PUT', - 'REPORT', - 'SEARCH', - 'SUBSCRIBE', - 'TRACE', - 'UNLOCK', - 'UNSUBSCRIBE' -] - -module.exports = { - Agent, - ClientRequest, - IncomingMessage, - METHODS, - STATUS_CODES: statusCodes, - get, - globalAgent : new Agent(), - request, - maxHeaderSize: '8KB' - -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./incoming-message":785,"./request":786,"builtin-status-codes":218}],785:[function(require,module,exports){ -(function (process,Buffer){ -var capability = require('./capability') -var inherits = require('inherits') -var stream = require('readable-stream') - -var IncomingMessage = function (response, mode, fetchTimer) { - stream.Readable.call(this) - - this._mode = mode - this.headers = {} - this.rawHeaders = [] - this.trailers = {} - this.rawTrailers = [] - - // Fake the 'close' event, but only once 'end' fires - this.on('end', () => { - // The nextTick is necessary to prevent the 'request' module from causing an infinite loop - process.nextTick(() =>this.emit('close')) - }) - - this._fetchResponse = response - - this.url = response.url - this.statusCode = response.status - this.statusMessage = response.statusText - - response.headers.forEach((header, key) => { - this.headers[key.toLowerCase()] = header - this.rawHeaders.push(key, header) - }) - - if (capability.writableStream) { - var writable = new WritableStream({ - write: chunk => { - return new Promise((resolve, reject) => { - if (this._destroyed) { - reject() - } else if(this.push(Buffer.from(chunk))) { - resolve() - } else { - this._resumeFetch = resolve - } - }) - }, - close: () => { - clearTimeout(fetchTimer) - if (!this._destroyed){ - this.push(null) - } - }, - abort: err => { - if (!this._destroyed){ - this.emit('error', err) - } - } - }) - - try { - response.body - .pipeTo(writable) - .catch(err => { - console.log(err); - self.clearTimeout(fetchTimer) - if (!this._destroyed){ - this.emit('error', err) - } - }) - return - } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this - } - // fallback for when writableStream or pipeTo aren't available - var reader = response.body.getReader() - - function read (context) { - reader.read() - .then(result => { - if (context._destroyed){ - return - } - if (result.done) { - clearTimeout(fetchTimer) - context.push(null) - return - } - context.push(Buffer.from(result.value)) - read(context) - }) - .catch(err => { - clearTimeout(fetchTimer) - if (!context._destroyed){ - context.emit('error', err) - } - }) - } - - read(this) - -} - -inherits(IncomingMessage, stream.Readable) - -IncomingMessage.prototype._read = function () { - var resolve = this._resumeFetch - if (resolve) { - this._resumeFetch = null - resolve() - } -} - -module.exports = IncomingMessage -}).call(this,require('_process'),require("buffer").Buffer) -},{"./capability":783,"_process":1438,"buffer":217,"inherits":453,"readable-stream":801}],786:[function(require,module,exports){ -(function (Buffer){ -var capability = require('./capability') -var inherits = require('inherits') -var IncomingMessage = require('./incoming-message') -var stream = require('readable-stream') - -var fetch = self.fetch - -var ClientRequest = module.exports = function (opts) { - stream.Writable.call(this) - - this._opts = opts - this._body = [] - this._headers = {} - if (opts.auth) - this.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) - - - Object.keys(opts.headers).forEach(name => { - this.setHeader(name, opts.headers[name]) - }) - - this._mode = 'fetch' - this._fetchTimer = null - - this.on('finish', () => this._onFinish()) -} - -inherits(ClientRequest, stream.Writable) - -ClientRequest.prototype.setHeader = function (name, value) { - var lowerName = name.toLowerCase() - // This check is not necessary, but it prevents warnings from browsers about setting unsafe - // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but - // http-browserify did it, so I will too. - if (unsafeHeaders.indexOf(lowerName) !== -1){ - return - } - this._headers[lowerName] = value -} - -ClientRequest.prototype.getHeader = function (name) { - var header = this._headers[name.toLowerCase()] - if (header) - return header.value - return null -} - -ClientRequest.prototype.removeHeader = function (name) { - delete this._headers[name.toLowerCase()] -} - -ClientRequest.prototype._onFinish = function () { - if (this._destroyed) - return - var opts = this._opts - - var headersObj = this._headers - var body = null - if (opts.method !== 'GET' && opts.method !== 'HEAD') { - body = new Blob(this._body, { - type: (headersObj['content-type'] || {}).value || '' - }); - } - - var signal = null - if (capability.abortController) { - var controller = new AbortController() - signal = controller.signal - this._fetchAbortController = controller - - if ('requestTimeout' in opts && opts.requestTimeout !== 0) { - this._fetchTimer = setTimeout(() => { - this.emit('requestTimeout') - if (this._fetchAbortController) - this._fetchAbortController.abort() - }, opts.requestTimeout) - } - } - - fetch(this._opts.url, { - method: this._opts.method, - headers: this._headers, - body: body || undefined, - mode: 'cors', - credentials: opts.withCredentials ? 'include' : 'same-origin', - signal: signal - }) - .then(response => { - this._fetchResponse = response - this._connect() - }, reason => { - clearTimeout(this._fetchTimer) - if (!this._destroyed) - this.emit('error', reason) - }) -} - -ClientRequest.prototype._connect = function () { - if (this._destroyed) - return - - this._response = new IncomingMessage(this._fetchResponse, this._mode, this._fetchTimer) - this._response.on('error', (err) => this.emit('error', err)) - - this.emit('response', this._response) -} - -ClientRequest.prototype._write = function (chunk, encoding, cb) { - this._body.push(chunk) - cb() -} - -ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { - this._destroyed = true - - - clearTimeout(this._fetchTimer) - - if (this._response) - this._response._destroyed = true - if (this._xhr) - this._xhr.abort() - else if (this._fetchAbortController) - this._fetchAbortController.abort() -} - -ClientRequest.prototype.end = function (data, encoding, cb) { - if (typeof data === 'function') { - cb = data - data = undefined - } - - stream.Writable.prototype.end.call(this, data, encoding, cb) -} - -ClientRequest.prototype.flushHeaders = function () {} -ClientRequest.prototype.setTimeout = function () {} -ClientRequest.prototype.setNoDelay = function () {} -ClientRequest.prototype.setSocketKeepAlive = function () {} - -// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method -var unsafeHeaders = [ - 'accept-charset', - 'accept-encoding', - 'access-control-request-headers', - 'access-control-request-method', - 'connection', - 'content-length', - 'cookie', - 'cookie2', - 'date', - 'dnt', - 'expect', - 'host', - 'keep-alive', - 'origin', - 'referer', - 'te', - 'trailer', - 'transfer-encoding', - 'upgrade', - 'via' -] - -}).call(this,require("buffer").Buffer) -},{"./capability":783,"./incoming-message":785,"buffer":217,"inherits":453,"readable-stream":801}],787:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],788:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],789:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":791,"./_stream_writable":793,"_process":1438,"dup":90,"inherits":453}],790:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":792,"dup":91,"inherits":453}],791:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":787,"../experimentalWarning":788,"./_stream_duplex":789,"./internal/streams/async_iterator":794,"./internal/streams/buffer_list":795,"./internal/streams/destroy":796,"./internal/streams/state":799,"./internal/streams/stream":800,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],792:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":787,"./_stream_duplex":789,"dup":93,"inherits":453}],793:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":787,"./_stream_duplex":789,"./internal/streams/destroy":796,"./internal/streams/state":799,"./internal/streams/stream":800,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],794:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":797,"_process":1438,"dup":95}],795:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],796:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],797:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":787,"dup":98}],798:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":787,"./end-of-stream":797,"dup":99}],799:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":787,"dup":100}],800:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],801:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":789,"./lib/_stream_passthrough.js":790,"./lib/_stream_readable.js":791,"./lib/_stream_transform.js":792,"./lib/_stream_writable.js":793,"./lib/internal/streams/end-of-stream.js":797,"./lib/internal/streams/pipeline.js":798,"dup":102}],802:[function(require,module,exports){ -'use strict'; - -const { - URLWithLegacySupport, - format, - URLSearchParams, - defaultBase -} = require('./src/url'); -const relative = require('./src/relative'); - -module.exports = { - URL: URLWithLegacySupport, - URLSearchParams, - format, - relative, - defaultBase -}; - -},{"./src/relative":803,"./src/url":804}],803:[function(require,module,exports){ -'use strict'; - -const { URLWithLegacySupport, format } = require('./url'); - -module.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => { - let protocol = location.protocol ? - location.protocol.replace(':', '') : - 'http'; - - // Check protocol map - protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':'; - let urlParsed; - - try { - urlParsed = new URLWithLegacySupport(url); - } catch (err) { - urlParsed = {}; - } - - const base = Object.assign({}, location, { - protocol: protocol || urlParsed.protocol, - host: location.host || urlParsed.host - }); - - return new URLWithLegacySupport(url, format(base)).toString(); -}; - -},{"./url":804}],804:[function(require,module,exports){ -'use strict'; - -const defaultBase = self.location ? - self.location.protocol + '//' + self.location.host : - ''; -const URL = self.URL; - -class URLWithLegacySupport { - constructor(url, base = defaultBase) { - this.super = new URL(url, base); - this.path = this.pathname + this.search; - this.auth = - this.username && this.password ? - this.username + ':' + this.password : - null; - - this.query = - this.search && this.search.startsWith('?') ? - this.search.slice(1) : - null; - } - - get hash() { - return this.super.hash; - } - get host() { - return this.super.host; - } - get hostname() { - return this.super.hostname; - } - get href() { - return this.super.href; - } - get origin() { - return this.super.origin; - } - get password() { - return this.super.password; - } - get pathname() { - return this.super.pathname; - } - get port() { - return this.super.port; - } - get protocol() { - return this.super.protocol; - } - get search() { - return this.super.search; - } - get searchParams() { - return this.super.searchParams; - } - get username() { - return this.super.username; - } - - set hash(hash) { - this.super.hash = hash; - } - set host(host) { - this.super.host = host; - } - set hostname(hostname) { - this.super.hostname = hostname; - } - set href(href) { - this.super.href = href; - } - set origin(origin) { - this.super.origin = origin; - } - set password(password) { - this.super.password = password; - } - set pathname(pathname) { - this.super.pathname = pathname; - } - set port(port) { - this.super.port = port; - } - set protocol(protocol) { - this.super.protocol = protocol; - } - set search(search) { - this.super.search = search; - } - set searchParams(searchParams) { - this.super.searchParams = searchParams; - } - set username(username) { - this.super.username = username; - } - - createObjectURL(o) { - return this.super.createObjectURL(o); - } - revokeObjectURL(o) { - this.super.revokeObjectURL(o); - } - toJSON() { - return this.super.toJSON(); - } - toString() { - return this.super.toString(); - } - format() { - return this.toString(); - } -} - -function format(obj) { - if (typeof obj === 'string') { - const url = new URL(obj); - - return url.toString(); - } - - if (!(obj instanceof URL)) { - const userPass = - obj.username && obj.password ? - `${obj.username}:${obj.password}@` : - ''; - const auth = obj.auth ? obj.auth + '@' : ''; - const port = obj.port ? ':' + obj.port : ''; - const protocol = obj.protocol ? obj.protocol + '//' : ''; - const host = obj.host || ''; - const hostname = obj.hostname || ''; - const search = obj.search || (obj.query ? '?' + obj.query : ''); - const hash = obj.hash || ''; - const pathname = obj.pathname || ''; - const path = obj.path || pathname + search; - - return `${protocol}${userPass || auth}${host || - hostname + port}${path}${hash}`; - } -} - -module.exports = { - URLWithLegacySupport, - URLSearchParams: self.URLSearchParams, - defaultBase, - format -}; - -},{}],805:[function(require,module,exports){ -var stream = require('stream') - - -function isStream (obj) { - return obj instanceof stream.Stream -} - - -function isReadable (obj) { - return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' -} - - -function isWritable (obj) { - return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' -} - - -function isDuplex (obj) { - return isReadable(obj) && isWritable(obj) -} - - -module.exports = isStream -module.exports.isReadable = isReadable -module.exports.isWritable = isWritable -module.exports.isDuplex = isDuplex - -},{"stream":1715}],806:[function(require,module,exports){ -const rawPipe = (...fns) => { - let res - while (fns.length) { - res = fns.shift()(res) - } - return res -} - -const isIterable = obj => obj && ( - typeof obj[Symbol.asyncIterator] === 'function' || - typeof obj[Symbol.iterator] === 'function' || - typeof obj.next === 'function' // Probably, right? -) - -const isDuplex = obj => obj && typeof obj.sink === 'function' && isIterable(obj.source) - -const duplexPipelineFn = duplex => source => { - duplex.sink(source) // TODO: error on sink side is unhandled rejection - this is the same as pull streams - return duplex.source -} - -const pipe = (...fns) => { - // Duplex at start: wrap in function and return duplex source - if (isDuplex(fns[0])) { - const duplex = fns[0] - fns[0] = () => duplex.source - // Iterable at start: wrap in function - } else if (isIterable(fns[0])) { - const source = fns[0] - fns[0] = () => source - } - - if (fns.length > 1) { - // Duplex at end: use duplex sink - if (isDuplex(fns[fns.length - 1])) { - fns[fns.length - 1] = fns[fns.length - 1].sink - } - } - - if (fns.length > 2) { - // Duplex in the middle, consume source with duplex sink and return duplex source - for (let i = 1; i < fns.length - 1; i++) { - if (isDuplex(fns[i])) { - fns[i] = duplexPipelineFn(fns[i]) - } - } - } - - return rawPipe(...fns) -} - -module.exports = pipe -module.exports.pipe = pipe -module.exports.rawPipe = rawPipe -module.exports.isIterable = isIterable -module.exports.isDuplex = isDuplex - -},{}],807:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],808:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],809:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":811,"./_stream_writable":813,"_process":1438,"dup":90,"inherits":453}],810:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":812,"dup":91,"inherits":453}],811:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":807,"../experimentalWarning":808,"./_stream_duplex":809,"./internal/streams/async_iterator":814,"./internal/streams/buffer_list":815,"./internal/streams/destroy":816,"./internal/streams/state":819,"./internal/streams/stream":820,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],812:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":807,"./_stream_duplex":809,"dup":93,"inherits":453}],813:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":807,"./_stream_duplex":809,"./internal/streams/destroy":816,"./internal/streams/state":819,"./internal/streams/stream":820,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],814:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":817,"_process":1438,"dup":95}],815:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],816:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],817:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":807,"dup":98}],818:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":807,"./end-of-stream":817,"dup":99}],819:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":807,"dup":100}],820:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],821:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":809,"./lib/_stream_passthrough.js":810,"./lib/_stream_readable.js":811,"./lib/_stream_transform.js":812,"./lib/_stream_writable.js":813,"./lib/internal/streams/end-of-stream.js":817,"./lib/internal/streams/pipeline.js":818,"dup":102}],822:[function(require,module,exports){ -(function (Buffer){ -const { Readable, Writable, Duplex } = require('stream') -const getIterator = require('get-iterator') -const Fifo = require('p-fifo') -const END_CHUNK = Buffer.alloc(0) - -module.exports = function toDuplex (duplex, options) { - options = options || {} - - let reading = false - const fifo = new Fifo() - - duplex = { - sink: duplex.sink, - source: duplex.source ? getIterator(duplex.source) : null - } - - let Stream = Duplex - if (!duplex.source) { - Stream = Writable - } else if (!duplex.sink) { - Stream = Readable - } - - Object.assign( - options, - duplex.source ? { - async read (size) { - if (reading) return - reading = true - - try { - while (true) { - const { value, done } = await duplex.source.next(size) - if (done) return this.push(null) - if (!this.push(value)) break - } - } catch (err) { - this.emit('error', err) - } finally { - reading = false - } - } - } : {}, - duplex.sink ? { - write (chunk, enc, cb) { - fifo.push(chunk).then(() => cb(), cb) - }, - final (cb) { - fifo.push(END_CHUNK).then(() => cb(), cb) - } - } : {} - ) - - const stream = new Stream(options) - - if (duplex.sink) { - duplex.sink({ - [Symbol.asyncIterator] () { - return this - }, - async next () { - const chunk = await fifo.shift() - return chunk === END_CHUNK ? { done: true } : { value: chunk } - }, - async throw (err) { - stream.destroy(err) - return { done: true } - }, - async return () { - stream.destroy() - return { done: true } - } - }) - } - - return stream -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"get-iterator":388,"p-fifo":1397,"stream":821}],823:[function(require,module,exports){ -'use strict' - -const toTransform = require('./transform') -const toDuplex = require('./duplex') - -function toReadable (source, options) { - return toDuplex({ source }, options) -} - -function toWritable (sink, options) { - return toDuplex({ sink }, options) -} - -module.exports = toReadable -module.exports.readable = toReadable -module.exports.writable = toWritable -module.exports.transform = toTransform -module.exports.duplex = toDuplex - -},{"./duplex":822,"./transform":824}],824:[function(require,module,exports){ -const toDuplex = require('./duplex') -const defer = require('p-defer') - -module.exports = function toTransform (transform, options) { - const { promise, resolve } = defer() - - const source = (async function * () { - const it = await promise - for await (const chunk of it) yield chunk - })() - - return toDuplex({ sink: s => resolve(transform(s)), source }, options) -} - -},{"./duplex":822,"p-defer":1396}],825:[function(require,module,exports){ -(function(){ - - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Basic JavaScript BN library - subset useful for RSA encryption. - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary&0xffffff)==0xefcafe); - - // (public) Constructor - function BigInteger(a,b,c) { - 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); - } - - // return new, unset BigInteger - function nbi() { return new BigInteger(null); } - - // 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. - - // 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; - } - 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; - } - var inBrowser = typeof navigator !== "undefined"; - if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; - } - else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; - } - else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; - } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; - } - - // (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+this.DV; - else this.t = 0; - } - - // return bigint initialized to value - function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - - // (protected) set from string and radix - function bnpFromString(s,b) { - 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 { this.fromRadix(s,b); return; } - this.t = 0; - this.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) - this[this.t++] = x; - else if(sh+k > this.DB) { - this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); - } - else - this[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; - } - - // (public) return string representation in given radix - function bnToString(b) { - if(this.s < 0) return "-"+this.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 this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this[i]&((1<>(p+=this.DB-k); - } - else { - d = (this[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } - } - if(d > 0) m = true; - if(m) r += int2char(d); - } - } - return m?r:"0"; - } - - // (public) -this - function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - - // (public) |this| - function bnAbs() { return (this.s<0)?this.negate():this; } - - // (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; - } - - // 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; - } - - // (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)); - } - - // (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; - } - - // (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; - } - - // (protected) r = this << n - function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r[i+ds+1] = (this[i]>>cbs)|c; - c = (this[i]&bm)<= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); - } - - // (protected) r = this >> n - function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r[i-ds-1] |= (this[i]&bm)<>bs; - } - if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c -= a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r[i++] = this.DV+c; - else if(c > 0) r[i++] = c; - r.t = i; - r.clamp(); - } - - // (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); - } - - // (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(); - } - - // (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 pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.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<1)?y[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 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)?this.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); - } - - // (public) this mod a - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; - } - - // Modular reduction using "classic" algorithm - function Classic(m) { this.m = m; } - function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { return x; } - function cReduce(x) { x.divRemTo(this.m,null,x); } - function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - - // (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; - } - - // 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; - } - - // xR mod m - function montConvert(x) { - var r = nbi(); - 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; - } - - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - - // 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); - } - - // r = "x^2/R mod m"; x != r - function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - - // r = "xy/R mod m"; x,y != r - function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - - // (protected) true iff this is even - function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } - - // (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 = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); - } - - // (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 - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - - // public - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Extended JavaScript BN functions, required for RSA private ops. - - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - // (public) - function bnClone() { var r = nbi(); this.copyTo(r); return r; } - - // (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))<>24; } - - // (public) return value as short (assumes DB>=16) - function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } - - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } - - // (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; - } - - // (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 = nbi(), z = nbi(), 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; - } - - // (protected) convert from radix string - function bnpFromRadix(s,b) { - this.fromInt(0); - if(b == null) b = 10; - var cs = this.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) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } - } - if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); - } - if(mi) BigInteger.ZERO.subTo(this,this); - } - - // (protected) alternate constructor - function bnpFromNumber(a,b,c) { - if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } - } - } - 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< 0) { - if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this[i]&((1<>(p+=this.DB-8); - } - else { - d = (this[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - - function bnEquals(a) { return(this.compareTo(a)==0); } - function bnMin(a) { return(this.compareTo(a)<0)?this:a; } - function bnMax(a) { return(this.compareTo(a)>0)?this:a; } - - // (protected) r = this op a (bitwise) - function bnpBitwiseTo(a,op,r) { - var i, f, m = Math.min(a.t,this.t); - for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); - if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r[i] = op(this[i],f); - r.t = this.t; - } - else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); - r.t = a.t; - } - r.s = op(this.s,a.s); - r.clamp(); - } - - // (public) this & a - function op_and(x,y) { return x&y; } - function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - - // (public) this | a - function op_or(x,y) { return x|y; } - function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - - // (public) this ^ a - function op_xor(x,y) { return x^y; } - function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - - // (public) this & ~a - function op_andnot(x,y) { return x&~y; } - function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - - // (public) ~this - function bnNot() { - var r = nbi(); - for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; - } - - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; - } - - // 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; - } - - // (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; - } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; - } - - // (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; - } - - // (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); - } - - // (protected) this op (1<>= this.DB; - } - if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c += a[i]; - r[i++] = c&this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = (c<0)?-1:0; - if(c > 0) r[i++] = c; - else if(c < -1) r[i++] = this.DV+c; - r.t = i; - r.clamp(); - } - - // (public) this + a - function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - - // (public) this - a - function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - - // (public) this * a - function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - - // (public) this^2 - function bnSquare() { var r = nbi(); this.squareTo(r); return r; } - - // (public) this / a - function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - - // (public) this % a - function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } - - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); - } - - // (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(); - } - - // (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]; - } - } - - // A "null" reducer - function NullExp() {} - function nNop(x) { return x; } - function nMulTo(x,y,r) { x.multiplyTo(y,r); } - function nSqrTo(x,r) { x.squareTo(r); } - - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - - // (public) this^e - function bnPow(e) { return this.exp(e,new NullExp()); } - - // (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(); - } - - // (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); - } - - // Barrett modular reduction - function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2*m.t,this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - - 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 = nbi(); x.copyTo(r); this.reduce(r); return r; } - } - - function barrettRevert(x) { return x; } - - // x = x mod m (HAC 14.42) - function barrettReduce(x) { - x.drShiftTo(this.m.t-1,this.r2); - if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } - this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); - this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); - while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); - x.subTo(this.r2,x); - while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); - } - - // r = x^2 mod m; x != r - function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - - // r = x*y mod m; x,y != r - function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - - // (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< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; - } - } - - var j = e.t-1, w, is1 = true, r2 = nbi(), 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); - } - - 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; - } - 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); - } - - while(j >= 0 && (e[j]&(1< 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); - } - else { - y.subTo(x,y); - y.rShiftTo(1,y); - } - } - 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; - } - - // (public) 1/this % m (HAC 14.61) - function bnModInverse(m) { - var ac = m.isEven(); - 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); - } - 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); - } - 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; - if(d.compareTo(m) >= 0) return d.subtract(m); - if(d.signum() < 0) d.addTo(m,d); else return d; - if(d.signum() < 0) return d.add(m); else 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]; - - // (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); - } - - // (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 = nbi(); - for(var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); - 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 - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - - // public - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; - - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett - - // BigInteger interfaces not implemented in jsbn: - - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - - // Random number generator - requires a PRNG backend, e.g. prng4.js - - // For best results, put code like - // - // in your main HTML document. - - var rng_state; - var rng_pool; - var rng_pptr; - - // Mix in a 32-bit integer into the pool - function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; - } - - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); - } - - // Initialize the pool with junk if needed. - if(rng_pool == null) { - rng_pool = new Array(); - rng_pptr = 0; - var t; - if(typeof window !== "undefined" && window.crypto) { - if (window.crypto.getRandomValues) { - // Use webcrypto if available - var ua = new Uint8Array(32); - window.crypto.getRandomValues(ua); - for(t = 0; t < 32; ++t) - rng_pool[rng_pptr++] = ua[t]; - } - else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { - // Extract entropy (256 bits) from NS4 RNG if available - var z = window.crypto.random(32); - for(t = 0; t < z.length; ++t) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; - } - } - while(rng_pptr < rng_psize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); - } - - function rng_get_byte() { - if(rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); - } - - function rng_get_bytes(ba) { - var i; - for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } - - function SecureRandom() {} - - SecureRandom.prototype.nextBytes = rng_get_bytes; - - // prng4.js - uses Arcfour as a PRNG - - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for(i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for(i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; - } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; - } - - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } - - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - var rng_psize = 256; - - BigInteger.SecureRandom = SecureRandom; - BigInteger.BigInteger = BigInteger; - if (typeof exports !== 'undefined') { - exports = module.exports = BigInteger; - } else { - this.BigInteger = BigInteger; - this.SecureRandom = SecureRandom; - } - -}).call(this); - -},{}],826:[function(require,module,exports){ -'use strict'; - -var traverse = module.exports = function (schema, opts, cb) { - // Legacy support for v0.3.1 and earlier. - if (typeof opts == 'function') { - cb = opts; - opts = {}; - } - - cb = opts.cb || cb; - var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - - _traverse(opts, pre, post, schema, '', schema); -}; - - -traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true -}; - -traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; - -traverse.propsKeywords = { - definitions: true, - properties: true, - patternProperties: true, - dependencies: true -}; - -traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; - - -function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == 'object' && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i=0; i schema.maxItems){ - addError("There must be a maximum of " + schema.maxItems + " in the array"); - } - }else if(schema.properties || schema.additionalProperties){ - errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); - } - if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ - addError("does not match the regex pattern " + schema.pattern); - } - if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ - addError("may only be " + schema.maxLength + " characters long"); - } - if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ - addError("must be at least " + schema.minLength + " characters long"); - } - if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum && - schema.minimum > value){ - addError("must have a minimum value of " + schema.minimum); - } - if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum && - schema.maximum < value){ - addError("must have a maximum value of " + schema.maximum); - } - if(schema['enum']){ - var enumer = schema['enum']; - l = enumer.length; - var found; - for(var j = 0; j < l; j++){ - if(enumer[j]===value){ - found=1; - break; - } - } - if(!found){ - addError("does not have a value in the enumeration " + enumer.join(", ")); - } - } - if(typeof schema.maxDecimal == 'number' && - (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ - addError("may only have " + schema.maxDecimal + " digits of decimal places"); - } - } - } - return null; - } - // validate an object against a schema - function checkObj(instance,objTypeDef,path,additionalProp){ - - if(typeof objTypeDef =='object'){ - if(typeof instance != 'object' || instance instanceof Array){ - errors.push({property:path,message:"an object is required"}); - } - - for(var i in objTypeDef){ - if(objTypeDef.hasOwnProperty(i)){ - var value = instance[i]; - // skip _not_ specified properties - if (value === undefined && options.existingOnly) continue; - var propDef = objTypeDef[i]; - // set default - if(value === undefined && propDef["default"]){ - value = instance[i] = propDef["default"]; - } - if(options.coerce && i in instance){ - value = instance[i] = options.coerce(value, propDef); - } - checkProp(value,propDef,path,i); - } - } - } - for(i in instance){ - if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ - if (options.filter) { - delete instance[i]; - continue; - } else { - errors.push({property:path,message:(typeof value) + "The property " + i + - " is not defined in the schema and the schema does not allow additional properties"}); - } - } - var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; - if(requires && !(requires in instance)){ - errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); - } - value = instance[i]; - if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ - if(options.coerce){ - value = instance[i] = options.coerce(value, additionalProp); - } - checkProp(value,additionalProp,path,i); - } - if(!_changing && value && value.$schema){ - errors = errors.concat(checkProp(value,value.$schema,path,i)); - } - } - return errors; - } - if(schema){ - checkProp(instance,schema,'',_changing || ''); - } - if(!_changing && instance && instance.$schema){ - checkProp(instance,instance.$schema,'',''); - } - return {valid:!errors.length,errors:errors}; -}; -exports.mustBeValid = function(result){ - // summary: - // This checks to ensure that the result is valid and will throw an appropriate error message if it is not - // result: the result returned from checkPropertyChange or validate - if(!result.valid){ - throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); - } -} - -return exports; -})); - -},{}],828:[function(require,module,exports){ +},{"_process":1258}],667:[function(require,module,exports){ exports = module.exports = stringify exports.getSerialize = serializer @@ -93250,744 +68613,7 @@ function serializer(replacer, cycleReplacer) { } } -},{}],829:[function(require,module,exports){ -/* - * lib/jsprim.js: utilities for primitive JavaScript types - */ - -var mod_assert = require('assert-plus'); -var mod_util = require('util'); - -var mod_extsprintf = require('extsprintf'); -var mod_verror = require('verror'); -var mod_jsonschema = require('json-schema'); - -/* - * Public interface - */ -exports.deepCopy = deepCopy; -exports.deepEqual = deepEqual; -exports.isEmpty = isEmpty; -exports.hasKey = hasKey; -exports.forEachKey = forEachKey; -exports.pluck = pluck; -exports.flattenObject = flattenObject; -exports.flattenIter = flattenIter; -exports.validateJsonObject = validateJsonObjectJS; -exports.validateJsonObjectJS = validateJsonObjectJS; -exports.randElt = randElt; -exports.extraProperties = extraProperties; -exports.mergeObjects = mergeObjects; - -exports.startsWith = startsWith; -exports.endsWith = endsWith; - -exports.parseInteger = parseInteger; - -exports.iso8601 = iso8601; -exports.rfc1123 = rfc1123; -exports.parseDateTime = parseDateTime; - -exports.hrtimediff = hrtimeDiff; -exports.hrtimeDiff = hrtimeDiff; -exports.hrtimeAccum = hrtimeAccum; -exports.hrtimeAdd = hrtimeAdd; -exports.hrtimeNanosec = hrtimeNanosec; -exports.hrtimeMicrosec = hrtimeMicrosec; -exports.hrtimeMillisec = hrtimeMillisec; - - -/* - * Deep copy an acyclic *basic* Javascript object. This only handles basic - * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects - * containing these. This does *not* handle instances of other classes. - */ -function deepCopy(obj) -{ - var ret, key; - var marker = '__deepCopy'; - - if (obj && obj[marker]) - throw (new Error('attempted deep copy of cyclic object')); - - if (obj && obj.constructor == Object) { - ret = {}; - obj[marker] = true; - - for (key in obj) { - if (key == marker) - continue; - - ret[key] = deepCopy(obj[key]); - } - - delete (obj[marker]); - return (ret); - } - - if (obj && obj.constructor == Array) { - ret = []; - obj[marker] = true; - - for (key = 0; key < obj.length; key++) - ret.push(deepCopy(obj[key])); - - delete (obj[marker]); - return (ret); - } - - /* - * It must be a primitive type -- just return it. - */ - return (obj); -} - -function deepEqual(obj1, obj2) -{ - if (typeof (obj1) != typeof (obj2)) - return (false); - - if (obj1 === null || obj2 === null || typeof (obj1) != 'object') - return (obj1 === obj2); - - if (obj1.constructor != obj2.constructor) - return (false); - - var k; - for (k in obj1) { - if (!obj2.hasOwnProperty(k)) - return (false); - - if (!deepEqual(obj1[k], obj2[k])) - return (false); - } - - for (k in obj2) { - if (!obj1.hasOwnProperty(k)) - return (false); - } - - return (true); -} - -function isEmpty(obj) -{ - var key; - for (key in obj) - return (false); - return (true); -} - -function hasKey(obj, key) -{ - mod_assert.equal(typeof (key), 'string'); - return (Object.prototype.hasOwnProperty.call(obj, key)); -} - -function forEachKey(obj, callback) -{ - for (var key in obj) { - if (hasKey(obj, key)) { - callback(key, obj[key]); - } - } -} - -function pluck(obj, key) -{ - mod_assert.equal(typeof (key), 'string'); - return (pluckv(obj, key)); -} - -function pluckv(obj, key) -{ - if (obj === null || typeof (obj) !== 'object') - return (undefined); - - if (obj.hasOwnProperty(key)) - return (obj[key]); - - var i = key.indexOf('.'); - if (i == -1) - return (undefined); - - var key1 = key.substr(0, i); - if (!obj.hasOwnProperty(key1)) - return (undefined); - - return (pluckv(obj[key1], key.substr(i + 1))); -} - -/* - * Invoke callback(row) for each entry in the array that would be returned by - * flattenObject(data, depth). This is just like flattenObject(data, - * depth).forEach(callback), except that the intermediate array is never - * created. - */ -function flattenIter(data, depth, callback) -{ - doFlattenIter(data, depth, [], callback); -} - -function doFlattenIter(data, depth, accum, callback) -{ - var each; - var key; - - if (depth === 0) { - each = accum.slice(0); - each.push(data); - callback(each); - return; - } - - mod_assert.ok(data !== null); - mod_assert.equal(typeof (data), 'object'); - mod_assert.equal(typeof (depth), 'number'); - mod_assert.ok(depth >= 0); - - for (key in data) { - each = accum.slice(0); - each.push(key); - doFlattenIter(data[key], depth - 1, each, callback); - } -} - -function flattenObject(data, depth) -{ - if (depth === 0) - return ([ data ]); - - mod_assert.ok(data !== null); - mod_assert.equal(typeof (data), 'object'); - mod_assert.equal(typeof (depth), 'number'); - mod_assert.ok(depth >= 0); - - var rv = []; - var key; - - for (key in data) { - flattenObject(data[key], depth - 1).forEach(function (p) { - rv.push([ key ].concat(p)); - }); - } - - return (rv); -} - -function startsWith(str, prefix) -{ - return (str.substr(0, prefix.length) == prefix); -} - -function endsWith(str, suffix) -{ - return (str.substr( - str.length - suffix.length, suffix.length) == suffix); -} - -function iso8601(d) -{ - if (typeof (d) == 'number') - d = new Date(d); - mod_assert.ok(d.constructor === Date); - return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', - d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), - d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), - d.getUTCMilliseconds())); -} - -var RFC1123_MONTHS = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; -var RFC1123_DAYS = [ - 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - -function rfc1123(date) { - return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', - RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), - RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), - date.getUTCHours(), date.getUTCMinutes(), - date.getUTCSeconds())); -} - -/* - * Parses a date expressed as a string, as either a number of milliseconds since - * the epoch or any string format that Date accepts, giving preference to the - * former where these two sets overlap (e.g., small numbers). - */ -function parseDateTime(str) -{ - /* - * This is irritatingly implicit, but significantly more concise than - * alternatives. The "+str" will convert a string containing only a - * number directly to a Number, or NaN for other strings. Thus, if the - * conversion succeeds, we use it (this is the milliseconds-since-epoch - * case). Otherwise, we pass the string directly to the Date - * constructor to parse. - */ - var numeric = +str; - if (!isNaN(numeric)) { - return (new Date(numeric)); - } else { - return (new Date(str)); - } -} - - -/* - * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode - * the ES6 definitions here, while allowing for them to someday be higher. - */ -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; -var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; - - -/* - * Default options for parseInteger(). - */ -var PI_DEFAULTS = { - base: 10, - allowSign: true, - allowPrefix: false, - allowTrailing: false, - allowImprecise: false, - trimWhitespace: false, - leadingZeroIsOctal: false -}; - -var CP_0 = 0x30; -var CP_9 = 0x39; - -var CP_A = 0x41; -var CP_B = 0x42; -var CP_O = 0x4f; -var CP_T = 0x54; -var CP_X = 0x58; -var CP_Z = 0x5a; - -var CP_a = 0x61; -var CP_b = 0x62; -var CP_o = 0x6f; -var CP_t = 0x74; -var CP_x = 0x78; -var CP_z = 0x7a; - -var PI_CONV_DEC = 0x30; -var PI_CONV_UC = 0x37; -var PI_CONV_LC = 0x57; - - -/* - * A stricter version of parseInt() that provides options for changing what - * is an acceptable string (for example, disallowing trailing characters). - */ -function parseInteger(str, uopts) -{ - mod_assert.string(str, 'str'); - mod_assert.optionalObject(uopts, 'options'); - - var baseOverride = false; - var options = PI_DEFAULTS; - - if (uopts) { - baseOverride = hasKey(uopts, 'base'); - options = mergeObjects(options, uopts); - mod_assert.number(options.base, 'options.base'); - mod_assert.ok(options.base >= 2, 'options.base >= 2'); - mod_assert.ok(options.base <= 36, 'options.base <= 36'); - mod_assert.bool(options.allowSign, 'options.allowSign'); - mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); - mod_assert.bool(options.allowTrailing, - 'options.allowTrailing'); - mod_assert.bool(options.allowImprecise, - 'options.allowImprecise'); - mod_assert.bool(options.trimWhitespace, - 'options.trimWhitespace'); - mod_assert.bool(options.leadingZeroIsOctal, - 'options.leadingZeroIsOctal'); - - if (options.leadingZeroIsOctal) { - mod_assert.ok(!baseOverride, - '"base" and "leadingZeroIsOctal" are ' + - 'mutually exclusive'); - } - } - - var c; - var pbase = -1; - var base = options.base; - var start; - var mult = 1; - var value = 0; - var idx = 0; - var len = str.length; - - /* Trim any whitespace on the left side. */ - if (options.trimWhitespace) { - while (idx < len && isSpace(str.charCodeAt(idx))) { - ++idx; - } - } - - /* Check the number for a leading sign. */ - if (options.allowSign) { - if (str[idx] === '-') { - idx += 1; - mult = -1; - } else if (str[idx] === '+') { - idx += 1; - } - } - - /* Parse the base-indicating prefix if there is one. */ - if (str[idx] === '0') { - if (options.allowPrefix) { - pbase = prefixToBase(str.charCodeAt(idx + 1)); - if (pbase !== -1 && (!baseOverride || pbase === base)) { - base = pbase; - idx += 2; - } - } - - if (pbase === -1 && options.leadingZeroIsOctal) { - base = 8; - } - } - - /* Parse the actual digits. */ - for (start = idx; idx < len; ++idx) { - c = translateDigit(str.charCodeAt(idx)); - if (c !== -1 && c < base) { - value *= base; - value += c; - } else { - break; - } - } - - /* If we didn't parse any digits, we have an invalid number. */ - if (start === idx) { - return (new Error('invalid number: ' + JSON.stringify(str))); - } - - /* Trim any whitespace on the right side. */ - if (options.trimWhitespace) { - while (idx < len && isSpace(str.charCodeAt(idx))) { - ++idx; - } - } - - /* Check for trailing characters. */ - if (idx < len && !options.allowTrailing) { - return (new Error('trailing characters after number: ' + - JSON.stringify(str.slice(idx)))); - } - - /* If our value is 0, we return now, to avoid returning -0. */ - if (value === 0) { - return (0); - } - - /* Calculate our final value. */ - var result = value * mult; - - /* - * If the string represents a value that cannot be precisely represented - * by JavaScript, then we want to check that: - * - * - We never increased the value past MAX_SAFE_INTEGER - * - We don't make the result negative and below MIN_SAFE_INTEGER - * - * Because we only ever increment the value during parsing, there's no - * chance of moving past MAX_SAFE_INTEGER and then dropping below it - * again, losing precision in the process. This means that we only need - * to do our checks here, at the end. - */ - if (!options.allowImprecise && - (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { - return (new Error('number is outside of the supported range: ' + - JSON.stringify(str.slice(start, idx)))); - } - - return (result); -} - - -/* - * Interpret a character code as a base-36 digit. - */ -function translateDigit(d) -{ - if (d >= CP_0 && d <= CP_9) { - /* '0' to '9' -> 0 to 9 */ - return (d - PI_CONV_DEC); - } else if (d >= CP_A && d <= CP_Z) { - /* 'A' - 'Z' -> 10 to 35 */ - return (d - PI_CONV_UC); - } else if (d >= CP_a && d <= CP_z) { - /* 'a' - 'z' -> 10 to 35 */ - return (d - PI_CONV_LC); - } else { - /* Invalid character code */ - return (-1); - } -} - - -/* - * Test if a value matches the ECMAScript definition of trimmable whitespace. - */ -function isSpace(c) -{ - return (c === 0x20) || - (c >= 0x0009 && c <= 0x000d) || - (c === 0x00a0) || - (c === 0x1680) || - (c === 0x180e) || - (c >= 0x2000 && c <= 0x200a) || - (c === 0x2028) || - (c === 0x2029) || - (c === 0x202f) || - (c === 0x205f) || - (c === 0x3000) || - (c === 0xfeff); -} - - -/* - * Determine which base a character indicates (e.g., 'x' indicates hex). - */ -function prefixToBase(c) -{ - if (c === CP_b || c === CP_B) { - /* 0b/0B (binary) */ - return (2); - } else if (c === CP_o || c === CP_O) { - /* 0o/0O (octal) */ - return (8); - } else if (c === CP_t || c === CP_T) { - /* 0t/0T (decimal) */ - return (10); - } else if (c === CP_x || c === CP_X) { - /* 0x/0X (hexadecimal) */ - return (16); - } else { - /* Not a meaningful character */ - return (-1); - } -} - - -function validateJsonObjectJS(schema, input) -{ - var report = mod_jsonschema.validate(input, schema); - - if (report.errors.length === 0) - return (null); - - /* Currently, we only do anything useful with the first error. */ - var error = report.errors[0]; - - /* The failed property is given by a URI with an irrelevant prefix. */ - var propname = error['property']; - var reason = error['message'].toLowerCase(); - var i, j; - - /* - * There's at least one case where the property error message is - * confusing at best. We work around this here. - */ - if ((i = reason.indexOf('the property ')) != -1 && - (j = reason.indexOf(' is not defined in the schema and the ' + - 'schema does not allow additional properties')) != -1) { - i += 'the property '.length; - if (propname === '') - propname = reason.substr(i, j - i); - else - propname = propname + '.' + reason.substr(i, j - i); - - reason = 'unsupported property'; - } - - var rv = new mod_verror.VError('property "%s": %s', propname, reason); - rv.jsv_details = error; - return (rv); -} - -function randElt(arr) -{ - mod_assert.ok(Array.isArray(arr) && arr.length > 0, - 'randElt argument must be a non-empty array'); - - return (arr[Math.floor(Math.random() * arr.length)]); -} - -function assertHrtime(a) -{ - mod_assert.ok(a[0] >= 0 && a[1] >= 0, - 'negative numbers not allowed in hrtimes'); - mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); -} - -/* - * Compute the time elapsed between hrtime readings A and B, where A is later - * than B. hrtime readings come from Node's process.hrtime(). There is no - * defined way to represent negative deltas, so it's illegal to diff B from A - * where the time denoted by B is later than the time denoted by A. If this - * becomes valuable, we can define a representation and extend the - * implementation to support it. - */ -function hrtimeDiff(a, b) -{ - assertHrtime(a); - assertHrtime(b); - mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), - 'negative differences not allowed'); - - var rv = [ a[0] - b[0], 0 ]; - - if (a[1] >= b[1]) { - rv[1] = a[1] - b[1]; - } else { - rv[0]--; - rv[1] = 1e9 - (b[1] - a[1]); - } - - return (rv); -} - -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of nanoseconds. - */ -function hrtimeNanosec(a) -{ - assertHrtime(a); - - return (Math.floor(a[0] * 1e9 + a[1])); -} - -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of microseconds. - */ -function hrtimeMicrosec(a) -{ - assertHrtime(a); - - return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); -} - -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of milliseconds. - */ -function hrtimeMillisec(a) -{ - assertHrtime(a); - - return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); -} - -/* - * Add two hrtime readings A and B, overwriting A with the result of the - * addition. This function is useful for accumulating several hrtime intervals - * into a counter. Returns A. - */ -function hrtimeAccum(a, b) -{ - assertHrtime(a); - assertHrtime(b); - - /* - * Accumulate the nanosecond component. - */ - a[1] += b[1]; - if (a[1] >= 1e9) { - /* - * The nanosecond component overflowed, so carry to the seconds - * field. - */ - a[0]++; - a[1] -= 1e9; - } - - /* - * Accumulate the seconds component. - */ - a[0] += b[0]; - - return (a); -} - -/* - * Add two hrtime readings A and B, returning the result as a new hrtime array. - * Does not modify either input argument. - */ -function hrtimeAdd(a, b) -{ - assertHrtime(a); - - var rv = [ a[0], a[1] ]; - - return (hrtimeAccum(rv, b)); -} - - -/* - * Check an object for unexpected properties. Accepts the object to check, and - * an array of allowed property names (strings). Returns an array of key names - * that were found on the object, but did not appear in the list of allowed - * properties. If no properties were found, the returned array will be of - * zero length. - */ -function extraProperties(obj, allowed) -{ - mod_assert.ok(typeof (obj) === 'object' && obj !== null, - 'obj argument must be a non-null object'); - mod_assert.ok(Array.isArray(allowed), - 'allowed argument must be an array of strings'); - for (var i = 0; i < allowed.length; i++) { - mod_assert.ok(typeof (allowed[i]) === 'string', - 'allowed argument must be an array of strings'); - } - - return (Object.keys(obj).filter(function (key) { - return (allowed.indexOf(key) === -1); - })); -} - -/* - * Given three sets of properties "provided" (may be undefined), "overrides" - * (required), and "defaults" (may be undefined), construct an object containing - * the union of these sets with "overrides" overriding "provided", and - * "provided" overriding "defaults". None of the input objects are modified. - */ -function mergeObjects(provided, overrides, defaults) -{ - var rv, k; - - rv = {}; - if (defaults) { - for (k in defaults) - rv[k] = defaults[k]; - } - - if (provided) { - for (k in provided) - rv[k] = provided[k]; - } - - if (overrides) { - for (k in overrides) - rv[k] = overrides[k]; - } - - return (rv); -} - -},{"assert-plus":77,"extsprintf":374,"json-schema":827,"util":1776,"verror":1787}],830:[function(require,module,exports){ +},{}],668:[function(require,module,exports){ module.exports = debounce; function debounce(fn, wait, callFirst) { @@ -94013,7 +68639,7 @@ function debounce(fn, wait, callFirst) { }; } -},{}],831:[function(require,module,exports){ +},{}],669:[function(require,module,exports){ module.exports = set; /* @@ -94064,7 +68690,7 @@ function set(obj, props, value) { return true; } -},{}],832:[function(require,module,exports){ +},{}],670:[function(require,module,exports){ /* index.js - Kademlia DHT K-bucket implementation as a binary tree. @@ -94502,560 +69128,7 @@ class KBucket extends EventEmitter { module.exports = KBucket -},{"events":370,"randombytes":1552}],833:[function(require,module,exports){ -'use strict' -module.exports = require('./lib/api')(require('./lib/keccak')) - -},{"./lib/api":834,"./lib/keccak":838}],834:[function(require,module,exports){ -'use strict' -var createKeccak = require('./keccak') -var createShake = require('./shake') - -module.exports = function (KeccakState) { - var Keccak = createKeccak(KeccakState) - var Shake = createShake(KeccakState) - - return function (algorithm, options) { - var hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm - switch (hash) { - case 'keccak224': return new Keccak(1152, 448, null, 224, options) - case 'keccak256': return new Keccak(1088, 512, null, 256, options) - case 'keccak384': return new Keccak(832, 768, null, 384, options) - case 'keccak512': return new Keccak(576, 1024, null, 512, options) - - case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options) - case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options) - case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options) - case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options) - - case 'shake128': return new Shake(1344, 256, 0x1f, options) - case 'shake256': return new Shake(1088, 512, 0x1f, options) - - default: throw new Error('Invald algorithm: ' + algorithm) - } - } -} - -},{"./keccak":835,"./shake":836}],835:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var inherits = require('inherits') - -module.exports = function (KeccakState) { - function Keccak (rate, capacity, delimitedSuffix, hashBitLength, options) { - Transform.call(this, options) - - this._rate = rate - this._capacity = capacity - this._delimitedSuffix = delimitedSuffix - this._hashBitLength = hashBitLength - this._options = options - - this._state = new KeccakState() - this._state.initialize(rate, capacity) - this._finalized = false - } - - inherits(Keccak, Transform) - - Keccak.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) - } - - Keccak.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err - } - - callback(error) - } - - Keccak.prototype.update = function (data, encoding) { - if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - this._state.absorb(data) - - return this - } - - Keccak.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - - if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix) - var digest = this._state.squeeze(this._hashBitLength / 8) - if (encoding !== undefined) digest = digest.toString(encoding) - - this._resetState() - - return digest - } - - // remove result from memory - Keccak.prototype._resetState = function () { - this._state.initialize(this._rate, this._capacity) - return this - } - - // because sometimes we need hash right now and little later - Keccak.prototype._clone = function () { - var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options) - this._state.copy(clone._state) - clone._finalized = this._finalized - - return clone - } - - return Keccak -} - -},{"inherits":453,"safe-buffer":1593,"stream":1715}],836:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var inherits = require('inherits') - -module.exports = function (KeccakState) { - function Shake (rate, capacity, delimitedSuffix, options) { - Transform.call(this, options) - - this._rate = rate - this._capacity = capacity - this._delimitedSuffix = delimitedSuffix - this._options = options - - this._state = new KeccakState() - this._state.initialize(rate, capacity) - this._finalized = false - } - - inherits(Shake, Transform) - - Shake.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) - } - - Shake.prototype._flush = function () {} - - Shake.prototype._read = function (size) { - this.push(this.squeeze(size)) - } - - Shake.prototype.update = function (data, encoding) { - if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') - if (this._finalized) throw new Error('Squeeze already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - this._state.absorb(data) - - return this - } - - Shake.prototype.squeeze = function (dataByteLength, encoding) { - if (!this._finalized) { - this._finalized = true - this._state.absorbLastFewBits(this._delimitedSuffix) - } - - var data = this._state.squeeze(dataByteLength) - if (encoding !== undefined) data = data.toString(encoding) - - return data - } - - Shake.prototype._resetState = function () { - this._state.initialize(this._rate, this._capacity) - return this - } - - Shake.prototype._clone = function () { - var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options) - this._state.copy(clone._state) - clone._finalized = this._finalized - - return clone - } - - return Shake -} - -},{"inherits":453,"safe-buffer":1593,"stream":1715}],837:[function(require,module,exports){ -'use strict' -var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648] - -exports.p1600 = function (s) { - for (var round = 0; round < 24; ++round) { - // theta - var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40] - var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41] - var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42] - var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43] - var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44] - var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45] - var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46] - var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47] - var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48] - var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49] - - var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31) - var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31) - var t1slo0 = s[0] ^ lo - var t1shi0 = s[1] ^ hi - var t1slo5 = s[10] ^ lo - var t1shi5 = s[11] ^ hi - var t1slo10 = s[20] ^ lo - var t1shi10 = s[21] ^ hi - var t1slo15 = s[30] ^ lo - var t1shi15 = s[31] ^ hi - var t1slo20 = s[40] ^ lo - var t1shi20 = s[41] ^ hi - lo = lo0 ^ (lo2 << 1 | hi2 >>> 31) - hi = hi0 ^ (hi2 << 1 | lo2 >>> 31) - var t1slo1 = s[2] ^ lo - var t1shi1 = s[3] ^ hi - var t1slo6 = s[12] ^ lo - var t1shi6 = s[13] ^ hi - var t1slo11 = s[22] ^ lo - var t1shi11 = s[23] ^ hi - var t1slo16 = s[32] ^ lo - var t1shi16 = s[33] ^ hi - var t1slo21 = s[42] ^ lo - var t1shi21 = s[43] ^ hi - lo = lo1 ^ (lo3 << 1 | hi3 >>> 31) - hi = hi1 ^ (hi3 << 1 | lo3 >>> 31) - var t1slo2 = s[4] ^ lo - var t1shi2 = s[5] ^ hi - var t1slo7 = s[14] ^ lo - var t1shi7 = s[15] ^ hi - var t1slo12 = s[24] ^ lo - var t1shi12 = s[25] ^ hi - var t1slo17 = s[34] ^ lo - var t1shi17 = s[35] ^ hi - var t1slo22 = s[44] ^ lo - var t1shi22 = s[45] ^ hi - lo = lo2 ^ (lo4 << 1 | hi4 >>> 31) - hi = hi2 ^ (hi4 << 1 | lo4 >>> 31) - var t1slo3 = s[6] ^ lo - var t1shi3 = s[7] ^ hi - var t1slo8 = s[16] ^ lo - var t1shi8 = s[17] ^ hi - var t1slo13 = s[26] ^ lo - var t1shi13 = s[27] ^ hi - var t1slo18 = s[36] ^ lo - var t1shi18 = s[37] ^ hi - var t1slo23 = s[46] ^ lo - var t1shi23 = s[47] ^ hi - lo = lo3 ^ (lo0 << 1 | hi0 >>> 31) - hi = hi3 ^ (hi0 << 1 | lo0 >>> 31) - var t1slo4 = s[8] ^ lo - var t1shi4 = s[9] ^ hi - var t1slo9 = s[18] ^ lo - var t1shi9 = s[19] ^ hi - var t1slo14 = s[28] ^ lo - var t1shi14 = s[29] ^ hi - var t1slo19 = s[38] ^ lo - var t1shi19 = s[39] ^ hi - var t1slo24 = s[48] ^ lo - var t1shi24 = s[49] ^ hi - - // rho & pi - var t2slo0 = t1slo0 - var t2shi0 = t1shi0 - var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28) - var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28) - var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29) - var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29) - var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23) - var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23) - var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14) - var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14) - var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31) - var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31) - var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20) - var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20) - var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22) - var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22) - var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19) - var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19) - var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30) - var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30) - var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2) - var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2) - var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26) - var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26) - var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21) - var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21) - var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17) - var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17) - var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3) - var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3) - var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4) - var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4) - var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9) - var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9) - var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7) - var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7) - var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11) - var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11) - var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8) - var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8) - var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5) - var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5) - var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12) - var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12) - var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25) - var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25) - var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24) - var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24) - var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18) - var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18) - - // chi - s[0] = t2slo0 ^ (~t2slo1 & t2slo2) - s[1] = t2shi0 ^ (~t2shi1 & t2shi2) - s[10] = t2slo5 ^ (~t2slo6 & t2slo7) - s[11] = t2shi5 ^ (~t2shi6 & t2shi7) - s[20] = t2slo10 ^ (~t2slo11 & t2slo12) - s[21] = t2shi10 ^ (~t2shi11 & t2shi12) - s[30] = t2slo15 ^ (~t2slo16 & t2slo17) - s[31] = t2shi15 ^ (~t2shi16 & t2shi17) - s[40] = t2slo20 ^ (~t2slo21 & t2slo22) - s[41] = t2shi20 ^ (~t2shi21 & t2shi22) - s[2] = t2slo1 ^ (~t2slo2 & t2slo3) - s[3] = t2shi1 ^ (~t2shi2 & t2shi3) - s[12] = t2slo6 ^ (~t2slo7 & t2slo8) - s[13] = t2shi6 ^ (~t2shi7 & t2shi8) - s[22] = t2slo11 ^ (~t2slo12 & t2slo13) - s[23] = t2shi11 ^ (~t2shi12 & t2shi13) - s[32] = t2slo16 ^ (~t2slo17 & t2slo18) - s[33] = t2shi16 ^ (~t2shi17 & t2shi18) - s[42] = t2slo21 ^ (~t2slo22 & t2slo23) - s[43] = t2shi21 ^ (~t2shi22 & t2shi23) - s[4] = t2slo2 ^ (~t2slo3 & t2slo4) - s[5] = t2shi2 ^ (~t2shi3 & t2shi4) - s[14] = t2slo7 ^ (~t2slo8 & t2slo9) - s[15] = t2shi7 ^ (~t2shi8 & t2shi9) - s[24] = t2slo12 ^ (~t2slo13 & t2slo14) - s[25] = t2shi12 ^ (~t2shi13 & t2shi14) - s[34] = t2slo17 ^ (~t2slo18 & t2slo19) - s[35] = t2shi17 ^ (~t2shi18 & t2shi19) - s[44] = t2slo22 ^ (~t2slo23 & t2slo24) - s[45] = t2shi22 ^ (~t2shi23 & t2shi24) - s[6] = t2slo3 ^ (~t2slo4 & t2slo0) - s[7] = t2shi3 ^ (~t2shi4 & t2shi0) - s[16] = t2slo8 ^ (~t2slo9 & t2slo5) - s[17] = t2shi8 ^ (~t2shi9 & t2shi5) - s[26] = t2slo13 ^ (~t2slo14 & t2slo10) - s[27] = t2shi13 ^ (~t2shi14 & t2shi10) - s[36] = t2slo18 ^ (~t2slo19 & t2slo15) - s[37] = t2shi18 ^ (~t2shi19 & t2shi15) - s[46] = t2slo23 ^ (~t2slo24 & t2slo20) - s[47] = t2shi23 ^ (~t2shi24 & t2shi20) - s[8] = t2slo4 ^ (~t2slo0 & t2slo1) - s[9] = t2shi4 ^ (~t2shi0 & t2shi1) - s[18] = t2slo9 ^ (~t2slo5 & t2slo6) - s[19] = t2shi9 ^ (~t2shi5 & t2shi6) - s[28] = t2slo14 ^ (~t2slo10 & t2slo11) - s[29] = t2shi14 ^ (~t2shi10 & t2shi11) - s[38] = t2slo19 ^ (~t2slo15 & t2slo16) - s[39] = t2shi19 ^ (~t2shi15 & t2shi16) - s[48] = t2slo24 ^ (~t2slo20 & t2slo21) - s[49] = t2shi24 ^ (~t2shi20 & t2shi21) - - // iota - s[0] ^= P1600_ROUND_CONSTANTS[round * 2] - s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1] - } -} - -},{}],838:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var keccakState = require('./keccak-state-unroll') - -function Keccak () { - // much faster than `new Array(50)` - this.state = [ - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 - ] - - this.blockSize = null - this.count = 0 - this.squeezing = false -} - -Keccak.prototype.initialize = function (rate, capacity) { - for (var i = 0; i < 50; ++i) this.state[i] = 0 - this.blockSize = rate / 8 - this.count = 0 - this.squeezing = false -} - -Keccak.prototype.absorb = function (data) { - for (var i = 0; i < data.length; ++i) { - this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4)) - this.count += 1 - if (this.count === this.blockSize) { - keccakState.p1600(this.state) - this.count = 0 - } - } -} - -Keccak.prototype.absorbLastFewBits = function (bits) { - this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4)) - if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state) - this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4)) - keccakState.p1600(this.state) - this.count = 0 - this.squeezing = true -} - -Keccak.prototype.squeeze = function (length) { - if (!this.squeezing) this.absorbLastFewBits(0x01) - - var output = Buffer.alloc(length) - for (var i = 0; i < length; ++i) { - output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff - this.count += 1 - if (this.count === this.blockSize) { - keccakState.p1600(this.state) - this.count = 0 - } - } - - return output -} - -Keccak.prototype.copy = function (dest) { - for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i] - dest.blockSize = this.blockSize - dest.count = this.count - dest.squeezing = this.squeezing -} - -module.exports = Keccak - -},{"./keccak-state-unroll":837,"safe-buffer":1593}],839:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var createKeccakHash = require('keccak'); -var BN = require('bn.js'); - -module.exports = function (a) { - a = toBuffer(a); - - return createKeccakHash('keccak256').update(a).digest(); -}; - -function toBuffer(v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = Buffer.from(v); - } else if (typeof v === 'string') { - if (isHexString(v)) { - v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex'); - } else { - v = Buffer.from(v); - } - } else if (typeof v === 'number') { - v = intToBuffer(v); - } else if (v === null || v === undefined) { - v = Buffer.allocUnsafe(0); - } else if (BN.isBN(v)) { - v = v.toArrayLike(Buffer); - } else if (v.toArray) { - // converts a BN to a Buffer - v = Buffer.from(v.toArray()); - } else { - throw new Error('invalid type'); - } - } - return v; -} - -function isHexString(value, length) { - if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - - if (length && value.length !== 2 + 2 * length) { - return false; - } - - return true; -} - -function padToEven(value) { - var a = value; // eslint-disable-line - - if (typeof a !== 'string') { - throw new Error('while padding to even, value must be string, is currently ' + (typeof a === 'undefined' ? 'undefined' : _typeof(a)) + ', while padToEven.'); - } - - if (a.length % 2) { - a = '0' + a; - } - - return a; -} - -function stripHexPrefix(str) { - if (typeof str !== 'string') { - return str; - } - - return isHexPrefixed(str) ? str.slice(2) : str; -} - -function isHexPrefixed(str) { - if (typeof str !== 'string') { - throw new Error("value must be type 'string', is currently type " + (typeof str === 'undefined' ? 'undefined' : _typeof(str)) + ', while checking isHexPrefixed.'); - } - - return str.slice(0, 2) === '0x'; -} - -function intToBuffer(i) { - var hex = intToHex(i); - - return Buffer.from(padToEven(hex.slice(2)), 'hex'); -} - -function intToHex(i) { - var hex = i.toString(16); // eslint-disable-line - - return '0x' + hex; -} -}).call(this,require("buffer").Buffer) -},{"bn.js":171,"buffer":217,"keccak":833}],840:[function(require,module,exports){ +},{"events":272,"randombytes":1366}],671:[function(require,module,exports){ (function (process){ 'use strict'; @@ -95369,7 +69442,7 @@ exports.default = LatencyMonitor; }).call(this,require('_process')) -},{"./VisibilityChangeEmitter":841,"_process":1438,"debug":253,"events":370,"lodash/get":1277,"lodash/isFunction":1283}],841:[function(require,module,exports){ +},{"./VisibilityChangeEmitter":672,"_process":1258,"debug":674,"events":272,"lodash/get":1106,"lodash/isFunction":1112}],672:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -95527,7 +69600,7 @@ var VisibilityChangeEmitter = function (_EventEmitter) { exports.default = VisibilityChangeEmitter; -},{"debug":253,"events":370}],842:[function(require,module,exports){ +},{"debug":674,"events":272}],673:[function(require,module,exports){ /* eslint-disable strict */ 'use strict'; @@ -95539,7 +69612,554 @@ Object.defineProperty(exports, '__esModule', { exports.default = require('./dist/LatencyMonitor').default; -},{"./dist/LatencyMonitor":840}],843:[function(require,module,exports){ +},{"./dist/LatencyMonitor":671}],674:[function(require,module,exports){ +(function (process){ +/** + * 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. + */ + +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 + */ + +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 + 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. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * 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); + + 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 + 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; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * 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); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +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 + */ + +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; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +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) {} +} + +}).call(this,require('_process')) +},{"./debug":675,"_process":1258}],675:[function(require,module,exports){ + +/** + * 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. + */ + +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". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + 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]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + 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; + + // 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]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // 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); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // 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); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + 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 + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +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; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":676}],676:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}],677:[function(require,module,exports){ var encodings = require('./lib/encodings') module.exports = Codec @@ -95648,7 +70268,7 @@ Codec.prototype.valueAsBuffer = function (opts) { return this._valueEncoding(opts).buffer } -},{"./lib/encodings":844}],844:[function(require,module,exports){ +},{"./lib/encodings":678}],678:[function(require,module,exports){ (function (Buffer){ exports.utf8 = exports['utf-8'] = { encode: function (data) { @@ -95716,7 +70336,7 @@ function isBinary (data) { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],845:[function(require,module,exports){ +},{"buffer":181}],679:[function(require,module,exports){ var createError = require('errno').create var LevelUPError = createError('LevelUPError') var NotFoundError = createError('NotFoundError', LevelUPError) @@ -95734,7 +70354,7 @@ module.exports = { EncodingError: createError('EncodingError', LevelUPError) } -},{"errno":317}],846:[function(require,module,exports){ +},{"errno":270}],680:[function(require,module,exports){ var inherits = require('inherits') var Readable = require('readable-stream').Readable var extend = require('xtend') @@ -95780,37 +70400,72 @@ ReadStream.prototype._destroy = function (err, callback) { }) } -},{"inherits":453,"readable-stream":861,"xtend":1860}],847:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],848:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],849:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":851,"./_stream_writable":853,"_process":1438,"dup":90,"inherits":453}],850:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":852,"dup":91,"inherits":453}],851:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":847,"../experimentalWarning":848,"./_stream_duplex":849,"./internal/streams/async_iterator":854,"./internal/streams/buffer_list":855,"./internal/streams/destroy":856,"./internal/streams/state":859,"./internal/streams/stream":860,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],852:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":847,"./_stream_duplex":849,"dup":93,"inherits":453}],853:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":847,"./_stream_duplex":849,"./internal/streams/destroy":856,"./internal/streams/state":859,"./internal/streams/stream":860,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],854:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":857,"_process":1438,"dup":95}],855:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],856:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],857:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":847,"dup":98}],858:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":847,"./end-of-stream":857,"dup":99}],859:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":847,"dup":100}],860:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],861:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":849,"./lib/_stream_passthrough.js":850,"./lib/_stream_readable.js":851,"./lib/_stream_transform.js":852,"./lib/_stream_writable.js":853,"./lib/internal/streams/end-of-stream.js":857,"./lib/internal/streams/pipeline.js":858,"dup":102}],862:[function(require,module,exports){ +},{"inherits":681,"readable-stream":696,"xtend":699}],681:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + +},{}],682:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],683:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],684:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":686,"./_stream_writable":688,"_process":1258,"dup":38,"inherits":681}],685:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":687,"dup":39,"inherits":681}],686:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":682,"../experimentalWarning":683,"./_stream_duplex":684,"./internal/streams/async_iterator":689,"./internal/streams/buffer_list":690,"./internal/streams/destroy":691,"./internal/streams/state":694,"./internal/streams/stream":695,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":681,"string_decoder/":698,"util":146}],687:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":682,"./_stream_duplex":684,"dup":41,"inherits":681}],688:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":682,"./_stream_duplex":684,"./internal/streams/destroy":691,"./internal/streams/state":694,"./internal/streams/stream":695,"_process":1258,"buffer":181,"dup":42,"inherits":681,"util-deprecate":1510}],689:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":692,"_process":1258,"dup":43}],690:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],691:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],692:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":682,"dup":46}],693:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":682,"./end-of-stream":692,"dup":47}],694:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":682,"dup":48}],695:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],696:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":684,"./lib/_stream_passthrough.js":685,"./lib/_stream_readable.js":686,"./lib/_stream_transform.js":687,"./lib/_stream_writable.js":688,"./lib/internal/streams/end-of-stream.js":692,"./lib/internal/streams/pipeline.js":693,"dup":50}],697:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],698:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":697}],699:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],700:[function(require,module,exports){ (function (process,Buffer){ module.exports = Level @@ -96112,7 +70767,7 @@ Level.destroy = function(db, callback) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"./iterator":863,"_process":1438,"abstract-leveldown":867,"buffer":217,"util":1776,"xtend":1860}],863:[function(require,module,exports){ +},{"./iterator":701,"_process":1258,"abstract-leveldown":705,"buffer":181,"util":1512,"xtend":707}],701:[function(require,module,exports){ (function (process,Buffer){ var util = require('util') var AbstractIterator = require('abstract-leveldown').AbstractIterator @@ -96299,7 +70954,7 @@ Iterator.prototype._next = function(callback) { } }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":1438,"abstract-leveldown":867,"buffer":217,"idb-readable-stream":448,"ltgt":1295,"stream":1715,"util":1776,"xtend":1860}],864:[function(require,module,exports){ +},{"_process":1258,"abstract-leveldown":705,"buffer":181,"idb-readable-stream":313,"ltgt":1124,"stream":1459,"util":1512,"xtend":707}],702:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -96382,7 +71037,7 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":1438}],865:[function(require,module,exports){ +},{"_process":1258}],703:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -96435,7 +71090,7 @@ AbstractIterator.prototype.end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":1438}],866:[function(require,module,exports){ +},{"_process":1258}],704:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -96711,13 +71366,13 @@ AbstractLevelDOWN.prototype._checkKey = function (obj, type) { module.exports = AbstractLevelDOWN }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":766,"./abstract-chained-batch":864,"./abstract-iterator":865,"_process":1438,"xtend":1860}],867:[function(require,module,exports){ +},{"../../../is-buffer/index.js":608,"./abstract-chained-batch":702,"./abstract-iterator":703,"_process":1258,"xtend":707}],705:[function(require,module,exports){ exports.AbstractLevelDOWN = require('./abstract-leveldown') exports.AbstractIterator = require('./abstract-iterator') exports.AbstractChainedBatch = require('./abstract-chained-batch') exports.isLevelDOWN = require('./is-leveldown') -},{"./abstract-chained-batch":864,"./abstract-iterator":865,"./abstract-leveldown":866,"./is-leveldown":868}],868:[function(require,module,exports){ +},{"./abstract-chained-batch":702,"./abstract-iterator":703,"./abstract-leveldown":704,"./is-leveldown":706}],706:[function(require,module,exports){ var AbstractLevelDOWN = require('./abstract-leveldown') function isLevelDOWN (db) { @@ -96733,7 +71388,9 @@ function isLevelDOWN (db) { module.exports = isLevelDOWN -},{"./abstract-leveldown":866}],869:[function(require,module,exports){ +},{"./abstract-leveldown":704}],707:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],708:[function(require,module,exports){ 'use strict' // For (old) browser support @@ -96766,22 +71423,32 @@ module.exports = function supports () { encodings: manifest.encodings || false, // Methods that are not part of abstract-leveldown or levelup - additionalMethods: manifest.additionalMethods || { - // May look something like: - // approximateSize: { - // sync: false, - // callback: true, - // promise: false - // }, - // createWriteStream: { - // sync: true, - // writable: true - // } - } + additionalMethods: xtend(manifest.additionalMethods) }) } -},{"xtend":1860,"xtend/mutable":1861}],870:[function(require,module,exports){ +},{"xtend":709,"xtend/mutable":710}],709:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],710:[function(require,module,exports){ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + +},{}],711:[function(require,module,exports){ var WriteError = require('level-errors').WriteError var promisify = require('./promisify') var getCallback = require('./common').getCallback @@ -96862,7 +71529,7 @@ Batch.prototype.write = function (options, callback) { module.exports = Batch -},{"./common":871,"./promisify":873,"level-errors":845}],871:[function(require,module,exports){ +},{"./common":712,"./promisify":714,"level-errors":679}],712:[function(require,module,exports){ exports.getCallback = function (options, callback) { return typeof options === 'function' ? options : callback } @@ -96871,7 +71538,7 @@ exports.getOptions = function (options) { return typeof options === 'object' && options !== null ? options : {} } -},{}],872:[function(require,module,exports){ +},{}],713:[function(require,module,exports){ (function (process){ var EventEmitter = require('events').EventEmitter var inherits = require('util').inherits @@ -96906,6 +71573,7 @@ function LevelUP (db, options, callback) { } var error + var self = this EventEmitter.call(this) this.setMaxListeners(Infinity) @@ -96930,7 +71598,9 @@ function LevelUP (db, options, callback) { this.options = getOptions(options) this._db = db this.db = new DeferredLevelDOWN(db) - this.open(callback) + this.open(callback || function (err) { + if (err) self.emit('error', err) + }) // Create manifest based on deferred-leveldown's this.supports = supports(this.db.supports, { @@ -97232,7 +71902,7 @@ LevelUP.errors = errors module.exports = LevelUP.default = LevelUP }).call(this,require('_process')) -},{"./batch":870,"./common":871,"./promisify":873,"_process":1438,"assert":78,"deferred-leveldown":258,"events":370,"level-errors":845,"level-iterator-stream":846,"level-supports":869,"util":1776,"xtend":1860}],873:[function(require,module,exports){ +},{"./batch":711,"./common":712,"./promisify":714,"_process":1258,"assert":26,"deferred-leveldown":217,"events":272,"level-errors":679,"level-iterator-stream":680,"level-supports":708,"util":1512,"xtend":715}],714:[function(require,module,exports){ function promisify () { var callback var promise = new Promise(function (resolve, reject) { @@ -97247,13 +71917,13 @@ function promisify () { module.exports = promisify -},{}],874:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":875,"_process":1438,"dup":247}],875:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":876}],876:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],877:[function(require,module,exports){ +},{}],715:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],716:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":717,"_process":1258,"dup":208}],717:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],718:[function(require,module,exports){ 'use strict' const PeerId = require('peer-id') @@ -97325,7 +71995,7 @@ class Bootstrap extends EventEmitter { exports = module.exports = Bootstrap exports.tag = 'bootstrap' -},{"async/nextTick":140,"debug":874,"events":370,"mafmt":1296,"multiaddr":1314,"peer-id":1432,"peer-info":1433}],878:[function(require,module,exports){ +},{"async/nextTick":90,"debug":716,"events":272,"mafmt":1125,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],719:[function(require,module,exports){ 'use strict' const secp256k1 = require('secp256k1') @@ -97416,7 +72086,7 @@ module.exports = (randomBytes) => { } } -},{"async/setImmediate":146,"multihashing-async":1336,"secp256k1":1601}],879:[function(require,module,exports){ +},{"async/setImmediate":96,"multihashing-async":1161,"secp256k1":1373}],720:[function(require,module,exports){ 'use strict' const bs58 = require('bs58') @@ -97556,7 +72226,7 @@ module.exports = (keysProtobuf, randomBytes, crypto) => { } } -},{"./crypto":878,"bs58":213,"multihashing-async":1336}],880:[function(require,module,exports){ +},{"./crypto":719,"bs58":177,"multihashing-async":1161}],721:[function(require,module,exports){ 'use strict'; const asn1 = exports; @@ -97569,7 +72239,7 @@ asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); -},{"./asn1/api":881,"./asn1/base":883,"./asn1/constants":887,"./asn1/decoders":889,"./asn1/encoders":892,"bn.js":171}],881:[function(require,module,exports){ +},{"./asn1/api":722,"./asn1/base":724,"./asn1/constants":728,"./asn1/decoders":730,"./asn1/encoders":733,"bn.js":135}],722:[function(require,module,exports){ 'use strict'; const encoders = require('./encoders'); @@ -97628,7 +72298,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; -},{"./decoders":889,"./encoders":892,"inherits":453}],882:[function(require,module,exports){ +},{"./decoders":730,"./encoders":733,"inherits":317}],723:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -97783,7 +72453,7 @@ EncoderBuffer.prototype.join = function join(out, offset) { return out; }; -},{"../base/reporter":885,"buffer":217,"inherits":453}],883:[function(require,module,exports){ +},{"../base/reporter":726,"buffer":181,"inherits":317}],724:[function(require,module,exports){ 'use strict'; const base = exports; @@ -97793,7 +72463,7 @@ base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); -},{"./buffer":882,"./node":884,"./reporter":885}],884:[function(require,module,exports){ +},{"./buffer":723,"./node":725,"./reporter":726}],725:[function(require,module,exports){ 'use strict'; const Reporter = require('../base/reporter').Reporter; @@ -98433,7 +73103,7 @@ Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); }; -},{"../base/buffer":882,"../base/reporter":885,"minimalistic-assert":1303}],885:[function(require,module,exports){ +},{"../base/buffer":723,"../base/reporter":726,"minimalistic-assert":1129}],726:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -98558,7 +73228,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) { return this; }; -},{"inherits":453}],886:[function(require,module,exports){ +},{"inherits":317}],727:[function(require,module,exports){ 'use strict'; // Helper @@ -98618,7 +73288,7 @@ exports.tag = { }; exports.tagByName = reverse(exports.tag); -},{}],887:[function(require,module,exports){ +},{}],728:[function(require,module,exports){ 'use strict'; const constants = exports; @@ -98641,7 +73311,7 @@ constants._reverse = function reverse(map) { constants.der = require('./der'); -},{"./der":886}],888:[function(require,module,exports){ +},{"./der":727}],729:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -98978,7 +73648,7 @@ function derDecodeLen(buf, primitive, fail) { return len; } -},{"../base/buffer":882,"../base/node":884,"../constants/der":886,"bn.js":171,"inherits":453}],889:[function(require,module,exports){ +},{"../base/buffer":723,"../base/node":725,"../constants/der":727,"bn.js":135,"inherits":317}],730:[function(require,module,exports){ 'use strict'; const decoders = exports; @@ -98986,7 +73656,7 @@ const decoders = exports; decoders.der = require('./der'); decoders.pem = require('./pem'); -},{"./der":888,"./pem":890}],890:[function(require,module,exports){ +},{"./der":729,"./pem":731}],731:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -99039,7 +73709,7 @@ PEMDecoder.prototype.decode = function decode(data, options) { return DERDecoder.prototype.decode.call(this, input, options); }; -},{"./der":888,"buffer":217,"inherits":453}],891:[function(require,module,exports){ +},{"./der":729,"buffer":181,"inherits":317}],732:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -99336,7 +74006,7 @@ function encodeTag(tag, primitive, cls, reporter) { return res; } -},{"../base/node":884,"../constants/der":886,"buffer":217,"inherits":453}],892:[function(require,module,exports){ +},{"../base/node":725,"../constants/der":727,"buffer":181,"inherits":317}],733:[function(require,module,exports){ 'use strict'; const encoders = exports; @@ -99344,7 +74014,7 @@ const encoders = exports; encoders.der = require('./der'); encoders.pem = require('./pem'); -},{"./der":891,"./pem":893}],893:[function(require,module,exports){ +},{"./der":732,"./pem":734}],734:[function(require,module,exports){ 'use strict'; const inherits = require('inherits'); @@ -99369,19 +74039,17 @@ PEMEncoder.prototype.encode = function encode(data, options) { return out.join('\n'); }; -},{"./der":891,"inherits":453}],894:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],895:[function(require,module,exports){ -arguments[4][469][0].apply(exports,arguments) -},{"./utils":899,"blakejs":168,"buffer":217,"dup":469}],896:[function(require,module,exports){ -arguments[4][470][0].apply(exports,arguments) -},{"buffer":217,"dup":470,"nodeify":1384}],897:[function(require,module,exports){ -arguments[4][471][0].apply(exports,arguments) -},{"./blake":895,"./crypto-sha1-2":896,"./utils":899,"buffer":217,"dup":471,"js-sha3":894,"murmurhash3js":1354}],898:[function(require,module,exports){ -arguments[4][472][0].apply(exports,arguments) -},{"./crypto":897,"buffer":217,"dup":472,"multihashes":1331}],899:[function(require,module,exports){ -arguments[4][473][0].apply(exports,arguments) -},{"_process":1438,"buffer":217,"dup":473}],900:[function(require,module,exports){ +},{"./der":732,"inherits":317}],735:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./utils":739,"blakejs":132,"buffer":181,"dup":331}],736:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"buffer":181,"dup":332,"nodeify":1225}],737:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"./blake":735,"./crypto-sha1-2":736,"./utils":739,"buffer":181,"dup":333,"js-sha3":666,"murmurhash3js":1179}],738:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"./crypto":737,"buffer":181,"dup":334,"multihashes":1157}],739:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"_process":1258,"buffer":181,"dup":335}],740:[function(require,module,exports){ (function(nacl) { 'use strict'; @@ -101760,7 +76428,7 @@ nacl.setPRNG = function(fn) { })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); -},{"crypto":182}],901:[function(require,module,exports){ +},{"crypto":146}],741:[function(require,module,exports){ 'use strict' const crypto = require('browserify-aes') @@ -101770,7 +76438,7 @@ module.exports = { createDecipheriv: crypto.createDecipheriv } -},{"browserify-aes":185}],902:[function(require,module,exports){ +},{"browserify-aes":149}],742:[function(require,module,exports){ 'use strict' const ciphers = require('./ciphers') @@ -101802,7 +76470,7 @@ exports.create = function (key, iv, callback) { callback(null, res) } -},{"./ciphers":901}],903:[function(require,module,exports){ +},{"./ciphers":741}],743:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -101845,7 +76513,7 @@ exports.create = function (hashType, secret, callback) { } }).call(this,require("buffer").Buffer) -},{"../nodeify":916,"../webcrypto":920,"./lengths":904,"buffer":217}],904:[function(require,module,exports){ +},{"../nodeify":756,"../webcrypto":760,"./lengths":744,"buffer":181}],744:[function(require,module,exports){ 'use strict' module.exports = { @@ -101854,7 +76522,7 @@ module.exports = { SHA512: 64 } -},{}],905:[function(require,module,exports){ +},{}],745:[function(require,module,exports){ 'use strict' const hmac = require('./hmac') @@ -101869,7 +76537,7 @@ exports.keys = keys exports.randomBytes = require('./random-bytes') exports.pbkdf2 = require('./pbkdf2') -},{"./aes":902,"./hmac":903,"./keys":910,"./pbkdf2":917,"./random-bytes":918}],906:[function(require,module,exports){ +},{"./aes":742,"./hmac":743,"./keys":750,"./pbkdf2":757,"./random-bytes":758}],746:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102000,7 +76668,7 @@ function unmarshalPrivateKey (curve, key) { } }).call(this,require("buffer").Buffer) -},{"../nodeify":916,"../util":919,"../webcrypto":920,"asn1.js":880,"buffer":217}],907:[function(require,module,exports){ +},{"../nodeify":756,"../util":759,"../webcrypto":760,"asn1.js":721,"buffer":181}],747:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102187,7 +76855,7 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"./ed25519":908,"./keys.proto":912,"bs58":213,"buffer":217,"multihashing-async":898,"protons":1454}],908:[function(require,module,exports){ +},{"./ed25519":748,"./keys.proto":752,"bs58":177,"buffer":181,"multihashing-async":738,"protons":1274}],748:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102242,7 +76910,7 @@ exports.hashAndVerify = function (key, sig, msg, callback) { } }).call(this,require("buffer").Buffer) -},{"async/nextTick":140,"buffer":217,"tweetnacl":900}],909:[function(require,module,exports){ +},{"async/nextTick":90,"buffer":181,"tweetnacl":740}],749:[function(require,module,exports){ 'use strict' const ecdh = require('./ecdh') @@ -102255,7 +76923,7 @@ module.exports = (curve, callback) => { ecdh.generateEphmeralKeyPair(curve, callback) } -},{"./ecdh":906}],910:[function(require,module,exports){ +},{"./ecdh":746}],750:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102394,7 +77062,7 @@ exports.import = (pem, password, callback) => { } }).call(this,require("buffer").Buffer) -},{"../random-bytes":918,"./ed25519-class":907,"./ephemeral-keys":909,"./key-stretcher":911,"./keys.proto":912,"./rsa-class":914,"buffer":217,"libp2p-crypto-secp256k1":879,"node-forge/lib/asn1":1361,"node-forge/lib/forge":1366,"node-forge/lib/pbe":1371,"node-forge/lib/rsa":1379,"protons":1454}],911:[function(require,module,exports){ +},{"../random-bytes":758,"./ed25519-class":747,"./ephemeral-keys":749,"./key-stretcher":751,"./keys.proto":752,"./rsa-class":754,"buffer":181,"libp2p-crypto-secp256k1":720,"node-forge/lib/asn1":1202,"node-forge/lib/forge":1207,"node-forge/lib/pbe":1212,"node-forge/lib/rsa":1220,"protons":1274}],751:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102506,7 +77174,7 @@ module.exports = (cipherType, hash, secret, callback) => { } }).call(this,require("buffer").Buffer) -},{"../hmac":903,"async/whilst":153,"buffer":217}],912:[function(require,module,exports){ +},{"../hmac":743,"async/whilst":103,"buffer":181}],752:[function(require,module,exports){ 'use strict' module.exports = `enum KeyType { @@ -102522,7 +77190,7 @@ message PrivateKey { required KeyType Type = 1; required bytes Data = 2; }` -},{}],913:[function(require,module,exports){ +},{}],753:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -102641,7 +77309,7 @@ function derivePublicFromPrivate (jwKey) { } }).call(this,require("buffer").Buffer) -},{"../nodeify":916,"../random-bytes":918,"../webcrypto":920,"./rsa-utils":915,"buffer":217}],914:[function(require,module,exports){ +},{"../nodeify":756,"../random-bytes":758,"../webcrypto":760,"./rsa-utils":755,"buffer":181}],754:[function(require,module,exports){ 'use strict' const multihashing = require('multihashing-async') @@ -102855,7 +77523,7 @@ module.exports = { fromJwk } -},{"./keys.proto":912,"./rsa":913,"async/nextTick":140,"bs58":213,"multihashing-async":898,"node-forge/lib/forge":1366,"node-forge/lib/pbe":1371,"node-forge/lib/sha512":1382,"protons":1454}],915:[function(require,module,exports){ +},{"./keys.proto":752,"./rsa":753,"async/nextTick":90,"bs58":177,"multihashing-async":738,"node-forge/lib/forge":1207,"node-forge/lib/pbe":1212,"node-forge/lib/sha512":1223,"protons":1274}],755:[function(require,module,exports){ 'use strict' const asn1 = require('asn1.js') @@ -102971,7 +77639,7 @@ exports.jwkToPkix = function (jwk) { }, 'der') } -},{"./../util":919,"asn1.js":880}],916:[function(require,module,exports){ +},{"./../util":759,"asn1.js":721}],756:[function(require,module,exports){ 'use strict' // Based on npmjs.com/nodeify but without additional `nextTick` calls @@ -102984,7 +77652,7 @@ module.exports = function nodeify (promise, cb) { }) } -},{}],917:[function(require,module,exports){ +},{}],757:[function(require,module,exports){ 'use strict' const forgePbkdf2 = require('node-forge/lib/pbkdf2') @@ -103029,7 +77697,7 @@ function pbkdf2 (password, salt, iterations, keySize, hash) { module.exports = pbkdf2 -},{"node-forge/lib/pbkdf2":1372,"node-forge/lib/util":1383}],918:[function(require,module,exports){ +},{"node-forge/lib/pbkdf2":1213,"node-forge/lib/util":1224}],758:[function(require,module,exports){ 'use strict' const randomBytes = require('iso-random-stream/src/random') @@ -103040,7 +77708,7 @@ module.exports = function (number) { return randomBytes(number) } -},{"iso-random-stream/src/random":781}],919:[function(require,module,exports){ +},{"iso-random-stream/src/random":618}],759:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -103064,14 +77732,14 @@ exports.toBn = function toBn (str) { } }).call(this,require("buffer").Buffer) -},{"asn1.js":880,"buffer":217}],920:[function(require,module,exports){ +},{"asn1.js":721,"buffer":181}],760:[function(require,module,exports){ /* global self */ 'use strict' module.exports = self.crypto || self.msCrypto -},{}],921:[function(require,module,exports){ +},{}],761:[function(require,module,exports){ (function (Buffer){ var Writable = require('readable-stream').Writable var inherits = require('inherits') @@ -103209,56 +77877,45 @@ function u8Concat (parts) { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"inherits":453,"readable-stream":965}],922:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":923,"_process":1438,"dup":247}],923:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":950}],924:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],925:[function(require,module,exports){ +},{"buffer":181,"inherits":317,"readable-stream":804}],762:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":763,"_process":1258,"dup":208}],763:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],764:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],765:[function(require,module,exports){ module.exports={ "_args": [ [ - "ipfs-http-client@^33.0.2", - "/var/www/html/ethoFSV2/node_modules/libp2p-delegated-content-routing" + "ipfs-http-client@33.1.1", + "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet" ] ], - "_from": "ipfs-http-client@>=33.0.2 <34.0.0", - "_hasShrinkwrap": false, + "_from": "ipfs-http-client@33.1.1", "_id": "ipfs-http-client@33.1.1", - "_inCache": true, - "_installable": true, + "_inBundle": false, + "_integrity": "sha512-iwtLL3lOIzxXJFwLnOEtFUv1cYTuWJ0NauD7rpMEd/y4C7z6fuN6TSF4h547lxMh7sJWv+6Z0PmOA5N8FzUHJw==", "_location": "/libp2p-delegated-content-routing/ipfs-http-client", - "_nodeVersion": "12.2.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/ipfs-http-client_33.1.1_1564166843634_0.48463625472557426" - }, - "_npmUser": { - "email": "alan138@gmail.com", - "name": "alanshaw" - }, - "_npmVersion": "6.9.0", "_phantomChildren": {}, "_requested": { + "type": "version", + "registry": true, + "raw": "ipfs-http-client@33.1.1", "name": "ipfs-http-client", - "raw": "ipfs-http-client@^33.0.2", - "rawSpec": "^33.0.2", - "scope": null, - "spec": ">=33.0.2 <34.0.0", - "type": "range" + "escapedName": "ipfs-http-client", + "rawSpec": "33.1.1", + "saveSpec": null, + "fetchSpec": "33.1.1" }, "_requiredBy": [ "/libp2p-delegated-content-routing" ], "_resolved": "https://registry.npmjs.org/ipfs-http-client/-/ipfs-http-client-33.1.1.tgz", - "_shasum": "6ddc13e86f8db768093290b19537d2388c74dd45", - "_shrinkwrap": null, - "_spec": "ipfs-http-client@^33.0.2", - "_where": "/var/www/html/ethoFSV2/node_modules/libp2p-delegated-content-routing", + "_spec": "33.1.1", + "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet", "browser": { - "fs": false, "glob": false, + "fs": false, "stream": "readable-stream" }, "bugs": { @@ -103266,12 +77923,12 @@ module.exports={ }, "contributors": [ { - "name": "Matt Ober", - "email": "matt.ober3@gmail.com" + "name": "Alan Shaw", + "email": "alan.shaw@protocol.ai" }, { "name": "Alan Shaw", - "email": "alan.shaw@protocol.ai" + "email": "alan@tableflip.io" }, { "name": "Alex Mingoia", @@ -103450,8 +78107,8 @@ module.exports={ "email": "mappum@gmail.com" }, { - "name": "Alan Shaw", - "email": "alan@tableflip.io" + "name": "Matt Ober", + "email": "matt.ober3@gmail.com" }, { "name": "Maxime Lathuilière", @@ -103694,20 +78351,14 @@ module.exports={ "nock": "^10.0.2", "stream-equal": "^1.1.1" }, - "directories": {}, - "dist": { - "fileCount": 160, - "integrity": "sha512-iwtLL3lOIzxXJFwLnOEtFUv1cYTuWJ0NauD7rpMEd/y4C7z6fuN6TSF4h547lxMh7sJWv+6Z0PmOA5N8FzUHJw==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdO0q8CRA9TVsSAnZWagAA2SgP/36mFRoUaC8+aISz0/NY\nmKrhUbhgUHAaXG57LHzVdfJy+P4bV6z/+NUhe7UVRacbbCTHQ0DiYPaA5Ojz\n/+DSjZZjG9UEAyM7O7WNYnze8buRAgT4FpzzzBxiLhMCqYEjZNJJglwEZ8Ft\n5kf1MLw3G2uzgsTTxt+4gqgwxF27n4ngTlwIW4nFsGrRABFb49AjaAL9/r8T\njuZEdVnjzQ2UW4vdax5rONGKxmapZSxEpbNtMWGT2mAm5Unt1HItnT6EoTiQ\nTu5Xa0uAT4Jiu81w2cOewSxGeZRrvlFGoJQyu5NTnUqjD68zoHBJkuNEuCzl\nTe7gCMHdkwSw5eMf28+j8jpVHmb2bGPrMQhFVoUlzGcn3nw3a173A+9E+TH2\nlbqcWFx/aZZGXCNAA68UosZRaWttTmEMFu18EHXH9pene0GQ/gGcY25XOOm+\nnHeBFgLAvcfd7d2VlhXW9bS5RLNEhuCTubwtNoVCXE3fkfjdwuza94Ru2lsk\nbmv1fxS3DZhQpinucXsv2iRJ1ShCQwRMavT2a/CJwZ8c7i2Nxys1zH9iqEAW\nGfqhu2K6VQwwp6aH4Z8aY1deovQonFy7lOMwgzoLjy4uX9fGMfIp/roi3QTH\nVm/UGI3PTNnIxVXAq11aDfwxXxekZ7OWIdcHD09qOMeC42iLJxtzcvLSs4wL\nRiZz\r\n=u4SQ\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "6ddc13e86f8db768093290b19537d2388c74dd45", - "tarball": "https://registry.npmjs.org/ipfs-http-client/-/ipfs-http-client-33.1.1.tgz", - "unpackedSize": 8698078 - }, "engines": { "node": ">=8.3.0", "npm": ">=3.0.0" }, - "gitHead": "b65bba35368280a90aa5f7cab9c3a2ea256c50cd", + "files": [ + "src", + "dist" + ], "homepage": "https://github.com/ipfs/js-ipfs-http-client", "keywords": [ "ipfs" @@ -103715,15 +78366,7 @@ module.exports={ "leadMaintainer": "Alan Shaw ", "license": "MIT", "main": "src/index.js", - "maintainers": [ - { - "name": "alanshaw", - "email": "alan138@gmail.com" - } - ], "name": "ipfs-http-client", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/ipfs/js-ipfs-http-client.git" @@ -103743,7 +78386,7 @@ module.exports={ "version": "33.1.1" } -},{}],926:[function(require,module,exports){ +},{}],766:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -103808,7 +78451,7 @@ module.exports = (send) => { }) } -},{"../utils/stream-to-value-with-transformer":948,"err-code":924,"multiaddr":1314,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],927:[function(require,module,exports){ +},{"../utils/stream-to-value-with-transformer":788,"err-code":764,"multiaddr":1140,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],767:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -103873,7 +78516,7 @@ module.exports = (send) => { }) } -},{"../utils/stream-to-value-with-transformer":948,"multiaddr":1314,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],928:[function(require,module,exports){ +},{"../utils/stream-to-value-with-transformer":788,"multiaddr":1140,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],768:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -103924,7 +78567,7 @@ module.exports = (send) => { }) } -},{"promisify-es6":1443}],929:[function(require,module,exports){ +},{"promisify-es6":1263}],769:[function(require,module,exports){ 'use strict' const moduleConfig = require('../utils/module-config') @@ -103943,7 +78586,7 @@ module.exports = (arg) => { } } -},{"../utils/module-config":945,"./findpeer":926,"./findprovs":927,"./get":928,"./provide":930,"./put":931,"./query":932}],930:[function(require,module,exports){ +},{"../utils/module-config":785,"./findpeer":766,"./findprovs":767,"./get":768,"./provide":770,"./put":771,"./query":772}],770:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -103982,7 +78625,7 @@ module.exports = (send) => { }) } -},{"cids":222,"promisify-es6":1443}],931:[function(require,module,exports){ +},{"cids":185,"promisify-es6":1263}],771:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104009,7 +78652,7 @@ module.exports = (send) => { }) } -},{"promisify-es6":1443}],932:[function(require,module,exports){ +},{"promisify-es6":1263}],772:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104052,7 +78695,7 @@ module.exports = (send) => { }) } -},{"../utils/stream-to-value-with-transformer":948,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],933:[function(require,module,exports){ +},{"../utils/stream-to-value-with-transformer":788,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],773:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -104081,7 +78724,7 @@ module.exports = (send) => { } } -},{"../utils/module-config":945,"pull-defer":1467,"pull-stream":1495,"stream-to-pull-stream":1735}],934:[function(require,module,exports){ +},{"../utils/module-config":785,"pull-defer":1285,"pull-stream":1311,"stream-to-pull-stream":1497}],774:[function(require,module,exports){ 'use strict' const Stream = require('readable-stream') @@ -104108,7 +78751,7 @@ module.exports = (send) => { } } -},{"pump":1537,"readable-stream":965,"through2":966}],935:[function(require,module,exports){ +},{"pump":1353,"readable-stream":804,"through2":807}],775:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104142,7 +78785,7 @@ module.exports = (arg) => { }) } -},{"../utils/module-config":945,"../utils/stream-to-value-with-transformer":948,"promisify-es6":1443}],936:[function(require,module,exports){ +},{"../utils/module-config":785,"../utils/stream-to-value-with-transformer":788,"promisify-es6":1263}],776:[function(require,module,exports){ 'use strict' const IsIpfs = require('is-ipfs') @@ -104219,7 +78862,7 @@ module.exports.normalizeOpts = (opts) => { return opts } -},{"../utils/clean-cid":943,"../utils/module-config":945,"../utils/stream-to-value-with-transformer":948,"./refs-local":935,"./refs-local-pull-stream":933,"./refs-local-readable-stream":934,"is-ipfs":775,"promisify-es6":1443}],937:[function(require,module,exports){ +},{"../utils/clean-cid":783,"../utils/module-config":785,"../utils/stream-to-value-with-transformer":788,"./refs-local":775,"./refs-local-pull-stream":773,"./refs-local-readable-stream":774,"is-ipfs":614,"promisify-es6":1263}],777:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104254,7 +78897,7 @@ module.exports = (send) => { }) } -},{"multiaddr":1314,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],938:[function(require,module,exports){ +},{"multiaddr":1140,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],778:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104273,7 +78916,7 @@ module.exports = (send) => { }) } -},{"promisify-es6":1443}],939:[function(require,module,exports){ +},{"promisify-es6":1263}],779:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104292,7 +78935,7 @@ module.exports = (send) => { }) } -},{"promisify-es6":1443}],940:[function(require,module,exports){ +},{"promisify-es6":1263}],780:[function(require,module,exports){ 'use strict' const moduleConfig = require('../utils/module-config') @@ -104309,7 +78952,7 @@ module.exports = (arg) => { } } -},{"../utils/module-config":945,"./addrs":937,"./connect":938,"./disconnect":939,"./localAddrs":941,"./peers":942}],941:[function(require,module,exports){ +},{"../utils/module-config":785,"./addrs":777,"./connect":778,"./disconnect":779,"./localAddrs":781,"./peers":782}],781:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104335,7 +78978,7 @@ module.exports = (send) => { }) } -},{"multiaddr":1314,"promisify-es6":1443}],942:[function(require,module,exports){ +},{"multiaddr":1140,"promisify-es6":1263}],782:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -104411,7 +79054,7 @@ function parsePeer (verbose, peer) { return res } -},{"multiaddr":1314,"peer-id":1432,"promisify-es6":1443}],943:[function(require,module,exports){ +},{"multiaddr":1140,"peer-id":1253,"promisify-es6":1263}],783:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -104432,7 +79075,7 @@ module.exports = function (cid) { } }).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"cids":222}],944:[function(require,module,exports){ +},{"../../../../../is-buffer/index.js":608,"cids":185}],784:[function(require,module,exports){ 'use strict' const pkg = require('../../package.json') @@ -104447,7 +79090,7 @@ exports = module.exports = () => { } } -},{"../../package.json":925}],945:[function(require,module,exports){ +},{"../../package.json":765}],785:[function(require,module,exports){ 'use strict' const getConfig = require('./default-config') @@ -104471,7 +79114,7 @@ module.exports = (arg) => { } } -},{"./default-config":944,"./send-request":946,"multiaddr":1314}],946:[function(require,module,exports){ +},{"./default-config":784,"./send-request":786,"multiaddr":1140}],786:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -104714,7 +79357,7 @@ exports = module.exports = (config) => { } }).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"./stream-to-json-value":947,"./stream-to-value":949,"debug":922,"detect-node":271,"iso-stream-http":782,"ndjson":1357,"once":1394,"pump":1537,"qs":1540,"qs/lib/utils":1543}],947:[function(require,module,exports){ +},{"../../../../../is-buffer/index.js":608,"./stream-to-json-value":787,"./stream-to-value":789,"debug":762,"detect-node":228,"iso-stream-http":619,"ndjson":1182,"once":1228,"pump":1353,"qs":1355,"qs/lib/utils":1358}],787:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -104752,7 +79395,7 @@ function streamToJsonValue (res, cb) { module.exports = streamToJsonValue }).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")}) -},{"../../../../../is-buffer/index.js":766,"./stream-to-value":949}],948:[function(require,module,exports){ +},{"../../../../../is-buffer/index.js":608,"./stream-to-value":789}],788:[function(require,module,exports){ 'use strict' const streamToValue = require('./stream-to-value') @@ -104772,7 +79415,7 @@ function streamToValueWithTransformer (response, transformer, callback) { module.exports = streamToValueWithTransformer -},{"./stream-to-value":949}],949:[function(require,module,exports){ +},{"./stream-to-value":789}],789:[function(require,module,exports){ 'use strict' const pump = require('pump') @@ -104792,39 +79435,41 @@ function streamToValue (response, callback) { module.exports = streamToValue -},{"concat-stream":921,"pump":1537}],950:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],951:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],952:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],953:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":955,"./_stream_writable":957,"_process":1438,"dup":90,"inherits":453}],954:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":956,"dup":91,"inherits":453}],955:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":951,"../experimentalWarning":952,"./_stream_duplex":953,"./internal/streams/async_iterator":958,"./internal/streams/buffer_list":959,"./internal/streams/destroy":960,"./internal/streams/state":963,"./internal/streams/stream":964,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],956:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":951,"./_stream_duplex":953,"dup":93,"inherits":453}],957:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":951,"./_stream_duplex":953,"./internal/streams/destroy":960,"./internal/streams/state":963,"./internal/streams/stream":964,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],958:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":961,"_process":1438,"dup":95}],959:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],960:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],961:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":951,"dup":98}],962:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":951,"./end-of-stream":961,"dup":99}],963:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":951,"dup":100}],964:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],965:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":953,"./lib/_stream_passthrough.js":954,"./lib/_stream_readable.js":955,"./lib/_stream_transform.js":956,"./lib/_stream_writable.js":957,"./lib/internal/streams/end-of-stream.js":961,"./lib/internal/streams/pipeline.js":962,"dup":102}],966:[function(require,module,exports){ +},{"concat-stream":761,"pump":1353}],790:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],791:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],792:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":794,"./_stream_writable":796,"_process":1258,"dup":38,"inherits":317}],793:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":795,"dup":39,"inherits":317}],794:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":790,"../experimentalWarning":791,"./_stream_duplex":792,"./internal/streams/async_iterator":797,"./internal/streams/buffer_list":798,"./internal/streams/destroy":799,"./internal/streams/state":802,"./internal/streams/stream":803,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":806,"util":146}],795:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":790,"./_stream_duplex":792,"dup":41,"inherits":317}],796:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":790,"./_stream_duplex":792,"./internal/streams/destroy":799,"./internal/streams/state":802,"./internal/streams/stream":803,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],797:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":800,"_process":1258,"dup":43}],798:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],799:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],800:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":790,"dup":46}],801:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":790,"./end-of-stream":800,"dup":47}],802:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":790,"dup":48}],803:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],804:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":792,"./lib/_stream_passthrough.js":793,"./lib/_stream_readable.js":794,"./lib/_stream_transform.js":795,"./lib/_stream_writable.js":796,"./lib/internal/streams/end-of-stream.js":800,"./lib/internal/streams/pipeline.js":801,"dup":50}],805:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],806:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":805}],807:[function(require,module,exports){ (function (process){ var Transform = require('readable-stream').Transform , inherits = require('util').inherits @@ -104839,7 +79484,7 @@ inherits(DestroyableTransform, Transform) DestroyableTransform.prototype.destroy = function(err) { if (this._destroyed) return this._destroyed = true - + var self = this process.nextTick(function() { if (err) @@ -104923,7 +79568,7 @@ module.exports.obj = through2(function (options, transform, flush) { }) }).call(this,require('_process')) -},{"_process":1438,"readable-stream":965,"util":1776}],967:[function(require,module,exports){ +},{"_process":1258,"readable-stream":804,"util":1512}],808:[function(require,module,exports){ 'use strict' const dht = require('ipfs-http-client/src/dht') @@ -105035,58 +79680,47 @@ class DelegatedContentRouting { module.exports = DelegatedContentRouting -},{"ipfs-http-client/src/dht":929,"ipfs-http-client/src/files-regular/refs":936,"ipfs-http-client/src/swarm":940,"ipfs-http-client/src/utils/default-config":944,"multiaddr":1314,"p-queue":1400}],968:[function(require,module,exports){ -arguments[4][921][0].apply(exports,arguments) -},{"buffer":217,"dup":921,"inherits":453,"readable-stream":1001}],969:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":970,"_process":1438,"dup":247}],970:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":986}],971:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],972:[function(require,module,exports){ +},{"ipfs-http-client/src/dht":769,"ipfs-http-client/src/files-regular/refs":776,"ipfs-http-client/src/swarm":780,"ipfs-http-client/src/utils/default-config":784,"multiaddr":1140,"p-queue":1234}],809:[function(require,module,exports){ +arguments[4][761][0].apply(exports,arguments) +},{"buffer":181,"dup":761,"inherits":317,"readable-stream":841}],810:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":811,"_process":1258,"dup":208}],811:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],812:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],813:[function(require,module,exports){ module.exports={ "_args": [ [ - "ipfs-http-client@^33.0.1", - "/var/www/html/ethoFSV2/node_modules/libp2p-delegated-peer-routing" + "ipfs-http-client@33.1.1", + "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet" ] ], - "_from": "ipfs-http-client@>=33.0.1 <34.0.0", - "_hasShrinkwrap": false, + "_from": "ipfs-http-client@33.1.1", "_id": "ipfs-http-client@33.1.1", - "_inCache": true, - "_installable": true, + "_inBundle": false, + "_integrity": "sha512-iwtLL3lOIzxXJFwLnOEtFUv1cYTuWJ0NauD7rpMEd/y4C7z6fuN6TSF4h547lxMh7sJWv+6Z0PmOA5N8FzUHJw==", "_location": "/libp2p-delegated-peer-routing/ipfs-http-client", - "_nodeVersion": "12.2.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/ipfs-http-client_33.1.1_1564166843634_0.48463625472557426" - }, - "_npmUser": { - "email": "alan138@gmail.com", - "name": "alanshaw" - }, - "_npmVersion": "6.9.0", "_phantomChildren": {}, "_requested": { + "type": "version", + "registry": true, + "raw": "ipfs-http-client@33.1.1", "name": "ipfs-http-client", - "raw": "ipfs-http-client@^33.0.1", - "rawSpec": "^33.0.1", - "scope": null, - "spec": ">=33.0.1 <34.0.0", - "type": "range" + "escapedName": "ipfs-http-client", + "rawSpec": "33.1.1", + "saveSpec": null, + "fetchSpec": "33.1.1" }, "_requiredBy": [ "/libp2p-delegated-peer-routing" ], "_resolved": "https://registry.npmjs.org/ipfs-http-client/-/ipfs-http-client-33.1.1.tgz", - "_shasum": "6ddc13e86f8db768093290b19537d2388c74dd45", - "_shrinkwrap": null, - "_spec": "ipfs-http-client@^33.0.1", - "_where": "/var/www/html/ethoFSV2/node_modules/libp2p-delegated-peer-routing", + "_spec": "33.1.1", + "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet", "browser": { - "fs": false, "glob": false, + "fs": false, "stream": "readable-stream" }, "bugs": { @@ -105094,12 +79728,12 @@ module.exports={ }, "contributors": [ { - "name": "Matt Ober", - "email": "matt.ober3@gmail.com" + "name": "Alan Shaw", + "email": "alan.shaw@protocol.ai" }, { "name": "Alan Shaw", - "email": "alan.shaw@protocol.ai" + "email": "alan@tableflip.io" }, { "name": "Alex Mingoia", @@ -105278,8 +79912,8 @@ module.exports={ "email": "mappum@gmail.com" }, { - "name": "Alan Shaw", - "email": "alan@tableflip.io" + "name": "Matt Ober", + "email": "matt.ober3@gmail.com" }, { "name": "Maxime Lathuilière", @@ -105522,20 +80156,14 @@ module.exports={ "nock": "^10.0.2", "stream-equal": "^1.1.1" }, - "directories": {}, - "dist": { - "fileCount": 160, - "integrity": "sha512-iwtLL3lOIzxXJFwLnOEtFUv1cYTuWJ0NauD7rpMEd/y4C7z6fuN6TSF4h547lxMh7sJWv+6Z0PmOA5N8FzUHJw==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdO0q8CRA9TVsSAnZWagAA2SgP/36mFRoUaC8+aISz0/NY\nmKrhUbhgUHAaXG57LHzVdfJy+P4bV6z/+NUhe7UVRacbbCTHQ0DiYPaA5Ojz\n/+DSjZZjG9UEAyM7O7WNYnze8buRAgT4FpzzzBxiLhMCqYEjZNJJglwEZ8Ft\n5kf1MLw3G2uzgsTTxt+4gqgwxF27n4ngTlwIW4nFsGrRABFb49AjaAL9/r8T\njuZEdVnjzQ2UW4vdax5rONGKxmapZSxEpbNtMWGT2mAm5Unt1HItnT6EoTiQ\nTu5Xa0uAT4Jiu81w2cOewSxGeZRrvlFGoJQyu5NTnUqjD68zoHBJkuNEuCzl\nTe7gCMHdkwSw5eMf28+j8jpVHmb2bGPrMQhFVoUlzGcn3nw3a173A+9E+TH2\nlbqcWFx/aZZGXCNAA68UosZRaWttTmEMFu18EHXH9pene0GQ/gGcY25XOOm+\nnHeBFgLAvcfd7d2VlhXW9bS5RLNEhuCTubwtNoVCXE3fkfjdwuza94Ru2lsk\nbmv1fxS3DZhQpinucXsv2iRJ1ShCQwRMavT2a/CJwZ8c7i2Nxys1zH9iqEAW\nGfqhu2K6VQwwp6aH4Z8aY1deovQonFy7lOMwgzoLjy4uX9fGMfIp/roi3QTH\nVm/UGI3PTNnIxVXAq11aDfwxXxekZ7OWIdcHD09qOMeC42iLJxtzcvLSs4wL\nRiZz\r\n=u4SQ\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "6ddc13e86f8db768093290b19537d2388c74dd45", - "tarball": "https://registry.npmjs.org/ipfs-http-client/-/ipfs-http-client-33.1.1.tgz", - "unpackedSize": 8698078 - }, "engines": { "node": ">=8.3.0", "npm": ">=3.0.0" }, - "gitHead": "b65bba35368280a90aa5f7cab9c3a2ea256c50cd", + "files": [ + "src", + "dist" + ], "homepage": "https://github.com/ipfs/js-ipfs-http-client", "keywords": [ "ipfs" @@ -105543,15 +80171,7 @@ module.exports={ "leadMaintainer": "Alan Shaw ", "license": "MIT", "main": "src/index.js", - "maintainers": [ - { - "name": "alanshaw", - "email": "alan138@gmail.com" - } - ], "name": "ipfs-http-client", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/ipfs/js-ipfs-http-client.git" @@ -105571,65 +80191,67 @@ module.exports={ "version": "33.1.1" } -},{}],973:[function(require,module,exports){ -arguments[4][926][0].apply(exports,arguments) -},{"../utils/stream-to-value-with-transformer":984,"dup":926,"err-code":971,"multiaddr":1314,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],974:[function(require,module,exports){ -arguments[4][927][0].apply(exports,arguments) -},{"../utils/stream-to-value-with-transformer":984,"dup":927,"multiaddr":1314,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],975:[function(require,module,exports){ -arguments[4][928][0].apply(exports,arguments) -},{"dup":928,"promisify-es6":1443}],976:[function(require,module,exports){ -arguments[4][929][0].apply(exports,arguments) -},{"../utils/module-config":981,"./findpeer":973,"./findprovs":974,"./get":975,"./provide":977,"./put":978,"./query":979,"dup":929}],977:[function(require,module,exports){ -arguments[4][930][0].apply(exports,arguments) -},{"cids":222,"dup":930,"promisify-es6":1443}],978:[function(require,module,exports){ -arguments[4][931][0].apply(exports,arguments) -},{"dup":931,"promisify-es6":1443}],979:[function(require,module,exports){ -arguments[4][932][0].apply(exports,arguments) -},{"../utils/stream-to-value-with-transformer":984,"dup":932,"peer-id":1432,"peer-info":1433,"promisify-es6":1443}],980:[function(require,module,exports){ -arguments[4][944][0].apply(exports,arguments) -},{"../../package.json":972,"dup":944}],981:[function(require,module,exports){ -arguments[4][945][0].apply(exports,arguments) -},{"./default-config":980,"./send-request":982,"dup":945,"multiaddr":1314}],982:[function(require,module,exports){ -arguments[4][946][0].apply(exports,arguments) -},{"../../../../../is-buffer/index.js":766,"./stream-to-json-value":983,"./stream-to-value":985,"debug":969,"detect-node":271,"dup":946,"iso-stream-http":782,"ndjson":1357,"once":1394,"pump":1537,"qs":1540,"qs/lib/utils":1543}],983:[function(require,module,exports){ -arguments[4][947][0].apply(exports,arguments) -},{"../../../../../is-buffer/index.js":766,"./stream-to-value":985,"dup":947}],984:[function(require,module,exports){ -arguments[4][948][0].apply(exports,arguments) -},{"./stream-to-value":985,"dup":948}],985:[function(require,module,exports){ -arguments[4][949][0].apply(exports,arguments) -},{"concat-stream":968,"dup":949,"pump":1537}],986:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],987:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],988:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],989:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":991,"./_stream_writable":993,"_process":1438,"dup":90,"inherits":453}],990:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":992,"dup":91,"inherits":453}],991:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":987,"../experimentalWarning":988,"./_stream_duplex":989,"./internal/streams/async_iterator":994,"./internal/streams/buffer_list":995,"./internal/streams/destroy":996,"./internal/streams/state":999,"./internal/streams/stream":1000,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],992:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":987,"./_stream_duplex":989,"dup":93,"inherits":453}],993:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":987,"./_stream_duplex":989,"./internal/streams/destroy":996,"./internal/streams/state":999,"./internal/streams/stream":1000,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],994:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":997,"_process":1438,"dup":95}],995:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],996:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],997:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":987,"dup":98}],998:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":987,"./end-of-stream":997,"dup":99}],999:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":987,"dup":100}],1000:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],1001:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":989,"./lib/_stream_passthrough.js":990,"./lib/_stream_readable.js":991,"./lib/_stream_transform.js":992,"./lib/_stream_writable.js":993,"./lib/internal/streams/end-of-stream.js":997,"./lib/internal/streams/pipeline.js":998,"dup":102}],1002:[function(require,module,exports){ +},{}],814:[function(require,module,exports){ +arguments[4][766][0].apply(exports,arguments) +},{"../utils/stream-to-value-with-transformer":825,"dup":766,"err-code":812,"multiaddr":1140,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],815:[function(require,module,exports){ +arguments[4][767][0].apply(exports,arguments) +},{"../utils/stream-to-value-with-transformer":825,"dup":767,"multiaddr":1140,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],816:[function(require,module,exports){ +arguments[4][768][0].apply(exports,arguments) +},{"dup":768,"promisify-es6":1263}],817:[function(require,module,exports){ +arguments[4][769][0].apply(exports,arguments) +},{"../utils/module-config":822,"./findpeer":814,"./findprovs":815,"./get":816,"./provide":818,"./put":819,"./query":820,"dup":769}],818:[function(require,module,exports){ +arguments[4][770][0].apply(exports,arguments) +},{"cids":185,"dup":770,"promisify-es6":1263}],819:[function(require,module,exports){ +arguments[4][771][0].apply(exports,arguments) +},{"dup":771,"promisify-es6":1263}],820:[function(require,module,exports){ +arguments[4][772][0].apply(exports,arguments) +},{"../utils/stream-to-value-with-transformer":825,"dup":772,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],821:[function(require,module,exports){ +arguments[4][784][0].apply(exports,arguments) +},{"../../package.json":813,"dup":784}],822:[function(require,module,exports){ +arguments[4][785][0].apply(exports,arguments) +},{"./default-config":821,"./send-request":823,"dup":785,"multiaddr":1140}],823:[function(require,module,exports){ +arguments[4][786][0].apply(exports,arguments) +},{"../../../../../is-buffer/index.js":608,"./stream-to-json-value":824,"./stream-to-value":826,"debug":810,"detect-node":228,"dup":786,"iso-stream-http":619,"ndjson":1182,"once":1228,"pump":1353,"qs":1355,"qs/lib/utils":1358}],824:[function(require,module,exports){ +arguments[4][787][0].apply(exports,arguments) +},{"../../../../../is-buffer/index.js":608,"./stream-to-value":826,"dup":787}],825:[function(require,module,exports){ +arguments[4][788][0].apply(exports,arguments) +},{"./stream-to-value":826,"dup":788}],826:[function(require,module,exports){ +arguments[4][789][0].apply(exports,arguments) +},{"concat-stream":809,"dup":789,"pump":1353}],827:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],828:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],829:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":831,"./_stream_writable":833,"_process":1258,"dup":38,"inherits":317}],830:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":832,"dup":39,"inherits":317}],831:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":827,"../experimentalWarning":828,"./_stream_duplex":829,"./internal/streams/async_iterator":834,"./internal/streams/buffer_list":835,"./internal/streams/destroy":836,"./internal/streams/state":839,"./internal/streams/stream":840,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":843,"util":146}],832:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":827,"./_stream_duplex":829,"dup":41,"inherits":317}],833:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":827,"./_stream_duplex":829,"./internal/streams/destroy":836,"./internal/streams/state":839,"./internal/streams/stream":840,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],834:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":837,"_process":1258,"dup":43}],835:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],836:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],837:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":827,"dup":46}],838:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":827,"./end-of-stream":837,"dup":47}],839:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":827,"dup":48}],840:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],841:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":829,"./lib/_stream_passthrough.js":830,"./lib/_stream_readable.js":831,"./lib/_stream_transform.js":832,"./lib/_stream_writable.js":833,"./lib/internal/streams/end-of-stream.js":837,"./lib/internal/streams/pipeline.js":838,"dup":50}],842:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],843:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":842}],844:[function(require,module,exports){ 'use strict' const PeerId = require('peer-id') @@ -105693,13 +80315,13 @@ class DelegatedPeerRouting { module.exports = DelegatedPeerRouting -},{"ipfs-http-client/src/dht":976,"ipfs-http-client/src/utils/default-config":980,"p-queue":1400,"peer-id":1432}],1003:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1004,"_process":1438,"dup":247}],1004:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1008}],1005:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1006:[function(require,module,exports){ +},{"ipfs-http-client/src/dht":817,"ipfs-http-client/src/utils/default-config":821,"p-queue":1234,"peer-id":1253}],845:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":846,"_process":1258,"dup":208}],846:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],847:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],848:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -105712,7 +80334,7 @@ module.exports = { multicodec: '/floodsub/1.0.0' } -},{"debug":1003}],1007:[function(require,module,exports){ +},{"debug":845}],849:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -106003,9 +80625,7 @@ class FloodSub extends BaseProtocol { module.exports = FloodSub module.exports.multicodec = multicodec -},{"./config":1006,"assert":78,"async/map":137,"async/setImmediate":146,"libp2p-pubsub":1101,"pull-length-prefixed":1475,"pull-stream":1495}],1008:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1009:[function(require,module,exports){ +},{"./config":848,"assert":26,"async/map":87,"async/setImmediate":96,"libp2p-pubsub":937,"pull-length-prefixed":1292,"pull-stream":1311}],850:[function(require,module,exports){ 'use strict' const second = exports.second = 1000 @@ -106031,7 +80651,7 @@ exports.GossipSubHeartbeatInterval = second // Fanout ttl exports.GossipSubFanoutTTL = minute -},{}],1010:[function(require,module,exports){ +},{}],851:[function(require,module,exports){ 'use strict' const constants = require('./constants') @@ -106200,7 +80820,7 @@ class Heartbeat { module.exports = Heartbeat -},{"./constants":1009,"err-code":1005}],1011:[function(require,module,exports){ +},{"./constants":850,"err-code":847}],852:[function(require,module,exports){ 'use strict' const assert = require('assert') @@ -106801,97 +81421,7 @@ class GossipSub extends BasicPubsub { module.exports = GossipSub -},{"./constants":1009,"./heartbeat":1010,"./message":1012,"./messageCache":1015,"./pubsub":1016,"assert":78,"libp2p-pubsub":1101}],1012:[function(require,module,exports){ -'use strict' - -const protons = require('protons') - -const rpcProto = protons(require('./rpc.proto.js')) -const topicDescriptorProto = protons(require('./topic-descriptor.proto.js')) - -exports = module.exports -exports.rpc = rpcProto -exports.td = topicDescriptorProto - -},{"./rpc.proto.js":1013,"./topic-descriptor.proto.js":1014,"protons":1454}],1013:[function(require,module,exports){ -'use strict' -module.exports = ` -message RPC { - repeated SubOpts subscriptions = 1; - repeated Message msgs = 2; - optional ControlMessage control = 3; - - message SubOpts { - optional bool subscribe = 1; // subscribe or unsubcribe - optional string topicID = 2; - } - - message Message { - optional bytes from = 1; - optional bytes data = 2; - optional bytes seqno = 3; - repeated string topicIDs = 4; - optional bytes signature = 5; - optional bytes key = 6; - } - - message ControlMessage { - repeated ControlIHave ihave = 1; - repeated ControlIWant iwant = 2; - repeated ControlGraft graft = 3; - repeated ControlPrune prune = 4; - } - - message ControlIHave { - optional string topicID = 1; - repeated string messageIDs = 2; - } - - message ControlIWant { - repeated string messageIDs = 1; - } - - message ControlGraft { - optional string topicID = 1; - } - - message ControlPrune { - optional string topicID = 1; - } -}` - -},{}],1014:[function(require,module,exports){ -'use strict' -module.exports = ` -message TopicDescriptor { - optional string name = 1; - optional AuthOpts auth = 2; - optional EncOpts enc = 3; - - message AuthOpts { - optional AuthMode mode = 1; - repeated bytes keys = 2; // root keys to trust - - enum AuthMode { - NONE = 0; // no authentication, anyone can publish - KEY = 1; // only messages signed by keys in the topic descriptor are accepted - WOT = 2; // web of trust, certificates can allow publisher set to grow - } - } - - message EncOpts { - optional EncMode mode = 1; - repeated bytes keyHashes = 2; // the hashes of the shared keys used (salted) - - enum EncMode { - NONE = 0; // no encryption, anyone can read - SHAREDKEY = 1; // messages are encrypted with shared key - WOT = 2; // web of trust, certificates can allow publisher set to grow - } - } -}` - -},{}],1015:[function(require,module,exports){ +},{"./constants":850,"./heartbeat":851,"./message":854,"./messageCache":853,"./pubsub":857,"assert":26,"libp2p-pubsub":937}],853:[function(require,module,exports){ 'use strict' const { utils } = require('libp2p-pubsub') @@ -107002,7 +81532,97 @@ module.exports = { MessageCache } -},{"libp2p-pubsub":1101}],1016:[function(require,module,exports){ +},{"libp2p-pubsub":937}],854:[function(require,module,exports){ +'use strict' + +const protons = require('protons') + +const rpcProto = protons(require('./rpc.proto.js')) +const topicDescriptorProto = protons(require('./topic-descriptor.proto.js')) + +exports = module.exports +exports.rpc = rpcProto +exports.td = topicDescriptorProto + +},{"./rpc.proto.js":855,"./topic-descriptor.proto.js":856,"protons":1274}],855:[function(require,module,exports){ +'use strict' +module.exports = ` +message RPC { + repeated SubOpts subscriptions = 1; + repeated Message msgs = 2; + optional ControlMessage control = 3; + + message SubOpts { + optional bool subscribe = 1; // subscribe or unsubcribe + optional string topicID = 2; + } + + message Message { + optional bytes from = 1; + optional bytes data = 2; + optional bytes seqno = 3; + repeated string topicIDs = 4; + optional bytes signature = 5; + optional bytes key = 6; + } + + message ControlMessage { + repeated ControlIHave ihave = 1; + repeated ControlIWant iwant = 2; + repeated ControlGraft graft = 3; + repeated ControlPrune prune = 4; + } + + message ControlIHave { + optional string topicID = 1; + repeated string messageIDs = 2; + } + + message ControlIWant { + repeated string messageIDs = 1; + } + + message ControlGraft { + optional string topicID = 1; + } + + message ControlPrune { + optional string topicID = 1; + } +}` + +},{}],856:[function(require,module,exports){ +'use strict' +module.exports = ` +message TopicDescriptor { + optional string name = 1; + optional AuthOpts auth = 2; + optional EncOpts enc = 3; + + message AuthOpts { + optional AuthMode mode = 1; + repeated bytes keys = 2; // root keys to trust + + enum AuthMode { + NONE = 0; // no authentication, anyone can publish + KEY = 1; // only messages signed by keys in the topic descriptor are accepted + WOT = 2; // web of trust, certificates can allow publisher set to grow + } + } + + message EncOpts { + optional EncMode mode = 1; + repeated bytes keyHashes = 2; // the hashes of the shared keys used (salted) + + enum EncMode { + NONE = 0; // no encryption, anyone can read + SHAREDKEY = 1; // messages are encrypted with shared key + WOT = 2; // web of trust, certificates can allow publisher set to grow + } + } +}` + +},{}],857:[function(require,module,exports){ 'use strict' const { multicodec: floodsubMulticodec } = require('libp2p-floodsub') @@ -107515,27 +82135,25 @@ class BasicPubSub extends Pubsub { module.exports = BasicPubSub -},{"./message":1012,"assert":78,"async/map":137,"async/nextTick":140,"err-code":1005,"libp2p-floodsub":1007,"libp2p-pubsub":1101,"multistream-select":1344,"pull-length-prefixed":1475,"pull-stream":1495}],1017:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1018,"_process":1438,"dup":247}],1018:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1021}],1019:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1020:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],1021:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1022:[function(require,module,exports){ -arguments[4][469][0].apply(exports,arguments) -},{"./utils":1026,"blakejs":168,"buffer":217,"dup":469}],1023:[function(require,module,exports){ -arguments[4][470][0].apply(exports,arguments) -},{"buffer":217,"dup":470,"nodeify":1384}],1024:[function(require,module,exports){ -arguments[4][471][0].apply(exports,arguments) -},{"./blake":1022,"./crypto-sha1-2":1023,"./utils":1026,"buffer":217,"dup":471,"js-sha3":1020,"murmurhash3js":1354}],1025:[function(require,module,exports){ -arguments[4][472][0].apply(exports,arguments) -},{"./crypto":1024,"buffer":217,"dup":472,"multihashes":1331}],1026:[function(require,module,exports){ -arguments[4][473][0].apply(exports,arguments) -},{"_process":1438,"buffer":217,"dup":473}],1027:[function(require,module,exports){ +},{"./message":854,"assert":26,"async/map":87,"async/nextTick":90,"err-code":847,"libp2p-floodsub":849,"libp2p-pubsub":937,"multistream-select":1169,"pull-length-prefixed":1292,"pull-stream":1311}],858:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":859,"_process":1258,"dup":208}],859:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],860:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],861:[function(require,module,exports){ +arguments[4][271][0].apply(exports,arguments) +},{"dup":271}],862:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./utils":866,"blakejs":132,"buffer":181,"dup":331}],863:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"buffer":181,"dup":332,"nodeify":1225}],864:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"./blake":862,"./crypto-sha1-2":863,"./utils":866,"buffer":181,"dup":333,"js-sha3":666,"murmurhash3js":1179}],865:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"./crypto":864,"buffer":181,"dup":334,"multihashes":1157}],866:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"_process":1258,"buffer":181,"dup":335}],867:[function(require,module,exports){ 'use strict'; const EventEmitter = require('eventemitter3'); @@ -107823,7 +82441,7 @@ module.exports = class PQueue extends EventEmitter { } }; -},{"eventemitter3":369}],1028:[function(require,module,exports){ +},{"eventemitter3":861}],868:[function(require,module,exports){ 'use strict' // MaxRecordAge specifies the maximum time that any node will hold onto a record @@ -107870,7 +82488,7 @@ exports.defaultRandomWalk = { delay: 10 * second } -},{}],1029:[function(require,module,exports){ +},{}],869:[function(require,module,exports){ 'use strict' const { EventEmitter } = require('events') @@ -108575,7 +83193,7 @@ class KadDHT extends EventEmitter { module.exports = KadDHT -},{"./constants":1028,"./message":1032,"./network":1033,"./private":1037,"./providers":1038,"./query":1040,"./query-manager":1039,"./random-walk":1044,"./routing":1045,"./utils":1054,"assert":78,"async/each":106,"async/filter":113,"async/timeout":150,"async/waterfall":152,"err-code":1019,"events":370,"interface-datastore":458,"libp2p-crypto":905,"libp2p-record":1109,"peer-id":1432,"peer-info":1433,"promise-to-callback":1441}],1030:[function(require,module,exports){ +},{"./constants":868,"./message":872,"./network":873,"./private":877,"./providers":878,"./query":880,"./query-manager":879,"./random-walk":884,"./routing":885,"./utils":894,"assert":26,"async/each":56,"async/filter":63,"async/timeout":100,"async/waterfall":102,"err-code":860,"events":272,"interface-datastore":322,"libp2p-crypto":745,"libp2p-record":945,"peer-id":1253,"peer-info":1254,"promise-to-callback":1261}],870:[function(require,module,exports){ 'use strict' const PeerList = require('./peer-list') @@ -108610,7 +83228,7 @@ class LimitedPeerList extends PeerList { module.exports = LimitedPeerList -},{"./peer-list":1035}],1031:[function(require,module,exports){ +},{"./peer-list":875}],871:[function(require,module,exports){ 'use strict' module.exports = `// can't use, because protocol-buffers doesn't support imports @@ -108688,7 +83306,7 @@ message Message { repeated Peer providerPeers = 9; }` -},{}],1032:[function(require,module,exports){ +},{}],872:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -108814,7 +83432,7 @@ function fromPbPeer (peer) { module.exports = Message }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) -},{"../../../is-buffer/index.js":766,"./dht.proto":1031,"assert":78,"libp2p-record":1109,"peer-id":1432,"peer-info":1433,"protons":1454}],1033:[function(require,module,exports){ +},{"../../../is-buffer/index.js":608,"./dht.proto":871,"assert":26,"libp2p-record":945,"peer-id":1253,"peer-info":1254,"protons":1274}],873:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -109058,7 +83676,7 @@ function writeReadMessage (conn, msg, callback) { module.exports = Network -},{"./constants":1028,"./message":1032,"./rpc":1053,"./utils":1054,"async/setImmediate":146,"async/timeout":150,"err-code":1019,"pull-length-prefixed":1475,"pull-stream":1495}],1034:[function(require,module,exports){ +},{"./constants":868,"./message":872,"./rpc":893,"./utils":894,"async/setImmediate":96,"async/timeout":100,"err-code":860,"pull-length-prefixed":1292,"pull-stream":1311}],874:[function(require,module,exports){ 'use strict' const distance = require('xor-distance') @@ -109161,7 +83779,7 @@ class PeerDistanceList { module.exports = PeerDistanceList -},{"./utils":1054,"async/map":137,"xor-distance":1857}],1035:[function(require,module,exports){ +},{"./utils":894,"async/map":87,"xor-distance":1526}],875:[function(require,module,exports){ 'use strict' /** @@ -109227,7 +83845,7 @@ class PeerList { module.exports = PeerList -},{}],1036:[function(require,module,exports){ +},{}],876:[function(require,module,exports){ 'use strict' const Heap = require('heap') @@ -109313,7 +83931,7 @@ class PeerQueue { module.exports = PeerQueue -},{"./utils":1054,"debug":1017,"heap":437,"promisify-es6":1443,"xor-distance":1857}],1037:[function(require,module,exports){ +},{"./utils":894,"debug":858,"heap":307,"promisify-es6":1263,"xor-distance":1526}],877:[function(require,module,exports){ 'use strict' const PeerId = require('peer-id') @@ -109920,7 +84538,7 @@ module.exports = (dht) => ({ } }) -},{"./constants":1028,"./limited-peer-list":1030,"./message":1032,"./query":1040,"./utils":1054,"async/timeout":150,"err-code":1019,"libp2p-record":1109,"peer-id":1432,"peer-info":1433,"promise-to-callback":1441,"promisify-es6":1443}],1038:[function(require,module,exports){ +},{"./constants":868,"./limited-peer-list":870,"./message":872,"./query":880,"./utils":894,"async/timeout":100,"err-code":860,"libp2p-record":945,"peer-id":1253,"peer-info":1254,"promise-to-callback":1261,"promisify-es6":1263}],878:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -110220,7 +84838,7 @@ function readTime (buf) { module.exports = Providers }).call(this,require("buffer").Buffer) -},{"./constants":1028,"./utils":1054,"buffer":217,"hashlru":436,"interface-datastore":458,"p-queue":1027,"peer-id":1432,"promisify-es6":1443,"pull-stream-to-async-iterator":1493,"varint":1785}],1039:[function(require,module,exports){ +},{"./constants":868,"./utils":894,"buffer":181,"hashlru":306,"interface-datastore":322,"p-queue":867,"peer-id":1253,"promisify-es6":1263,"pull-stream-to-async-iterator":1309,"varint":1521}],879:[function(require,module,exports){ 'use strict' /** @@ -110274,7 +84892,7 @@ class QueryManager { module.exports = QueryManager -},{}],1040:[function(require,module,exports){ +},{}],880:[function(require,module,exports){ 'use strict' const mh = require('multihashes') @@ -110393,7 +85011,7 @@ class Query { module.exports = Query -},{"../utils":1054,"./run":1042,"multihashes":1331}],1041:[function(require,module,exports){ +},{"../utils":894,"./run":882,"multihashes":1157}],881:[function(require,module,exports){ 'use strict' const PeerQueue = require('../peer-queue') @@ -110480,7 +85098,7 @@ class Path { module.exports = Path -},{"../peer-queue":1036,"../utils":1054}],1042:[function(require,module,exports){ +},{"../peer-queue":876,"../utils":894}],882:[function(require,module,exports){ 'use strict' const PeerDistanceList = require('../peer-distance-list') @@ -110685,7 +85303,7 @@ class Run extends EventEmitter { module.exports = Run -},{"../peer-distance-list":1034,"../utils":1054,"./path":1041,"./workerQueue":1043,"events":370,"promisify-es6":1443}],1043:[function(require,module,exports){ +},{"../peer-distance-list":874,"../utils":894,"./path":881,"./workerQueue":883,"events":272,"promisify-es6":1263}],883:[function(require,module,exports){ 'use strict' const queue = require('async/queue') @@ -110943,7 +85561,7 @@ class WorkerQueue { module.exports = WorkerQueue -},{"async/queue":142,"promise-to-callback":1441,"promisify-es6":1443}],1044:[function(require,module,exports){ +},{"async/queue":92,"promise-to-callback":1261,"promisify-es6":1263}],884:[function(require,module,exports){ 'use strict' const promisify = require('promisify-es6') @@ -111124,7 +85742,7 @@ class RandomWalk { module.exports = RandomWalk -},{"./constants":1028,"./utils":1054,"abort-controller":2,"assert":78,"err-code":1019,"libp2p-crypto":905,"multihashing-async":1025,"p-times":1405,"peer-id":1432,"promisify-es6":1443}],1045:[function(require,module,exports){ +},{"./constants":868,"./utils":894,"abort-controller":2,"assert":26,"err-code":860,"libp2p-crypto":745,"multihashing-async":865,"p-times":1238,"peer-id":1253,"promisify-es6":1263}],885:[function(require,module,exports){ 'use strict' const KBucket = require('k-bucket') @@ -111279,7 +85897,7 @@ class RoutingTable { module.exports = RoutingTable -},{"./utils":1054,"k-bucket":832}],1046:[function(require,module,exports){ +},{"./utils":894,"k-bucket":670}],886:[function(require,module,exports){ 'use strict' const CID = require('cids') @@ -111348,7 +85966,7 @@ module.exports = (dht) => { } } -},{"../../utils":1054,"cids":222,"err-code":1019,"promise-to-callback":1441}],1047:[function(require,module,exports){ +},{"../../utils":894,"cids":185,"err-code":860,"promise-to-callback":1261}],887:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -111395,7 +86013,7 @@ module.exports = (dht) => { } }).call(this,require("buffer").Buffer) -},{"../../message":1032,"../../utils":1054,"async/waterfall":152,"buffer":217}],1048:[function(require,module,exports){ +},{"../../message":872,"../../utils":894,"async/waterfall":102,"buffer":181}],888:[function(require,module,exports){ 'use strict' const CID = require('cids') @@ -111476,7 +86094,7 @@ module.exports = (dht) => { } } -},{"../../message":1032,"../../utils":1054,"async/parallel":141,"cids":222,"err-code":1019,"peer-info":1433,"promise-to-callback":1441}],1049:[function(require,module,exports){ +},{"../../message":872,"../../utils":894,"async/parallel":91,"cids":185,"err-code":860,"peer-info":1254,"promise-to-callback":1261}],889:[function(require,module,exports){ 'use strict' const parallel = require('async/parallel') @@ -111553,7 +86171,7 @@ module.exports = (dht) => { } } -},{"../../message":1032,"../../utils":1054,"async/parallel":141,"err-code":1019,"libp2p-record":1109}],1050:[function(require,module,exports){ +},{"../../message":872,"../../utils":894,"async/parallel":91,"err-code":860,"libp2p-record":945}],890:[function(require,module,exports){ 'use strict' const T = require('../../message').TYPES @@ -111582,7 +86200,7 @@ module.exports = (dht) => { } } -},{"../../message":1032,"./add-provider":1046,"./find-node":1047,"./get-providers":1048,"./get-value":1049,"./ping":1051,"./put-value":1052}],1051:[function(require,module,exports){ +},{"../../message":872,"./add-provider":886,"./find-node":887,"./get-providers":888,"./get-value":889,"./ping":891,"./put-value":892}],891:[function(require,module,exports){ 'use strict' const utils = require('../../utils') @@ -111604,7 +86222,7 @@ module.exports = (dht) => { } } -},{"../../utils":1054}],1052:[function(require,module,exports){ +},{"../../utils":894}],892:[function(require,module,exports){ 'use strict' const utils = require('../../utils') @@ -111655,7 +86273,7 @@ module.exports = (dht) => { } } -},{"../../utils":1054,"err-code":1019}],1053:[function(require,module,exports){ +},{"../../utils":894,"err-code":860}],893:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -111754,7 +86372,7 @@ module.exports = (dht) => { } } -},{"../constants":1028,"../message":1032,"../utils":1054,"./handlers":1050,"pull-length-prefixed":1475,"pull-stream":1495}],1054:[function(require,module,exports){ +},{"../constants":868,"../message":872,"../utils":894,"./handlers":890,"pull-length-prefixed":1292,"pull-stream":1311}],894:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -111980,9 +86598,9 @@ exports.withTimeout = (asyncFn, time) => { } }).call(this,require("buffer").Buffer) -},{"async/map":137,"async/setImmediate":146,"base32.js":160,"buffer":217,"debug":1017,"err-code":1019,"interface-datastore":458,"libp2p-record":1109,"multihashes":1331,"multihashing-async":1025,"peer-id":1432,"xor-distance":1857}],1055:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1056:[function(require,module,exports){ +},{"async/map":87,"async/setImmediate":96,"base32.js":107,"buffer":181,"debug":858,"err-code":860,"interface-datastore":322,"libp2p-record":945,"multihashes":1157,"multihashing-async":865,"peer-id":1253,"xor-distance":1526}],895:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],896:[function(require,module,exports){ /** * Advanced Encryption Standard (AES) implementation. * @@ -113075,7 +87693,7 @@ function _createCipher(options) { return cipher; } -},{"./cipher":1059,"./cipherModes":1060,"./forge":1062,"./util":1083}],1057:[function(require,module,exports){ +},{"./cipher":899,"./cipherModes":900,"./forge":902,"./util":923}],897:[function(require,module,exports){ /** * Javascript implementation of Abstract Syntax Notation Number One. * @@ -114485,7 +89103,7 @@ asn1.prettyPrint = function(obj, level, indentation) { return rval; }; -},{"./forge":1062,"./oids":1068,"./util":1083}],1058:[function(require,module,exports){ +},{"./forge":902,"./oids":908,"./util":923}],898:[function(require,module,exports){ (function (Buffer){ /** * Base-N/Base-X encoding/decoding functions. @@ -114675,7 +89293,7 @@ function _encodeWithByteBuffer(input, alphabet) { } }).call(this,require("buffer").Buffer) -},{"buffer":182}],1059:[function(require,module,exports){ +},{"buffer":146}],899:[function(require,module,exports){ /** * Cipher base API. * @@ -114907,7 +89525,7 @@ BlockCipher.prototype.finish = function(pad) { return true; }; -},{"./forge":1062,"./util":1083}],1060:[function(require,module,exports){ +},{"./forge":902,"./util":923}],900:[function(require,module,exports){ /** * Supported cipher modes. * @@ -115896,7 +90514,7 @@ function from64To32(num) { return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; } -},{"./forge":1062,"./util":1083}],1061:[function(require,module,exports){ +},{"./forge":902,"./util":923}],901:[function(require,module,exports){ /** * DES (Data Encryption Standard) implementation. * @@ -116393,7 +91011,7 @@ function _createCipher(options) { return cipher; } -},{"./cipher":1059,"./cipherModes":1060,"./forge":1062,"./util":1083}],1062:[function(require,module,exports){ +},{"./cipher":899,"./cipherModes":900,"./forge":902,"./util":923}],902:[function(require,module,exports){ /** * Node.js module for Forge. * @@ -116408,7 +91026,7 @@ module.exports = { } }; -},{}],1063:[function(require,module,exports){ +},{}],903:[function(require,module,exports){ /** * Hash-based Message Authentication Code implementation. Requires a message * digest object that can be obtained, for example, from forge.md.sha1 or @@ -116556,7 +91174,7 @@ hmac.create = function() { return ctx; }; -},{"./forge":1062,"./md":1065,"./util":1083}],1064:[function(require,module,exports){ +},{"./forge":902,"./md":905,"./util":923}],904:[function(require,module,exports){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. @@ -117822,7 +92440,7 @@ BigInteger.prototype.isProbablePrime = bnIsProbablePrime; //long longValue() //static BigInteger valueOf(long val) -},{"./forge":1062}],1065:[function(require,module,exports){ +},{"./forge":902}],905:[function(require,module,exports){ /** * Node.js module for Forge message digests. * @@ -117835,7 +92453,7 @@ var forge = require('./forge'); module.exports = forge.md = forge.md || {}; forge.md.algorithms = forge.md.algorithms || {}; -},{"./forge":1062}],1066:[function(require,module,exports){ +},{"./forge":902}],906:[function(require,module,exports){ /** * Node.js module for Forge mask generation functions. * @@ -117849,7 +92467,7 @@ require('./mgf1'); module.exports = forge.mgf = forge.mgf || {}; forge.mgf.mgf1 = forge.mgf1; -},{"./forge":1062,"./mgf1":1067}],1067:[function(require,module,exports){ +},{"./forge":902,"./mgf1":907}],907:[function(require,module,exports){ /** * Javascript implementation of mask generation function MGF1. * @@ -117908,7 +92526,7 @@ mgf1.create = function(md) { return mgf; }; -},{"./forge":1062,"./util":1083}],1068:[function(require,module,exports){ +},{"./forge":902,"./util":923}],908:[function(require,module,exports){ /** * Object IDs for ASN.1. * @@ -118071,7 +92689,7 @@ _IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); _IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); _IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); -},{"./forge":1062}],1069:[function(require,module,exports){ +},{"./forge":902}],909:[function(require,module,exports){ /** * Password-based encryption functions. * @@ -119096,7 +93714,7 @@ function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { return params; } -},{"./aes":1056,"./asn1":1057,"./des":1061,"./forge":1062,"./md":1065,"./oids":1068,"./pbkdf2":1070,"./pem":1071,"./random":1078,"./rc2":1079,"./rsa":1080,"./util":1083}],1070:[function(require,module,exports){ +},{"./aes":896,"./asn1":897,"./des":901,"./forge":902,"./md":905,"./oids":908,"./pbkdf2":910,"./pem":911,"./random":918,"./rc2":919,"./rsa":920,"./util":923}],910:[function(require,module,exports){ (function (Buffer){ /** * Password-Based Key-Derivation Function #2 implementation. @@ -119311,7 +93929,7 @@ module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( }; }).call(this,require("buffer").Buffer) -},{"./forge":1062,"./hmac":1063,"./md":1065,"./util":1083,"buffer":182,"crypto":182}],1071:[function(require,module,exports){ +},{"./forge":902,"./hmac":903,"./md":905,"./util":923,"buffer":146,"crypto":146}],911:[function(require,module,exports){ /** * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. * @@ -119543,7 +94161,7 @@ function ltrim(str) { return str.replace(/^\s+/, ''); } -},{"./forge":1062,"./util":1083}],1072:[function(require,module,exports){ +},{"./forge":902,"./util":923}],912:[function(require,module,exports){ /** * Partial implementation of PKCS#1 v2.2: RSA-OEAP * @@ -119821,7 +94439,7 @@ function rsa_mgf1(seed, maskLength, hash) { return t.substring(0, maskLength); } -},{"./forge":1062,"./random":1078,"./sha1":1081,"./util":1083}],1073:[function(require,module,exports){ +},{"./forge":902,"./random":918,"./sha1":921,"./util":923}],913:[function(require,module,exports){ /** * Javascript implementation of PKCS#7 v1.5. * @@ -121080,7 +95698,7 @@ function _decryptContent(msg) { } } -},{"./aes":1056,"./asn1":1057,"./des":1061,"./forge":1062,"./oids":1068,"./pem":1071,"./pkcs7asn1":1074,"./random":1078,"./util":1083,"./x509":1084}],1074:[function(require,module,exports){ +},{"./aes":896,"./asn1":897,"./des":901,"./forge":902,"./oids":908,"./pem":911,"./pkcs7asn1":914,"./random":918,"./util":923,"./x509":924}],914:[function(require,module,exports){ /** * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. * @@ -121491,7 +96109,7 @@ p7v.recipientInfoValidator = { }] }; -},{"./asn1":1057,"./forge":1062,"./util":1083}],1075:[function(require,module,exports){ +},{"./asn1":897,"./forge":902,"./util":923}],915:[function(require,module,exports){ /** * Prime number generation API. * @@ -121790,7 +96408,7 @@ function getMillerRabinTests(bits) { })(); -},{"./forge":1062,"./jsbn":1064,"./random":1078,"./util":1083}],1076:[function(require,module,exports){ +},{"./forge":902,"./jsbn":904,"./random":918,"./util":923}],916:[function(require,module,exports){ (function (process){ /** * A javascript implementation of a cryptographically-secure @@ -122214,7 +96832,7 @@ prng.create = function(plugin) { }; }).call(this,require('_process')) -},{"./forge":1062,"./util":1083,"_process":1438,"crypto":182}],1077:[function(require,module,exports){ +},{"./forge":902,"./util":923,"_process":1258,"crypto":146}],917:[function(require,module,exports){ /** * Javascript implementation of PKCS#1 PSS signature padding. * @@ -122457,7 +97075,7 @@ pss.create = function(options) { return pssobj; }; -},{"./forge":1062,"./random":1078,"./util":1083}],1078:[function(require,module,exports){ +},{"./forge":902,"./random":918,"./util":923}],918:[function(require,module,exports){ /** * An API for getting cryptographically-secure random bytes. The bytes are * generated using the Fortuna algorithm devised by Bruce Schneier and @@ -122650,7 +97268,7 @@ module.exports = forge.random; })(); -},{"./aes":1056,"./forge":1062,"./prng":1076,"./sha256":1082,"./util":1083}],1079:[function(require,module,exports){ +},{"./aes":896,"./forge":902,"./prng":916,"./sha256":922,"./util":923}],919:[function(require,module,exports){ /** * RC2 implementation. * @@ -123062,7 +97680,7 @@ forge.rc2.createDecryptionCipher = function(key, bits) { return createCipher(key, bits, false); }; -},{"./forge":1062,"./util":1083}],1080:[function(require,module,exports){ +},{"./forge":902,"./util":923}],920:[function(require,module,exports){ /** * Javascript implementation of basic RSA algorithms. * @@ -124860,7 +99478,7 @@ function _base64ToBigInt(b64) { return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); } -},{"./asn1":1057,"./forge":1062,"./jsbn":1064,"./oids":1068,"./pkcs1":1072,"./prime":1075,"./random":1078,"./util":1083}],1081:[function(require,module,exports){ +},{"./asn1":897,"./forge":902,"./jsbn":904,"./oids":908,"./pkcs1":912,"./prime":915,"./random":918,"./util":923}],921:[function(require,module,exports){ /** * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. * @@ -125181,7 +99799,7 @@ function _update(s, w, bytes) { } } -},{"./forge":1062,"./md":1065,"./util":1083}],1082:[function(require,module,exports){ +},{"./forge":902,"./md":905,"./util":923}],922:[function(require,module,exports){ /** * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. * @@ -125510,7 +100128,7 @@ function _update(s, w, bytes) { } } -},{"./forge":1062,"./md":1065,"./util":1083}],1083:[function(require,module,exports){ +},{"./forge":902,"./md":905,"./util":923}],923:[function(require,module,exports){ (function (process,Buffer,setImmediate){ /** * Utility functions for web applications. @@ -128494,7 +103112,7 @@ util.estimateCores = function(options, callback) { }; }).call(this,require('_process'),require("buffer").Buffer,require("timers").setImmediate) -},{"./baseN":1058,"./forge":1062,"_process":1438,"buffer":182,"timers":1749}],1084:[function(require,module,exports){ +},{"./baseN":898,"./forge":902,"_process":1258,"buffer":146,"timers":1500}],924:[function(require,module,exports){ /** * Javascript implementation of X.509 and related components (such as * Certification Signing Requests) of a Public Key Infrastructure. @@ -131767,7 +106385,7 @@ pki.verifyCertificateChain = function(caStore, chain, verify) { return true; }; -},{"./aes":1056,"./asn1":1057,"./des":1061,"./forge":1062,"./md":1065,"./mgf":1066,"./oids":1068,"./pem":1071,"./pss":1077,"./rsa":1080,"./util":1083}],1085:[function(require,module,exports){ +},{"./aes":896,"./asn1":897,"./des":901,"./forge":902,"./md":905,"./mgf":906,"./oids":908,"./pem":911,"./pss":917,"./rsa":920,"./util":923}],925:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -131920,12 +106538,12 @@ class CMS { module.exports = CMS }).call(this,require("buffer").Buffer) -},{"./util":1088,"async/detect":104,"async/series":145,"async/setImmediate":146,"async/waterfall":152,"buffer":217,"err-code":1055,"node-forge/lib/forge":1062,"node-forge/lib/pbe":1069,"node-forge/lib/pkcs7":1073}],1086:[function(require,module,exports){ +},{"./util":928,"async/detect":54,"async/series":95,"async/setImmediate":96,"async/waterfall":102,"buffer":181,"err-code":895,"node-forge/lib/forge":902,"node-forge/lib/pbe":909,"node-forge/lib/pkcs7":913}],926:[function(require,module,exports){ 'use strict' module.exports = require('./keychain') -},{"./keychain":1087}],1087:[function(require,module,exports){ +},{"./keychain":927}],927:[function(require,module,exports){ /* eslint max-nested-callbacks: ["error", 5] */ 'use strict' @@ -132426,7 +107044,7 @@ class Keychain { module.exports = Keychain -},{"./cms":1085,"err-code":1055,"interface-datastore":458,"libp2p-crypto":905,"merge-options":1298,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"sanitize-filename":1595}],1088:[function(require,module,exports){ +},{"./cms":925,"err-code":895,"interface-datastore":322,"libp2p-crypto":745,"merge-options":1127,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"sanitize-filename":1372}],928:[function(require,module,exports){ 'use strict' require('node-forge/lib/x509') @@ -132499,444 +107117,7 @@ exports.certificateForKey = (key, privateKey, callback) => { return callback(null, cert) } -},{"node-forge/lib/forge":1062,"node-forge/lib/x509":1084}],1089:[function(require,module,exports){ -(function (process){ -"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); } - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -/** - * Colors. - */ - -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']; -/** - * 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 - */ -// eslint-disable-next-line complexity - -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' || window.process.__nwjs)) { - 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; - } // 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+)/); -} -/** - * Colorize log arguments if enabled. - * - * @api public - */ - - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); - - if (!this.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 - - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function (match) { - if (match === '%%') { - return; - } - - index++; - - if (match === '%c') { - // 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 - */ - - -function log() { - var _console; - - // This hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments); -} -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - - -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) {// Swallow - // XXX (@Qix-) should we be logging these? - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - - -function load() { - var r; - - try { - r = exports.storage.getItem('debug'); - } catch (error) {} // Swallow - // XXX (@Qix-) should we be logging these? - // 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; - } - - return r; -} -/** - * 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 { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) {// Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = require('./common')(exports); -var formatters = module.exports.formatters; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -}).call(this,require('_process')) -},{"./common":1090,"_process":1438}],1090:[function(require,module,exports){ -"use strict"; - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require('ms'); - Object.keys(env).forEach(function (key) { - createDebug[key] = env[key]; - }); - /** - * Active `debug` instances. - */ - - createDebug.instances = []; - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.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". - */ - - createDebug.formatters = {}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - - function selectColor(namespace) { - var hash = 0; - - for (var i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - - function createDebug(namespace) { - var prevTime; - - function debug() { - // Disabled? - if (!debug.enabled) { - return; - } - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var self = debug; // Set `diff` timestamp - - var curr = Number(new Date()); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } // 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 = createDebug.formatters[format]; - - if (typeof formatter === 'function') { - var val = args[index]; - match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` - - args.splice(index, 1); - index--; - } - - return match; - }); // Apply env-specific formatting (colors, etc.) - - createDebug.formatArgs.call(self, args); - var logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = createDebug.enabled(namespace); - debug.useColors = createDebug.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - debug.extend = extend; // Debug.formatArgs = formatArgs; - // debug.rawLog = rawLog; - // env-specific initialization logic for debug instances - - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - createDebug.instances.push(debug); - return debug; - } - - function destroy() { - var index = createDebug.instances.indexOf(this); - - if (index !== -1) { - createDebug.instances.splice(index, 1); - return true; - } - - return false; - } - - function extend(namespace, delimiter) { - return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - - - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.names = []; - createDebug.skips = []; - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - - for (i = 0; i < createDebug.instances.length; i++) { - var instance = createDebug.instances[i]; - instance.enabled = createDebug.enabled(instance.namespace); - } - } - /** - * Disable debug output. - * - * @api public - */ - - - function disable() { - createDebug.enable(''); - } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - - - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - var i; - var len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - - - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - - return val; - } - - createDebug.enable(createDebug.load()); - return createDebug; -} - -module.exports = setup; - - -},{"ms":1091}],1091:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1092:[function(require,module,exports){ +},{"node-forge/lib/forge":902,"node-forge/lib/x509":924}],929:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -133038,7 +107219,7 @@ function ensureBuffer () { } }).call(this,require("buffer").Buffer) -},{"./errors":1093,"./key-generator":1095,"buffer":217,"debug":1089,"pull-stream":1495,"xsalsa20":1858}],1093:[function(require,module,exports){ +},{"./errors":930,"./key-generator":932,"buffer":181,"debug":213,"pull-stream":1311,"xsalsa20":1527}],930:[function(require,module,exports){ 'use strict' module.exports.INVALID_PEER = 'Not a valid peer connection' @@ -133047,7 +107228,7 @@ module.exports.NO_LOCAL_ID = 'No local private key provided' module.exports.NO_HANDSHAKE_CONNECTION = 'No connection for the handshake provided' module.exports.STREAM_ENDED = 'Stream ended prematurely' -},{}],1094:[function(require,module,exports){ +},{}],931:[function(require,module,exports){ 'use strict' const pull = require('pull-stream') @@ -133119,7 +107300,7 @@ module.exports = Protector module.exports.errors = Errors module.exports.generate = require('./key-generator') -},{"./crypto":1092,"./errors":1093,"./key-generator":1095,"./state":1096,"assert":78,"debug":1089,"interface-connection":455,"pull-stream":1495}],1095:[function(require,module,exports){ +},{"./crypto":929,"./errors":930,"./key-generator":932,"./state":933,"assert":26,"debug":213,"interface-connection":319,"pull-stream":1311}],932:[function(require,module,exports){ (function (process){ 'use strict' @@ -133145,7 +107326,7 @@ if (require.main === module) { } }).call(this,require('_process')) -},{"_process":1438,"crypto":236}],1096:[function(require,module,exports){ +},{"_process":1258,"crypto":197}],933:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -133259,15 +107440,13 @@ class State { module.exports = State }).call(this,require("buffer").Buffer) -},{"./crypto":1092,"./key-generator":1095,"buffer":217,"crypto":236,"debug":1089,"pull-cat":1465,"pull-defer":1467,"pull-pair":1489,"pull-reader":1491,"pull-stream":1495}],1097:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1098,"_process":1438,"dup":247}],1098:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1100}],1099:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1100:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1101:[function(require,module,exports){ +},{"./crypto":929,"./key-generator":932,"buffer":181,"crypto":197,"debug":213,"pull-cat":1283,"pull-defer":1285,"pull-pair":1305,"pull-reader":1307,"pull-stream":1311}],934:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":935,"_process":1258,"dup":208}],935:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],936:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],937:[function(require,module,exports){ 'use strict' const EventEmitter = require('events') @@ -133661,7 +107840,7 @@ module.exports = PubsubBaseProtocol module.exports.message = message module.exports.utils = utils -},{"./message":1102,"./message/sign":1104,"./peer":1106,"./utils":1107,"async/each":106,"async/nextTick":140,"debug":1097,"err-code":1099,"events":370,"pull-stream/pull":1496,"pull-stream/sources/empty":1506,"time-cache":1748}],1102:[function(require,module,exports){ +},{"./message":938,"./message/sign":940,"./peer":942,"./utils":943,"async/each":56,"async/nextTick":90,"debug":934,"err-code":936,"events":272,"pull-stream/pull":1312,"pull-stream/sources/empty":1322,"time-cache":1499}],938:[function(require,module,exports){ 'use strict' const protons = require('protons') @@ -133677,7 +107856,7 @@ exports.RPC = RPC exports.Message = RPC.Message exports.SubOpts = RPC.SubOpts -},{"./rpc.proto.js":1103,"./topic-descriptor.proto.js":1105,"protons":1454}],1103:[function(require,module,exports){ +},{"./rpc.proto.js":939,"./topic-descriptor.proto.js":941,"protons":1274}],939:[function(require,module,exports){ 'use strict' module.exports = ` message RPC { @@ -133699,7 +107878,7 @@ message RPC { } }` -},{}],1104:[function(require,module,exports){ +},{}],940:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -133794,7 +107973,7 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"./index":1102,"buffer":217,"peer-id":1432}],1105:[function(require,module,exports){ +},{"./index":938,"buffer":181,"peer-id":1253}],941:[function(require,module,exports){ 'use strict' module.exports = ` // topicCID = cid(merkledag_protobuf(topicDescriptor)); (not the topic.name) @@ -133826,7 +108005,7 @@ message TopicDescriptor { } }` -},{}],1106:[function(require,module,exports){ +},{}],942:[function(require,module,exports){ 'use strict' const lp = require('pull-length-prefixed') @@ -134015,7 +108194,7 @@ class Peer extends EventEmitter { module.exports = Peer -},{"./message":1102,"async/setImmediate":146,"events":370,"pull-length-prefixed":1475,"pull-pushable":1490,"pull-stream":1495}],1107:[function(require,module,exports){ +},{"./message":938,"async/setImmediate":96,"events":272,"pull-length-prefixed":1292,"pull-pushable":1306,"pull-stream":1311}],943:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134129,9 +108308,9 @@ exports.normalizeOutRpcMessages = (messages) => { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"bs58":213,"libp2p-crypto":905}],1108:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1109:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"bs58":177,"libp2p-crypto":745}],944:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],945:[function(require,module,exports){ 'use strict' module.exports = { @@ -134140,7 +108319,7 @@ module.exports = { selection: require('./selection') } -},{"./record":1110,"./selection":1112,"./validator":1116}],1110:[function(require,module,exports){ +},{"./record":946,"./selection":948,"./validator":952}],946:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134224,7 +108403,7 @@ class Record { module.exports = Record }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./record.proto":1111,"./utils":1115,"assert":78,"protons":1454}],1111:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"./record.proto":947,"./utils":951,"assert":26,"protons":1274}],947:[function(require,module,exports){ 'use strict' module.exports = `// Record represents a dht record that contains a value // for a key value pair @@ -134245,7 +108424,7 @@ message Record { optional string timeReceived = 5; }` -},{}],1112:[function(require,module,exports){ +},{}],948:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134292,14 +108471,14 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"./selectors":1113,"buffer":217,"buffer-split":214,"err-code":1108}],1113:[function(require,module,exports){ +},{"./selectors":949,"buffer":181,"buffer-split":178,"err-code":944}],949:[function(require,module,exports){ 'use strict' module.exports = { pk: require('./public-key') } -},{"./public-key":1114}],1114:[function(require,module,exports){ +},{"./public-key":950}],950:[function(require,module,exports){ 'use strict' /** @@ -134317,9 +108496,9 @@ const publicKeySelector = (k, records) => { module.exports = publicKeySelector -},{}],1115:[function(require,module,exports){ -arguments[4][765][0].apply(exports,arguments) -},{"dup":765}],1116:[function(require,module,exports){ +},{}],951:[function(require,module,exports){ +arguments[4][607][0].apply(exports,arguments) +},{"dup":607}],952:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134361,9 +108540,9 @@ module.exports = { } }).call(this,require("buffer").Buffer) -},{"./validators":1117,"buffer":217,"buffer-split":214,"err-code":1108}],1117:[function(require,module,exports){ -arguments[4][1113][0].apply(exports,arguments) -},{"./public-key":1118,"dup":1113}],1118:[function(require,module,exports){ +},{"./validators":953,"buffer":181,"buffer-split":178,"err-code":944}],953:[function(require,module,exports){ +arguments[4][949][0].apply(exports,arguments) +},{"./public-key":954,"dup":949}],954:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134418,25 +108597,21 @@ module.exports = { } }).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) -},{"../../../is-buffer/index.js":766,"async/setImmediate":146,"multihashing-async":1336}],1119:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1120,"_process":1438,"dup":247}],1120:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1122}],1121:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],1122:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1123:[function(require,module,exports){ -arguments[4][469][0].apply(exports,arguments) -},{"./utils":1127,"blakejs":168,"buffer":217,"dup":469}],1124:[function(require,module,exports){ -arguments[4][470][0].apply(exports,arguments) -},{"buffer":217,"dup":470,"nodeify":1384}],1125:[function(require,module,exports){ -arguments[4][471][0].apply(exports,arguments) -},{"./blake":1123,"./crypto-sha1-2":1124,"./utils":1127,"buffer":217,"dup":471,"js-sha3":1121,"murmurhash3js":1354}],1126:[function(require,module,exports){ -arguments[4][472][0].apply(exports,arguments) -},{"./crypto":1125,"buffer":217,"dup":472,"multihashes":1331}],1127:[function(require,module,exports){ -arguments[4][473][0].apply(exports,arguments) -},{"_process":1438,"buffer":217,"dup":473}],1128:[function(require,module,exports){ +},{"../../../is-buffer/index.js":608,"async/setImmediate":96,"multihashing-async":1161}],955:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":956,"_process":1258,"dup":208}],956:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],957:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./utils":961,"blakejs":132,"buffer":181,"dup":331}],958:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"buffer":181,"dup":332,"nodeify":1225}],959:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"./blake":957,"./crypto-sha1-2":958,"./utils":961,"buffer":181,"dup":333,"js-sha3":666,"murmurhash3js":1179}],960:[function(require,module,exports){ +arguments[4][334][0].apply(exports,arguments) +},{"./crypto":959,"buffer":181,"dup":334,"multihashes":1157}],961:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"_process":1258,"buffer":181,"dup":335}],962:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134521,7 +108696,7 @@ function ensureBuffer () { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/throughs/async-map":1513,"pull-stream/throughs/map":1518}],1129:[function(require,module,exports){ +},{"buffer":181,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/throughs/async-map":1329,"pull-stream/throughs/map":1334}],963:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -134731,7 +108906,7 @@ exports.verifyNonce = (state, n2) => { } }).call(this,require("buffer").Buffer) -},{"../support":1137,"./secio.proto":1134,"async/parallel":141,"async/waterfall":152,"buffer":217,"debug":1119,"libp2p-crypto":905,"peer-id":1432,"protons":1454}],1130:[function(require,module,exports){ +},{"../support":971,"./secio.proto":968,"async/parallel":91,"async/waterfall":102,"buffer":181,"debug":955,"libp2p-crypto":745,"peer-id":1253,"protons":1274}],964:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -134768,7 +108943,7 @@ module.exports = function exchange (state, callback) { }) } -},{"../support":1137,"./crypto":1129,"async/waterfall":152,"debug":1119}],1131:[function(require,module,exports){ +},{"../support":971,"./crypto":963,"async/waterfall":102,"debug":955}],965:[function(require,module,exports){ 'use strict' const pull = require('pull-stream/pull') @@ -134831,7 +109006,7 @@ module.exports = function finish (state, callback) { }) } -},{"../etm":1128,"./crypto":1129,"debug":1119,"pull-handshake":1472,"pull-stream/pull":1496,"pull-stream/sources/error":1507}],1132:[function(require,module,exports){ +},{"../etm":962,"./crypto":963,"debug":955,"pull-handshake":1289,"pull-stream/pull":1312,"pull-stream/sources/error":1323}],966:[function(require,module,exports){ 'use strict' const series = require('async/series') @@ -134864,7 +109039,7 @@ module.exports = function handshake (state, callback) { return state.stream } -},{"./exchange":1130,"./finish":1131,"./propose":1133,"async/series":145}],1133:[function(require,module,exports){ +},{"./exchange":964,"./finish":965,"./propose":967,"async/series":95}],967:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -134901,7 +109076,7 @@ module.exports = function propose (state, callback) { }) } -},{"../support":1137,"./crypto":1129,"async/waterfall":152,"debug":1119}],1134:[function(require,module,exports){ +},{"../support":971,"./crypto":963,"async/waterfall":102,"debug":955}],968:[function(require,module,exports){ 'use strict' module.exports = `message Propose { @@ -134917,7 +109092,7 @@ message Exchange { optional bytes signature = 2; }` -},{}],1135:[function(require,module,exports){ +},{}],969:[function(require,module,exports){ 'use strict' const pull = require('pull-stream/pull') @@ -134977,7 +109152,7 @@ module.exports = { } } -},{"./handshake":1132,"./state":1136,"assert":78,"debug":1119,"interface-connection":455,"once":1394,"peer-info":1433,"pull-stream/pull":1496}],1136:[function(require,module,exports){ +},{"./handshake":966,"./state":970,"assert":26,"debug":955,"interface-connection":319,"once":1228,"peer-info":1254,"pull-stream/pull":1312}],970:[function(require,module,exports){ 'use strict' const handshake = require('pull-handshake') @@ -135026,7 +109201,7 @@ class State { module.exports = State -},{"pull-defer":1467,"pull-handshake":1472}],1137:[function(require,module,exports){ +},{"pull-defer":1285,"pull-handshake":1289}],971:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -135165,13 +109340,11 @@ exports.read = function read (reader, cb) { } }).call(this,require("buffer").Buffer) -},{"async/parallel":141,"buffer":217,"libp2p-crypto":905,"multihashing-async":1126,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"pull-stream/sources/values":1512}],1138:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1139,"_process":1438,"dup":247}],1139:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1140}],1140:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1141:[function(require,module,exports){ +},{"async/parallel":91,"buffer":181,"libp2p-crypto":745,"multihashing-async":960,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"pull-stream/sources/values":1328}],972:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":973,"_process":1258,"dup":208}],973:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],974:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -135434,7 +109607,7 @@ class WebRTCStar { module.exports = withIs(WebRTCStar, { className: 'WebRTCStar', symbolName: '@libp2p/js-libp2p-webrtc-star/webrtcstar' }) -},{"./utils":1142,"async/setImmediate":146,"class-is":224,"debug":1138,"events":370,"interface-connection":455,"mafmt":1296,"multiaddr":1314,"once":1394,"peer-id":1432,"peer-info":1433,"simple-peer":1633,"socket.io-client":1652,"stream-to-pull-stream":1735,"webrtcsupport":1840}],1142:[function(require,module,exports){ +},{"./utils":975,"async/setImmediate":96,"class-is":187,"debug":972,"events":272,"interface-connection":319,"mafmt":1125,"multiaddr":1140,"once":1228,"peer-id":1253,"peer-info":1254,"simple-peer":1403,"socket.io-client":1423,"stream-to-pull-stream":1497,"webrtcsupport":1524}],975:[function(require,module,exports){ 'use strict' const multiaddr = require('multiaddr') @@ -135485,13 +109658,11 @@ exports = module.exports exports.cleanUrlSIO = cleanUrlSIO exports.cleanMultiaddr = cleanMultiaddr -},{"multiaddr":1314}],1143:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1144,"_process":1438,"dup":247}],1144:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1145}],1145:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1146:[function(require,module,exports){ +},{"multiaddr":1140}],976:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":977,"_process":1258,"dup":208}],977:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],978:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -135578,18 +109749,16 @@ class WebsocketStarMulti { // listen on multiple websocket star servers without module.exports = WebsocketStarMulti -},{"async/map":137,"async/parallel":141,"debug":1143,"events":370,"libp2p-websocket-star":1151,"mafmt":1296,"multiaddr":1314,"once":1394}],1147:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1148,"_process":1438,"dup":247}],1148:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1149}],1149:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1150:[function(require,module,exports){ +},{"async/map":87,"async/parallel":91,"debug":976,"events":272,"libp2p-websocket-star":982,"mafmt":1125,"multiaddr":1140,"once":1228}],979:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":980,"_process":1258,"dup":208}],980:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],981:[function(require,module,exports){ 'use strict' exports.ERR_WS_STAR_WEBSOCKET_CONNECTION = 'ERR_WS_STAR_WEBSOCKET_CONNECTION' -},{}],1151:[function(require,module,exports){ +},{}],982:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -135727,7 +109896,7 @@ class WebsocketStar { module.exports = withIs(WebsocketStar, { className: 'WebsocketStar', symbolName: '@libp2p/js-libp2p-websocket-star/websocketstar' }) -},{"./listener":1152,"./utils":1153,"async/setImmediate":146,"class-is":224,"debug":1147,"events":370,"interface-connection":455,"mafmt":1296,"multiaddr":1314,"peer-id":1432,"peer-info":1433}],1152:[function(require,module,exports){ +},{"./listener":983,"./utils":984,"async/setImmediate":96,"class-is":187,"debug":979,"events":272,"interface-connection":319,"mafmt":1125,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],983:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -136099,7 +110268,7 @@ class Listener extends EE { module.exports = Listener }).call(this,require("buffer").Buffer) -},{"./errors":1150,"./utils":1153,"async/series":145,"async/setImmediate":146,"buffer":217,"debug":1147,"events":370,"interface-connection":455,"libp2p-crypto":905,"multiaddr":1314,"once":1394,"pull-stream/pull":1496,"pull-stream/throughs/through":1521,"socket.io-client":1652,"socket.io-pull-stream":1670,"uuid":1777}],1153:[function(require,module,exports){ +},{"./errors":981,"./utils":984,"async/series":95,"async/setImmediate":96,"buffer":181,"debug":979,"events":272,"interface-connection":319,"libp2p-crypto":745,"multiaddr":1140,"once":1228,"pull-stream/pull":1312,"pull-stream/throughs/through":1337,"socket.io-client":1423,"socket.io-pull-stream":1437,"uuid":1513}],984:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -136209,13 +110378,11 @@ exports.getIdAndValidate = getIdAndValidate exports.validateMa = (ma) => mafmt.WebSocketStar.matches(multiaddr(ma)) }).call(this,require("buffer").Buffer) -},{"buffer":217,"libp2p-crypto":905,"mafmt":1296,"multiaddr":1314,"peer-id":1432}],1154:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1155,"_process":1438,"dup":247}],1155:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1156}],1156:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1157:[function(require,module,exports){ +},{"buffer":181,"libp2p-crypto":745,"mafmt":1125,"multiaddr":1140,"peer-id":1253}],985:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":986,"_process":1258,"dup":208}],986:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],987:[function(require,module,exports){ 'use strict' const connect = require('pull-ws/client') @@ -136287,7 +110454,7 @@ class WebSockets { module.exports = withIs(WebSockets, { className: 'WebSockets', symbolName: '@libp2p/js-libp2p-websockets/websockets' }) -},{"./listener":1158,"class-is":224,"debug":1154,"interface-connection":455,"mafmt":1296,"multiaddr-to-uri":1311,"pull-ws/client":1528}],1158:[function(require,module,exports){ +},{"./listener":988,"class-is":187,"debug":985,"interface-connection":319,"mafmt":1125,"multiaddr-to-uri":1137,"pull-ws/client":1344}],988:[function(require,module,exports){ 'use strict' const Connection = require('interface-connection').Connection @@ -136357,15 +110524,13 @@ module.exports = (options, handler) => { return listener } -},{"interface-connection":455,"multiaddr":1314,"os":1395,"pull-ws/server":1532}],1159:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1160,"_process":1438,"dup":247}],1160:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1162}],1161:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1162:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1163:[function(require,module,exports){ +},{"interface-connection":319,"multiaddr":1140,"os":1229,"pull-ws/server":1348}],989:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":990,"_process":1258,"dup":208}],990:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],991:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],992:[function(require,module,exports){ 'use strict' const mafmt = require('mafmt') @@ -136493,7 +110658,7 @@ class Circuit { module.exports = Circuit -},{"./circuit/dialer":1164,"./circuit/utils":1168,"./listener":1170,"debug":1159,"mafmt":1296,"multiaddr":1314}],1164:[function(require,module,exports){ +},{"./circuit/dialer":993,"./circuit/utils":997,"./listener":999,"debug":989,"mafmt":1125,"multiaddr":1140}],993:[function(require,module,exports){ 'use strict' const once = require('once') @@ -136770,7 +110935,7 @@ class Dialer { module.exports = Dialer -},{"../multicodec":1171,"../protocol":1172,"./stream-handler":1167,"./utils":1168,"async/setImmediate":146,"async/waterfall":152,"debug":1159,"interface-connection":455,"multiaddr":1314,"once":1394,"peer-id":1432}],1165:[function(require,module,exports){ +},{"../multicodec":1000,"../protocol":1001,"./stream-handler":996,"./utils":997,"async/setImmediate":96,"async/waterfall":102,"debug":989,"interface-connection":319,"multiaddr":1140,"once":1228,"peer-id":1253}],994:[function(require,module,exports){ 'use strict' const pull = require('pull-stream/pull') @@ -137055,7 +111220,7 @@ class Hop extends EE { module.exports = Hop -},{"../protocol":1172,"./../multicodec":1171,"./stream-handler":1167,"./utils":1168,"async/series":145,"async/setImmediate":146,"async/waterfall":152,"debug":1159,"events":370,"multiaddr":1314,"once":1394,"peer-id":1432,"peer-info":1433,"pull-stream/pull":1496}],1166:[function(require,module,exports){ +},{"../protocol":1001,"./../multicodec":1000,"./stream-handler":996,"./utils":997,"async/series":95,"async/setImmediate":96,"async/waterfall":102,"debug":989,"events":272,"multiaddr":1140,"once":1228,"peer-id":1253,"peer-info":1254,"pull-stream/pull":1312}],995:[function(require,module,exports){ 'use strict' const setImmediate = require('async/setImmediate') @@ -137113,7 +111278,7 @@ class Stop extends EE { module.exports = Stop -},{"../protocol":1172,"./utils":1168,"async/series":145,"async/setImmediate":146,"debug":1159,"events":370,"interface-connection":455,"peer-info":1433}],1167:[function(require,module,exports){ +},{"../protocol":1001,"./utils":997,"async/series":95,"async/setImmediate":96,"debug":989,"events":272,"interface-connection":319,"peer-info":1254}],996:[function(require,module,exports){ 'use strict' const values = require('pull-stream/sources/values') @@ -137255,7 +111420,7 @@ class StreamHandler { module.exports = StreamHandler -},{"debug":1159,"pull-handshake":1472,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"pull-stream/sources/empty":1506,"pull-stream/sources/values":1512}],1168:[function(require,module,exports){ +},{"debug":989,"pull-handshake":1289,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"pull-stream/sources/empty":1322,"pull-stream/sources/values":1328}],997:[function(require,module,exports){ 'use strict' const multiaddr = require('multiaddr') @@ -137375,12 +111540,12 @@ module.exports = function (swarm) { } } -},{"../../get-peer-info":1178,"../protocol":1172,"multiaddr":1314,"peer-id":1432,"peer-info":1433}],1169:[function(require,module,exports){ +},{"../../get-peer-info":1007,"../protocol":1001,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],998:[function(require,module,exports){ 'use strict' module.exports = require('./circuit') -},{"./circuit":1163}],1170:[function(require,module,exports){ +},{"./circuit":992}],999:[function(require,module,exports){ 'use strict' const setImmediate = require('async/setImmediate') @@ -137531,14 +111696,14 @@ module.exports = (swarm, options, connHandler) => { return listener } -},{"./circuit/hop":1165,"./circuit/stop":1166,"./circuit/stream-handler":1167,"./circuit/utils":1168,"./multicodec":1171,"./protocol":1172,"async/setImmediate":146,"debug":1159,"events":370,"mafmt":1296,"multiaddr":1314}],1171:[function(require,module,exports){ +},{"./circuit/hop":994,"./circuit/stop":995,"./circuit/stream-handler":996,"./circuit/utils":997,"./multicodec":1000,"./protocol":1001,"async/setImmediate":96,"debug":989,"events":272,"mafmt":1125,"multiaddr":1140}],1000:[function(require,module,exports){ 'use strict' module.exports = { relay: '/libp2p/circuit/relay/0.1.0' } -},{}],1172:[function(require,module,exports){ +},{}],1001:[function(require,module,exports){ 'use strict' const protobuf = require('protons') module.exports = protobuf(` @@ -137584,7 +111749,7 @@ message CircuitRelay { } `) -},{"protons":1454}],1173:[function(require,module,exports){ +},{"protons":1274}],1002:[function(require,module,exports){ 'use strict' const mergeOptions = require('merge-options') @@ -137690,7 +111855,7 @@ module.exports.validate = (opts) => { return options } -},{"merge-options":1298,"superstruct":1743}],1174:[function(require,module,exports){ +},{"merge-options":1127,"superstruct":1498}],1003:[function(require,module,exports){ 'use strict' const EventEmitter = require('events') @@ -137910,7 +112075,7 @@ function protocolToProtocolTag (protocol) { return protocol.name.toLowerCase() } -},{"debug":1159,"events":370,"latency-monitor":842}],1175:[function(require,module,exports){ +},{"debug":989,"events":272,"latency-monitor":673}],1004:[function(require,module,exports){ 'use strict' const tryEach = require('async/tryEach') @@ -137996,7 +112161,7 @@ module.exports = (node) => { } } -},{"async/parallel":141,"async/tryEach":151,"err-code":1161,"promisify-es6":1443}],1176:[function(require,module,exports){ +},{"async/parallel":91,"async/tryEach":101,"err-code":991,"promisify-es6":1263}],1005:[function(require,module,exports){ 'use strict' const nextTick = require('async/nextTick') @@ -138041,7 +112206,7 @@ module.exports = (node) => { } } -},{"./errors":1177,"async/nextTick":140,"err-code":1161,"promisify-es6":1443}],1177:[function(require,module,exports){ +},{"./errors":1006,"async/nextTick":90,"err-code":991,"promisify-es6":1263}],1006:[function(require,module,exports){ 'use strict' exports.messages = { @@ -138056,7 +112221,7 @@ exports.codes = { ERR_DISCOVERED_SELF: 'ERR_DISCOVERED_SELF' } -},{}],1178:[function(require,module,exports){ +},{}],1007:[function(require,module,exports){ 'use strict' const PeerId = require('peer-id') @@ -138134,7 +112299,7 @@ module.exports = { getPeerInfo } -},{"err-code":1161,"multiaddr":1314,"peer-id":1432,"peer-info":1433}],1179:[function(require,module,exports){ +},{"err-code":991,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],1008:[function(require,module,exports){ 'use strict' const PeerInfo = require('peer-info') const PeerId = require('peer-id') @@ -138223,7 +112388,7 @@ function hasObservedAddr (input) { return input.observedAddr && input.observedAddr.length > 0 } -},{"./message":1182,"multiaddr":1314,"peer-id":1432,"peer-info":1433,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"pull-stream/throughs/take":1520}],1180:[function(require,module,exports){ +},{"./message":1011,"multiaddr":1140,"peer-id":1253,"peer-info":1254,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"pull-stream/throughs/take":1336}],1009:[function(require,module,exports){ 'use strict' exports = module.exports @@ -138232,7 +112397,7 @@ exports.listener = require('./listener') exports.dialer = require('./dialer') exports.message = require('./message') -},{"./dialer":1179,"./listener":1181,"./message":1182}],1181:[function(require,module,exports){ +},{"./dialer":1008,"./listener":1010,"./message":1011}],1010:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -138271,7 +112436,7 @@ module.exports = (conn, pInfoSelf) => { } }).call(this,require("buffer").Buffer) -},{"./message":1182,"buffer":217,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sources/values":1512}],1182:[function(require,module,exports){ +},{"./message":1011,"buffer":181,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sources/values":1328}],1011:[function(require,module,exports){ 'use strict' const protons = require('protons') @@ -138303,7 +112468,7 @@ message Identify { module.exports = protons(schema).Identify -},{"protons":1454}],1183:[function(require,module,exports){ +},{"protons":1274}],1012:[function(require,module,exports){ (function (process){ 'use strict' @@ -138890,7 +113055,7 @@ module.exports.createLibp2p = promisify((options, callback) => { }) }).call(this,require('_process')) -},{"./config":1173,"./connection-manager":1174,"./content-routing":1175,"./dht":1176,"./errors":1177,"./get-peer-info":1178,"./peer-routing":1184,"./ping":1187,"./pubsub":1190,"./switch":1201,"./util":1213,"_process":1438,"async/each":106,"async/nextTick":140,"async/parallel":141,"async/series":145,"debug":1159,"err-code":1161,"events":370,"fsm-event":383,"libp2p-websockets":1157,"peer-book":1431,"peer-info":1433,"promisify-es6":1443}],1184:[function(require,module,exports){ +},{"./config":1002,"./connection-manager":1003,"./content-routing":1004,"./dht":1005,"./errors":1006,"./get-peer-info":1007,"./peer-routing":1013,"./ping":1016,"./pubsub":1019,"./switch":1030,"./util":1042,"_process":1258,"async/each":56,"async/nextTick":90,"async/parallel":91,"async/series":95,"debug":989,"err-code":991,"events":272,"fsm-event":278,"libp2p-websockets":987,"peer-book":1252,"peer-info":1254,"promisify-es6":1263}],1013:[function(require,module,exports){ 'use strict' const tryEach = require('async/tryEach') @@ -138951,7 +113116,7 @@ module.exports = (node) => { } } -},{"async/tryEach":151,"err-code":1161,"promisify-es6":1443}],1185:[function(require,module,exports){ +},{"async/tryEach":101,"err-code":991,"promisify-es6":1263}],1014:[function(require,module,exports){ 'use strict' module.exports = { @@ -138959,7 +113124,7 @@ module.exports = { PING_LENGTH: 32 } -},{}],1186:[function(require,module,exports){ +},{}],1015:[function(require,module,exports){ 'use strict' const pull = require('pull-stream/pull') @@ -139011,7 +113176,7 @@ exports = module.exports exports.mount = mount exports.unmount = unmount -},{"./constants":1185,"debug":1159,"pull-handshake":1472,"pull-stream/pull":1496}],1187:[function(require,module,exports){ +},{"./constants":1014,"debug":989,"pull-handshake":1289,"pull-stream/pull":1312}],1016:[function(require,module,exports){ 'use strict' const handler = require('./handler') @@ -139020,7 +113185,7 @@ exports = module.exports = require('./ping') exports.mount = handler.mount exports.unmount = handler.unmount -},{"./handler":1186,"./ping":1188}],1188:[function(require,module,exports){ +},{"./handler":1015,"./ping":1017}],1017:[function(require,module,exports){ 'use strict' const EventEmitter = require('events').EventEmitter @@ -139105,7 +113270,7 @@ class Ping extends EventEmitter { module.exports = Ping -},{"./constants":1185,"./util":1189,"debug":1159,"events":370,"pull-handshake":1472,"pull-stream/pull":1496,"pull-stream/sources/empty":1506}],1189:[function(require,module,exports){ +},{"./constants":1014,"./util":1018,"debug":989,"events":272,"pull-handshake":1289,"pull-stream/pull":1312,"pull-stream/sources/empty":1322}],1018:[function(require,module,exports){ 'use strict' const crypto = require('libp2p-crypto') @@ -139120,7 +113285,7 @@ exports.rnd = (length) => { return crypto.randomBytes(length) } -},{"./constants":1185,"libp2p-crypto":905}],1190:[function(require,module,exports){ +},{"./constants":1014,"libp2p-crypto":745}],1019:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -139289,7 +113454,7 @@ module.exports = (node, Pubsub, config) => { } }).call(this,require("buffer").Buffer) -},{"./errors":1177,"async/nextTick":140,"buffer":217,"err-code":1161,"promisify-es6":1443}],1191:[function(require,module,exports){ +},{"./errors":1006,"async/nextTick":90,"buffer":181,"err-code":991,"promisify-es6":1263}],1020:[function(require,module,exports){ 'use strict' const EventEmitter = require('events').EventEmitter @@ -139417,7 +113582,7 @@ module.exports = withIs(BaseConnection, { symbolName: 'libp2p-switch/BaseConnection' }) -},{"class-is":224,"debug":1159,"events":370}],1192:[function(require,module,exports){ +},{"class-is":187,"debug":989,"events":272}],1021:[function(require,module,exports){ 'use strict' const debug = require('debug') @@ -139466,7 +113631,7 @@ function listener (_switch) { module.exports = listener -},{"../observe-connection":1204,"./incoming":1193,"debug":1159}],1193:[function(require,module,exports){ +},{"../observe-connection":1033,"./incoming":1022,"debug":989}],1022:[function(require,module,exports){ 'use strict' const FSM = require('fsm-event') @@ -139583,7 +113748,7 @@ module.exports = withIs(IncomingConnectionFSM, { symbolName: 'libp2p-switch/IncomingConnectionFSM' }) -},{"./base":1191,"class-is":224,"fsm-event":383,"multistream-select":1344}],1194:[function(require,module,exports){ +},{"./base":1020,"class-is":187,"fsm-event":278,"multistream-select":1169}],1023:[function(require,module,exports){ 'use strict' const FSM = require('fsm-event') @@ -140083,7 +114248,7 @@ module.exports = withIs(ConnectionFSM, { symbolName: 'libp2p-switch/ConnectionFSM' }) -},{"../../circuit":1169,"../../identify":1180,"../errors":1200,"../observe-connection":1204,"../utils":1212,"./base":1191,"async/nextTick":140,"async/parallel":141,"class-is":224,"err-code":1161,"fsm-event":383,"multistream-select":1344}],1195:[function(require,module,exports){ +},{"../../circuit":998,"../../identify":1009,"../errors":1029,"../observe-connection":1033,"../utils":1041,"./base":1020,"async/nextTick":90,"async/parallel":91,"class-is":187,"err-code":991,"fsm-event":278,"multistream-select":1169}],1024:[function(require,module,exports){ 'use strict' const identify = require('../../identify') @@ -140374,7 +114539,7 @@ class ConnectionManager { module.exports = ConnectionManager -},{"../../circuit":1169,"../../identify":1180,"../connection":1194,"../plaintext":1206,"../utils":1212,"debug":1159,"multistream-select":1344,"once":1394}],1196:[function(require,module,exports){ +},{"../../circuit":998,"../../identify":1009,"../connection":1023,"../plaintext":1035,"../utils":1041,"debug":989,"multistream-select":1169,"once":1228}],1025:[function(require,module,exports){ 'use strict' module.exports = { @@ -140388,7 +114553,7 @@ module.exports = { PRIORITY_LOW: 20 } -},{}],1197:[function(require,module,exports){ +},{}],1026:[function(require,module,exports){ 'use strict' const DialQueueManager = require('./queueManager') @@ -140509,7 +114674,7 @@ module.exports = function (_switch) { } } -},{"../../get-peer-info":1178,"../constants":1196,"./queueManager":1199}],1198:[function(require,module,exports){ +},{"../../get-peer-info":1007,"../constants":1025,"./queueManager":1028}],1027:[function(require,module,exports){ 'use strict' const ConnectionFSM = require('../connection') @@ -140792,7 +114957,7 @@ class Queue { module.exports = Queue -},{"../connection":1194,"../errors":1200,"async/nextTick":140,"debug":1159,"once":1394}],1199:[function(require,module,exports){ +},{"../connection":1023,"../errors":1029,"async/nextTick":90,"debug":989,"once":1228}],1028:[function(require,module,exports){ 'use strict' const once = require('once') @@ -141014,7 +115179,7 @@ class DialQueueManager { module.exports = DialQueueManager -},{"../constants":1196,"../errors":1200,"./queue":1198,"async/nextTick":140,"debug":1159,"once":1394,"retimer":1590}],1200:[function(require,module,exports){ +},{"../constants":1025,"../errors":1029,"./queue":1027,"async/nextTick":90,"debug":989,"once":1228,"retimer":1368}],1029:[function(require,module,exports){ 'use strict' const errCode = require('err-code') @@ -141036,7 +115201,7 @@ module.exports = { } } -},{"err-code":1161}],1201:[function(require,module,exports){ +},{"err-code":991}],1030:[function(require,module,exports){ 'use strict' const FSM = require('fsm-event') @@ -141312,7 +115477,7 @@ class Switch extends EventEmitter { module.exports = Switch module.exports.errors = Errors -},{"../circuit":1169,"../get-peer-info":1178,"./connection/handler":1192,"./connection/manager":1195,"./dialer":1197,"./errors":1200,"./observer":1205,"./plaintext":1206,"./protocol-muxer":1207,"./stats":1208,"./transport":1211,"assert":78,"async/each":106,"async/eachSeries":111,"async/series":145,"debug":1159,"events":370,"fsm-event":383}],1202:[function(require,module,exports){ +},{"../circuit":998,"../get-peer-info":1007,"./connection/handler":1021,"./connection/manager":1024,"./dialer":1026,"./errors":1029,"./observer":1034,"./plaintext":1035,"./protocol-muxer":1036,"./stats":1037,"./transport":1040,"assert":26,"async/each":56,"async/eachSeries":61,"async/series":95,"debug":989,"events":272,"fsm-event":278}],1031:[function(require,module,exports){ 'use strict' const tryEach = require('async/tryEach') @@ -141402,7 +115567,7 @@ class LimitDialer { module.exports = LimitDialer -},{"./queue":1203,"async/tryEach":151,"debug":1159}],1203:[function(require,module,exports){ +},{"./queue":1032,"async/tryEach":101,"debug":989}],1032:[function(require,module,exports){ 'use strict' const Connection = require('interface-connection').Connection @@ -141513,7 +115678,7 @@ class DialQueue { module.exports = DialQueue -},{"async/queue":142,"async/timeout":150,"debug":1159,"interface-connection":455,"once":1394,"pull-stream/pull":1496,"pull-stream/sources/empty":1506}],1204:[function(require,module,exports){ +},{"async/queue":92,"async/timeout":100,"debug":989,"interface-connection":319,"once":1228,"pull-stream/pull":1312,"pull-stream/sources/empty":1322}],1033:[function(require,module,exports){ 'use strict' const Connection = require('interface-connection').Connection @@ -141559,7 +115724,7 @@ module.exports = (transport, protocol, connection, observer) => { return new Connection(stream, connection) } -},{"interface-connection":455,"pull-stream/pull":1496}],1205:[function(require,module,exports){ +},{"interface-connection":319,"pull-stream/pull":1312}],1034:[function(require,module,exports){ 'use strict' const map = require('pull-stream/throughs/map') @@ -141609,7 +115774,7 @@ module.exports = (swtch) => { } } -},{"events":370,"pull-stream/throughs/map":1518}],1206:[function(require,module,exports){ +},{"events":272,"pull-stream/throughs/map":1334}],1035:[function(require,module,exports){ 'use strict' const setImmediate = require('async/setImmediate') @@ -141631,7 +115796,7 @@ module.exports = { } } -},{"async/setImmediate":146}],1207:[function(require,module,exports){ +},{"async/setImmediate":96}],1036:[function(require,module,exports){ 'use strict' const multistream = require('multistream-select') @@ -141681,7 +115846,7 @@ module.exports = function protocolMuxer (protocols, observer) { } } -},{"./observe-connection":1204,"debug":1159,"multistream-select":1344}],1208:[function(require,module,exports){ +},{"./observe-connection":1033,"debug":989,"multistream-select":1169}],1037:[function(require,module,exports){ 'use strict' const EventEmitter = require('events') @@ -141833,7 +115998,7 @@ module.exports = (observer, _options) => { } } -},{"./old-peers":1209,"./stat":1210,"events":370}],1209:[function(require,module,exports){ +},{"./old-peers":1038,"./stat":1039,"events":272}],1038:[function(require,module,exports){ 'use strict' const LRU = require('hashlru') @@ -141850,7 +116015,7 @@ module.exports = (maxSize) => { return patched } -},{"hashlru":436}],1210:[function(require,module,exports){ +},{"hashlru":306}],1039:[function(require,module,exports){ 'use strict' const EventEmitter = require('events') @@ -142091,7 +116256,7 @@ class Stats extends EventEmitter { module.exports = Stats -},{"bignumber.js":164,"events":370,"moving-average":1309,"retimer":1590}],1211:[function(require,module,exports){ +},{"bignumber.js":110,"events":272,"moving-average":1135,"retimer":1368}],1040:[function(require,module,exports){ 'use strict' /* eslint no-warning-comments: off */ @@ -142365,7 +116530,7 @@ function getDestination (addr) { module.exports = TransportManager -},{"./constants":1196,"./limit-dialer":1202,"./utils":1212,"async/parallel":141,"debug":1159,"once":1394}],1212:[function(require,module,exports){ +},{"./constants":1025,"./limit-dialer":1031,"./utils":1041,"async/parallel":91,"debug":989,"once":1228}],1041:[function(require,module,exports){ 'use strict' const Identify = require('../identify') @@ -142427,7 +116592,7 @@ module.exports.uniqueBy = (arr, getValue) => { return [...new Map(arr.map((i) => [getValue(i), i])).values()] } -},{"../identify":1180}],1213:[function(require,module,exports){ +},{"../identify":1009}],1042:[function(require,module,exports){ 'use strict' const once = require('once') @@ -142462,7 +116627,7 @@ function emitFirst (emitter, events, handler) { module.exports.emitFirst = emitFirst -},{"once":1394}],1214:[function(require,module,exports){ +},{"once":1228}],1043:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -144121,7 +118286,7 @@ function keys(object) { module.exports = isEqualWith; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1215:[function(require,module,exports){ +},{}],1044:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -144564,7 +118729,7 @@ function toNumber(value) { module.exports = throttle; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1216:[function(require,module,exports){ +},{}],1045:[function(require,module,exports){ var hashClear = require('./_hashClear'), hashDelete = require('./_hashDelete'), hashGet = require('./_hashGet'), @@ -144598,7 +118763,7 @@ Hash.prototype.set = hashSet; module.exports = Hash; -},{"./_hashClear":1244,"./_hashDelete":1245,"./_hashGet":1246,"./_hashHas":1247,"./_hashSet":1248}],1217:[function(require,module,exports){ +},{"./_hashClear":1073,"./_hashDelete":1074,"./_hashGet":1075,"./_hashHas":1076,"./_hashSet":1077}],1046:[function(require,module,exports){ var listCacheClear = require('./_listCacheClear'), listCacheDelete = require('./_listCacheDelete'), listCacheGet = require('./_listCacheGet'), @@ -144632,7 +118797,7 @@ ListCache.prototype.set = listCacheSet; module.exports = ListCache; -},{"./_listCacheClear":1254,"./_listCacheDelete":1255,"./_listCacheGet":1256,"./_listCacheHas":1257,"./_listCacheSet":1258}],1218:[function(require,module,exports){ +},{"./_listCacheClear":1083,"./_listCacheDelete":1084,"./_listCacheGet":1085,"./_listCacheHas":1086,"./_listCacheSet":1087}],1047:[function(require,module,exports){ var getNative = require('./_getNative'), root = require('./_root'); @@ -144641,7 +118806,7 @@ var Map = getNative(root, 'Map'); module.exports = Map; -},{"./_getNative":1241,"./_root":1270}],1219:[function(require,module,exports){ +},{"./_getNative":1070,"./_root":1099}],1048:[function(require,module,exports){ var mapCacheClear = require('./_mapCacheClear'), mapCacheDelete = require('./_mapCacheDelete'), mapCacheGet = require('./_mapCacheGet'), @@ -144675,7 +118840,7 @@ MapCache.prototype.set = mapCacheSet; module.exports = MapCache; -},{"./_mapCacheClear":1259,"./_mapCacheDelete":1260,"./_mapCacheGet":1261,"./_mapCacheHas":1262,"./_mapCacheSet":1263}],1220:[function(require,module,exports){ +},{"./_mapCacheClear":1088,"./_mapCacheDelete":1089,"./_mapCacheGet":1090,"./_mapCacheHas":1091,"./_mapCacheSet":1092}],1049:[function(require,module,exports){ var root = require('./_root'); /** Built-in value references. */ @@ -144683,7 +118848,7 @@ var Symbol = root.Symbol; module.exports = Symbol; -},{"./_root":1270}],1221:[function(require,module,exports){ +},{"./_root":1099}],1050:[function(require,module,exports){ var baseTimes = require('./_baseTimes'), isArguments = require('./isArguments'), isArray = require('./isArray'), @@ -144734,7 +118899,7 @@ function arrayLikeKeys(value, inherited) { module.exports = arrayLikeKeys; -},{"./_baseTimes":1234,"./_isIndex":1249,"./isArguments":1279,"./isArray":1280,"./isBuffer":1282,"./isTypedArray":1288}],1222:[function(require,module,exports){ +},{"./_baseTimes":1063,"./_isIndex":1078,"./isArguments":1108,"./isArray":1109,"./isBuffer":1111,"./isTypedArray":1117}],1051:[function(require,module,exports){ /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. @@ -144757,7 +118922,7 @@ function arrayMap(array, iteratee) { module.exports = arrayMap; -},{}],1223:[function(require,module,exports){ +},{}],1052:[function(require,module,exports){ var eq = require('./eq'); /** @@ -144780,7 +118945,7 @@ function assocIndexOf(array, key) { module.exports = assocIndexOf; -},{"./eq":1276}],1224:[function(require,module,exports){ +},{"./eq":1105}],1053:[function(require,module,exports){ /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. @@ -144806,7 +118971,7 @@ function baseFindIndex(array, predicate, fromIndex, fromRight) { module.exports = baseFindIndex; -},{}],1225:[function(require,module,exports){ +},{}],1054:[function(require,module,exports){ var castPath = require('./_castPath'), toKey = require('./_toKey'); @@ -144832,7 +118997,7 @@ function baseGet(object, path) { module.exports = baseGet; -},{"./_castPath":1237,"./_toKey":1273}],1226:[function(require,module,exports){ +},{"./_castPath":1066,"./_toKey":1102}],1055:[function(require,module,exports){ var Symbol = require('./_Symbol'), getRawTag = require('./_getRawTag'), objectToString = require('./_objectToString'); @@ -144862,7 +119027,7 @@ function baseGetTag(value) { module.exports = baseGetTag; -},{"./_Symbol":1220,"./_getRawTag":1242,"./_objectToString":1268}],1227:[function(require,module,exports){ +},{"./_Symbol":1049,"./_getRawTag":1071,"./_objectToString":1097}],1056:[function(require,module,exports){ var baseFindIndex = require('./_baseFindIndex'), baseIsNaN = require('./_baseIsNaN'), strictIndexOf = require('./_strictIndexOf'); @@ -144884,7 +119049,7 @@ function baseIndexOf(array, value, fromIndex) { module.exports = baseIndexOf; -},{"./_baseFindIndex":1224,"./_baseIsNaN":1229,"./_strictIndexOf":1271}],1228:[function(require,module,exports){ +},{"./_baseFindIndex":1053,"./_baseIsNaN":1058,"./_strictIndexOf":1100}],1057:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); @@ -144904,7 +119069,7 @@ function baseIsArguments(value) { module.exports = baseIsArguments; -},{"./_baseGetTag":1226,"./isObjectLike":1286}],1229:[function(require,module,exports){ +},{"./_baseGetTag":1055,"./isObjectLike":1115}],1058:[function(require,module,exports){ /** * The base implementation of `_.isNaN` without support for number objects. * @@ -144918,7 +119083,7 @@ function baseIsNaN(value) { module.exports = baseIsNaN; -},{}],1230:[function(require,module,exports){ +},{}],1059:[function(require,module,exports){ var isFunction = require('./isFunction'), isMasked = require('./_isMasked'), isObject = require('./isObject'), @@ -144967,7 +119132,7 @@ function baseIsNative(value) { module.exports = baseIsNative; -},{"./_isMasked":1252,"./_toSource":1274,"./isFunction":1283,"./isObject":1285}],1231:[function(require,module,exports){ +},{"./_isMasked":1081,"./_toSource":1103,"./isFunction":1112,"./isObject":1114}],1060:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isLength = require('./isLength'), isObjectLike = require('./isObjectLike'); @@ -145029,7 +119194,7 @@ function baseIsTypedArray(value) { module.exports = baseIsTypedArray; -},{"./_baseGetTag":1226,"./isLength":1284,"./isObjectLike":1286}],1232:[function(require,module,exports){ +},{"./_baseGetTag":1055,"./isLength":1113,"./isObjectLike":1115}],1061:[function(require,module,exports){ var isPrototype = require('./_isPrototype'), nativeKeys = require('./_nativeKeys'); @@ -145061,7 +119226,7 @@ function baseKeys(object) { module.exports = baseKeys; -},{"./_isPrototype":1253,"./_nativeKeys":1266}],1233:[function(require,module,exports){ +},{"./_isPrototype":1082,"./_nativeKeys":1095}],1062:[function(require,module,exports){ /** * The base implementation of `_.property` without support for deep paths. * @@ -145077,7 +119242,7 @@ function baseProperty(key) { module.exports = baseProperty; -},{}],1234:[function(require,module,exports){ +},{}],1063:[function(require,module,exports){ /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. @@ -145099,7 +119264,7 @@ function baseTimes(n, iteratee) { module.exports = baseTimes; -},{}],1235:[function(require,module,exports){ +},{}],1064:[function(require,module,exports){ var Symbol = require('./_Symbol'), arrayMap = require('./_arrayMap'), isArray = require('./isArray'), @@ -145138,7 +119303,7 @@ function baseToString(value) { module.exports = baseToString; -},{"./_Symbol":1220,"./_arrayMap":1222,"./isArray":1280,"./isSymbol":1287}],1236:[function(require,module,exports){ +},{"./_Symbol":1049,"./_arrayMap":1051,"./isArray":1109,"./isSymbol":1116}],1065:[function(require,module,exports){ /** * The base implementation of `_.unary` without support for storing metadata. * @@ -145154,7 +119319,7 @@ function baseUnary(func) { module.exports = baseUnary; -},{}],1237:[function(require,module,exports){ +},{}],1066:[function(require,module,exports){ var isArray = require('./isArray'), isKey = require('./_isKey'), stringToPath = require('./_stringToPath'), @@ -145177,7 +119342,7 @@ function castPath(value, object) { module.exports = castPath; -},{"./_isKey":1250,"./_stringToPath":1272,"./isArray":1280,"./toString":1293}],1238:[function(require,module,exports){ +},{"./_isKey":1079,"./_stringToPath":1101,"./isArray":1109,"./toString":1122}],1067:[function(require,module,exports){ var root = require('./_root'); /** Used to detect overreaching core-js shims. */ @@ -145185,7 +119350,7 @@ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; -},{"./_root":1270}],1239:[function(require,module,exports){ +},{"./_root":1099}],1068:[function(require,module,exports){ (function (global){ /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; @@ -145193,7 +119358,7 @@ var freeGlobal = typeof global == 'object' && global && global.Object === Object module.exports = freeGlobal; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1240:[function(require,module,exports){ +},{}],1069:[function(require,module,exports){ var isKeyable = require('./_isKeyable'); /** @@ -145213,7 +119378,7 @@ function getMapData(map, key) { module.exports = getMapData; -},{"./_isKeyable":1251}],1241:[function(require,module,exports){ +},{"./_isKeyable":1080}],1070:[function(require,module,exports){ var baseIsNative = require('./_baseIsNative'), getValue = require('./_getValue'); @@ -145232,7 +119397,7 @@ function getNative(object, key) { module.exports = getNative; -},{"./_baseIsNative":1230,"./_getValue":1243}],1242:[function(require,module,exports){ +},{"./_baseIsNative":1059,"./_getValue":1072}],1071:[function(require,module,exports){ var Symbol = require('./_Symbol'); /** Used for built-in method references. */ @@ -145280,7 +119445,7 @@ function getRawTag(value) { module.exports = getRawTag; -},{"./_Symbol":1220}],1243:[function(require,module,exports){ +},{"./_Symbol":1049}],1072:[function(require,module,exports){ /** * Gets the value at `key` of `object`. * @@ -145295,7 +119460,7 @@ function getValue(object, key) { module.exports = getValue; -},{}],1244:[function(require,module,exports){ +},{}],1073:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** @@ -145312,7 +119477,7 @@ function hashClear() { module.exports = hashClear; -},{"./_nativeCreate":1265}],1245:[function(require,module,exports){ +},{"./_nativeCreate":1094}],1074:[function(require,module,exports){ /** * Removes `key` and its value from the hash. * @@ -145331,7 +119496,7 @@ function hashDelete(key) { module.exports = hashDelete; -},{}],1246:[function(require,module,exports){ +},{}],1075:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used to stand-in for `undefined` hash values. */ @@ -145363,7 +119528,7 @@ function hashGet(key) { module.exports = hashGet; -},{"./_nativeCreate":1265}],1247:[function(require,module,exports){ +},{"./_nativeCreate":1094}],1076:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used for built-in method references. */ @@ -145388,7 +119553,7 @@ function hashHas(key) { module.exports = hashHas; -},{"./_nativeCreate":1265}],1248:[function(require,module,exports){ +},{"./_nativeCreate":1094}],1077:[function(require,module,exports){ var nativeCreate = require('./_nativeCreate'); /** Used to stand-in for `undefined` hash values. */ @@ -145413,7 +119578,7 @@ function hashSet(key, value) { module.exports = hashSet; -},{"./_nativeCreate":1265}],1249:[function(require,module,exports){ +},{"./_nativeCreate":1094}],1078:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; @@ -145440,7 +119605,7 @@ function isIndex(value, length) { module.exports = isIndex; -},{}],1250:[function(require,module,exports){ +},{}],1079:[function(require,module,exports){ var isArray = require('./isArray'), isSymbol = require('./isSymbol'); @@ -145471,7 +119636,7 @@ function isKey(value, object) { module.exports = isKey; -},{"./isArray":1280,"./isSymbol":1287}],1251:[function(require,module,exports){ +},{"./isArray":1109,"./isSymbol":1116}],1080:[function(require,module,exports){ /** * Checks if `value` is suitable for use as unique object key. * @@ -145488,7 +119653,7 @@ function isKeyable(value) { module.exports = isKeyable; -},{}],1252:[function(require,module,exports){ +},{}],1081:[function(require,module,exports){ var coreJsData = require('./_coreJsData'); /** Used to detect methods masquerading as native. */ @@ -145510,7 +119675,7 @@ function isMasked(func) { module.exports = isMasked; -},{"./_coreJsData":1238}],1253:[function(require,module,exports){ +},{"./_coreJsData":1067}],1082:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; @@ -145530,7 +119695,7 @@ function isPrototype(value) { module.exports = isPrototype; -},{}],1254:[function(require,module,exports){ +},{}],1083:[function(require,module,exports){ /** * Removes all key-value entries from the list cache. * @@ -145545,7 +119710,7 @@ function listCacheClear() { module.exports = listCacheClear; -},{}],1255:[function(require,module,exports){ +},{}],1084:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** Used for built-in method references. */ @@ -145582,7 +119747,7 @@ function listCacheDelete(key) { module.exports = listCacheDelete; -},{"./_assocIndexOf":1223}],1256:[function(require,module,exports){ +},{"./_assocIndexOf":1052}],1085:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** @@ -145603,7 +119768,7 @@ function listCacheGet(key) { module.exports = listCacheGet; -},{"./_assocIndexOf":1223}],1257:[function(require,module,exports){ +},{"./_assocIndexOf":1052}],1086:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** @@ -145621,7 +119786,7 @@ function listCacheHas(key) { module.exports = listCacheHas; -},{"./_assocIndexOf":1223}],1258:[function(require,module,exports){ +},{"./_assocIndexOf":1052}],1087:[function(require,module,exports){ var assocIndexOf = require('./_assocIndexOf'); /** @@ -145649,7 +119814,7 @@ function listCacheSet(key, value) { module.exports = listCacheSet; -},{"./_assocIndexOf":1223}],1259:[function(require,module,exports){ +},{"./_assocIndexOf":1052}],1088:[function(require,module,exports){ var Hash = require('./_Hash'), ListCache = require('./_ListCache'), Map = require('./_Map'); @@ -145672,7 +119837,7 @@ function mapCacheClear() { module.exports = mapCacheClear; -},{"./_Hash":1216,"./_ListCache":1217,"./_Map":1218}],1260:[function(require,module,exports){ +},{"./_Hash":1045,"./_ListCache":1046,"./_Map":1047}],1089:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** @@ -145692,7 +119857,7 @@ function mapCacheDelete(key) { module.exports = mapCacheDelete; -},{"./_getMapData":1240}],1261:[function(require,module,exports){ +},{"./_getMapData":1069}],1090:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** @@ -145710,7 +119875,7 @@ function mapCacheGet(key) { module.exports = mapCacheGet; -},{"./_getMapData":1240}],1262:[function(require,module,exports){ +},{"./_getMapData":1069}],1091:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** @@ -145728,7 +119893,7 @@ function mapCacheHas(key) { module.exports = mapCacheHas; -},{"./_getMapData":1240}],1263:[function(require,module,exports){ +},{"./_getMapData":1069}],1092:[function(require,module,exports){ var getMapData = require('./_getMapData'); /** @@ -145752,7 +119917,7 @@ function mapCacheSet(key, value) { module.exports = mapCacheSet; -},{"./_getMapData":1240}],1264:[function(require,module,exports){ +},{"./_getMapData":1069}],1093:[function(require,module,exports){ var memoize = require('./memoize'); /** Used as the maximum memoize cache size. */ @@ -145780,7 +119945,7 @@ function memoizeCapped(func) { module.exports = memoizeCapped; -},{"./memoize":1290}],1265:[function(require,module,exports){ +},{"./memoize":1119}],1094:[function(require,module,exports){ var getNative = require('./_getNative'); /* Built-in method references that are verified to be native. */ @@ -145788,7 +119953,7 @@ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; -},{"./_getNative":1241}],1266:[function(require,module,exports){ +},{"./_getNative":1070}],1095:[function(require,module,exports){ var overArg = require('./_overArg'); /* Built-in method references for those with the same name as other `lodash` methods. */ @@ -145796,7 +119961,7 @@ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; -},{"./_overArg":1269}],1267:[function(require,module,exports){ +},{"./_overArg":1098}],1096:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); /** Detect free variable `exports`. */ @@ -145828,7 +119993,7 @@ var nodeUtil = (function() { module.exports = nodeUtil; -},{"./_freeGlobal":1239}],1268:[function(require,module,exports){ +},{"./_freeGlobal":1068}],1097:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; @@ -145852,7 +120017,7 @@ function objectToString(value) { module.exports = objectToString; -},{}],1269:[function(require,module,exports){ +},{}],1098:[function(require,module,exports){ /** * Creates a unary function that invokes `func` with its argument transformed. * @@ -145869,7 +120034,7 @@ function overArg(func, transform) { module.exports = overArg; -},{}],1270:[function(require,module,exports){ +},{}],1099:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); /** Detect free variable `self`. */ @@ -145880,7 +120045,7 @@ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; -},{"./_freeGlobal":1239}],1271:[function(require,module,exports){ +},{"./_freeGlobal":1068}],1100:[function(require,module,exports){ /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. @@ -145905,7 +120070,7 @@ function strictIndexOf(array, value, fromIndex) { module.exports = strictIndexOf; -},{}],1272:[function(require,module,exports){ +},{}],1101:[function(require,module,exports){ var memoizeCapped = require('./_memoizeCapped'); /** Used to match property names within property paths. */ @@ -145934,7 +120099,7 @@ var stringToPath = memoizeCapped(function(string) { module.exports = stringToPath; -},{"./_memoizeCapped":1264}],1273:[function(require,module,exports){ +},{"./_memoizeCapped":1093}],1102:[function(require,module,exports){ var isSymbol = require('./isSymbol'); /** Used as references for various `Number` constants. */ @@ -145957,7 +120122,7 @@ function toKey(value) { module.exports = toKey; -},{"./isSymbol":1287}],1274:[function(require,module,exports){ +},{"./isSymbol":1116}],1103:[function(require,module,exports){ /** Used for built-in method references. */ var funcProto = Function.prototype; @@ -145985,7 +120150,7 @@ function toSource(func) { module.exports = toSource; -},{}],1275:[function(require,module,exports){ +},{}],1104:[function(require,module,exports){ /** * Creates a function that returns `value`. * @@ -146013,7 +120178,7 @@ function constant(value) { module.exports = constant; -},{}],1276:[function(require,module,exports){ +},{}],1105:[function(require,module,exports){ /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) @@ -146052,7 +120217,7 @@ function eq(value, other) { module.exports = eq; -},{}],1277:[function(require,module,exports){ +},{}],1106:[function(require,module,exports){ var baseGet = require('./_baseGet'); /** @@ -146087,7 +120252,7 @@ function get(object, path, defaultValue) { module.exports = get; -},{"./_baseGet":1225}],1278:[function(require,module,exports){ +},{"./_baseGet":1054}],1107:[function(require,module,exports){ /** * This method returns the first argument it receives. * @@ -146110,7 +120275,7 @@ function identity(value) { module.exports = identity; -},{}],1279:[function(require,module,exports){ +},{}],1108:[function(require,module,exports){ var baseIsArguments = require('./_baseIsArguments'), isObjectLike = require('./isObjectLike'); @@ -146148,7 +120313,7 @@ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsAr module.exports = isArguments; -},{"./_baseIsArguments":1228,"./isObjectLike":1286}],1280:[function(require,module,exports){ +},{"./_baseIsArguments":1057,"./isObjectLike":1115}],1109:[function(require,module,exports){ /** * Checks if `value` is classified as an `Array` object. * @@ -146176,7 +120341,7 @@ var isArray = Array.isArray; module.exports = isArray; -},{}],1281:[function(require,module,exports){ +},{}],1110:[function(require,module,exports){ var isFunction = require('./isFunction'), isLength = require('./isLength'); @@ -146211,7 +120376,7 @@ function isArrayLike(value) { module.exports = isArrayLike; -},{"./isFunction":1283,"./isLength":1284}],1282:[function(require,module,exports){ +},{"./isFunction":1112,"./isLength":1113}],1111:[function(require,module,exports){ var root = require('./_root'), stubFalse = require('./stubFalse'); @@ -146251,7 +120416,7 @@ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; -},{"./_root":1270,"./stubFalse":1292}],1283:[function(require,module,exports){ +},{"./_root":1099,"./stubFalse":1121}],1112:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObject = require('./isObject'); @@ -146290,7 +120455,7 @@ function isFunction(value) { module.exports = isFunction; -},{"./_baseGetTag":1226,"./isObject":1285}],1284:[function(require,module,exports){ +},{"./_baseGetTag":1055,"./isObject":1114}],1113:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; @@ -146327,7 +120492,7 @@ function isLength(value) { module.exports = isLength; -},{}],1285:[function(require,module,exports){ +},{}],1114:[function(require,module,exports){ /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) @@ -146360,7 +120525,7 @@ function isObject(value) { module.exports = isObject; -},{}],1286:[function(require,module,exports){ +},{}],1115:[function(require,module,exports){ /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". @@ -146391,7 +120556,7 @@ function isObjectLike(value) { module.exports = isObjectLike; -},{}],1287:[function(require,module,exports){ +},{}],1116:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); @@ -146422,7 +120587,7 @@ function isSymbol(value) { module.exports = isSymbol; -},{"./_baseGetTag":1226,"./isObjectLike":1286}],1288:[function(require,module,exports){ +},{"./_baseGetTag":1055,"./isObjectLike":1115}],1117:[function(require,module,exports){ var baseIsTypedArray = require('./_baseIsTypedArray'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); @@ -146451,7 +120616,7 @@ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedA module.exports = isTypedArray; -},{"./_baseIsTypedArray":1231,"./_baseUnary":1236,"./_nodeUtil":1267}],1289:[function(require,module,exports){ +},{"./_baseIsTypedArray":1060,"./_baseUnary":1065,"./_nodeUtil":1096}],1118:[function(require,module,exports){ var arrayLikeKeys = require('./_arrayLikeKeys'), baseKeys = require('./_baseKeys'), isArrayLike = require('./isArrayLike'); @@ -146490,7 +120655,7 @@ function keys(object) { module.exports = keys; -},{"./_arrayLikeKeys":1221,"./_baseKeys":1232,"./isArrayLike":1281}],1290:[function(require,module,exports){ +},{"./_arrayLikeKeys":1050,"./_baseKeys":1061,"./isArrayLike":1110}],1119:[function(require,module,exports){ var MapCache = require('./_MapCache'); /** Error message constants. */ @@ -146565,7 +120730,7 @@ memoize.Cache = MapCache; module.exports = memoize; -},{"./_MapCache":1219}],1291:[function(require,module,exports){ +},{"./_MapCache":1048}],1120:[function(require,module,exports){ /** * This method returns `undefined`. * @@ -146584,7 +120749,7 @@ function noop() { module.exports = noop; -},{}],1292:[function(require,module,exports){ +},{}],1121:[function(require,module,exports){ /** * This method returns `false`. * @@ -146604,7 +120769,7 @@ function stubFalse() { module.exports = stubFalse; -},{}],1293:[function(require,module,exports){ +},{}],1122:[function(require,module,exports){ var baseToString = require('./_baseToString'); /** @@ -146634,7 +120799,7 @@ function toString(value) { module.exports = toString; -},{"./_baseToString":1235}],1294:[function(require,module,exports){ +},{"./_baseToString":1064}],1123:[function(require,module,exports){ var looper = module.exports = function (fun) { (function next () { @@ -146650,7 +120815,7 @@ var looper = module.exports = function (fun) { })() } -},{}],1295:[function(require,module,exports){ +},{}],1124:[function(require,module,exports){ (function (Buffer){ exports.compare = function (a, b) { @@ -146819,7 +120984,7 @@ exports.filter = function (range, compare) { }).call(this,{"isBuffer":require("../is-buffer/index.js")}) -},{"../is-buffer/index.js":766}],1296:[function(require,module,exports){ +},{"../is-buffer/index.js":608}],1125:[function(require,module,exports){ 'use strict' const multiaddr = require('multiaddr') @@ -147069,7 +121234,7 @@ function base (n) { } } -},{"multiaddr":1314}],1297:[function(require,module,exports){ +},{"multiaddr":1140}],1126:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') @@ -147217,7 +121382,7 @@ function fnI (a, b, c, d, m, k, s) { module.exports = MD5 -},{"hash-base":423,"inherits":453,"safe-buffer":1593}],1298:[function(require,module,exports){ +},{"hash-base":293,"inherits":317,"safe-buffer":1371}],1127:[function(require,module,exports){ 'use strict'; const isOptionObject = require('is-plain-obj'); @@ -147382,7 +121547,7 @@ module.exports = function () { return merged.foobar; }; -},{"is-plain-obj":776}],1299:[function(require,module,exports){ +},{"is-plain-obj":615}],1128:[function(require,module,exports){ var bn = require('bn.js'); var brorand = require('brorand'); @@ -147499,8046 +121664,7 @@ MillerRabin.prototype.getDivisor = function getDivisor(n, k) { return false; }; -},{"bn.js":171,"brorand":181}],1300:[function(require,module,exports){ -module.exports={ - "application/1d-interleaved-parityfec": { - "source": "iana" - }, - "application/3gpdash-qoe-report+xml": { - "source": "iana", - "compressible": true - }, - "application/3gpp-ims+xml": { - "source": "iana", - "compressible": true - }, - "application/a2l": { - "source": "iana" - }, - "application/activemessage": { - "source": "iana" - }, - "application/activity+json": { - "source": "iana", - "compressible": true - }, - "application/alto-costmap+json": { - "source": "iana", - "compressible": true - }, - "application/alto-costmapfilter+json": { - "source": "iana", - "compressible": true - }, - "application/alto-directory+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointcost+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointcostparams+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointprop+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointpropparams+json": { - "source": "iana", - "compressible": true - }, - "application/alto-error+json": { - "source": "iana", - "compressible": true - }, - "application/alto-networkmap+json": { - "source": "iana", - "compressible": true - }, - "application/alto-networkmapfilter+json": { - "source": "iana", - "compressible": true - }, - "application/aml": { - "source": "iana" - }, - "application/andrew-inset": { - "source": "iana", - "extensions": ["ez"] - }, - "application/applefile": { - "source": "iana" - }, - "application/applixware": { - "source": "apache", - "extensions": ["aw"] - }, - "application/atf": { - "source": "iana" - }, - "application/atfx": { - "source": "iana" - }, - "application/atom+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atom"] - }, - "application/atomcat+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atomcat"] - }, - "application/atomdeleted+xml": { - "source": "iana", - "compressible": true - }, - "application/atomicmail": { - "source": "iana" - }, - "application/atomsvc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atomsvc"] - }, - "application/atsc-dwd+xml": { - "source": "iana", - "compressible": true - }, - "application/atsc-held+xml": { - "source": "iana", - "compressible": true - }, - "application/atsc-rsat+xml": { - "source": "iana", - "compressible": true - }, - "application/atxml": { - "source": "iana" - }, - "application/auth-policy+xml": { - "source": "iana", - "compressible": true - }, - "application/bacnet-xdd+zip": { - "source": "iana", - "compressible": false - }, - "application/batch-smtp": { - "source": "iana" - }, - "application/bdoc": { - "compressible": false, - "extensions": ["bdoc"] - }, - "application/beep+xml": { - "source": "iana", - "compressible": true - }, - "application/calendar+json": { - "source": "iana", - "compressible": true - }, - "application/calendar+xml": { - "source": "iana", - "compressible": true - }, - "application/call-completion": { - "source": "iana" - }, - "application/cals-1840": { - "source": "iana" - }, - "application/cbor": { - "source": "iana" - }, - "application/cccex": { - "source": "iana" - }, - "application/ccmp+xml": { - "source": "iana", - "compressible": true - }, - "application/ccxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ccxml"] - }, - "application/cdfx+xml": { - "source": "iana", - "compressible": true - }, - "application/cdmi-capability": { - "source": "iana", - "extensions": ["cdmia"] - }, - "application/cdmi-container": { - "source": "iana", - "extensions": ["cdmic"] - }, - "application/cdmi-domain": { - "source": "iana", - "extensions": ["cdmid"] - }, - "application/cdmi-object": { - "source": "iana", - "extensions": ["cdmio"] - }, - "application/cdmi-queue": { - "source": "iana", - "extensions": ["cdmiq"] - }, - "application/cdni": { - "source": "iana" - }, - "application/cea": { - "source": "iana" - }, - "application/cea-2018+xml": { - "source": "iana", - "compressible": true - }, - "application/cellml+xml": { - "source": "iana", - "compressible": true - }, - "application/cfw": { - "source": "iana" - }, - "application/clue_info+xml": { - "source": "iana", - "compressible": true - }, - "application/cms": { - "source": "iana" - }, - "application/cnrp+xml": { - "source": "iana", - "compressible": true - }, - "application/coap-group+json": { - "source": "iana", - "compressible": true - }, - "application/coap-payload": { - "source": "iana" - }, - "application/commonground": { - "source": "iana" - }, - "application/conference-info+xml": { - "source": "iana", - "compressible": true - }, - "application/cose": { - "source": "iana" - }, - "application/cose-key": { - "source": "iana" - }, - "application/cose-key-set": { - "source": "iana" - }, - "application/cpl+xml": { - "source": "iana", - "compressible": true - }, - "application/csrattrs": { - "source": "iana" - }, - "application/csta+xml": { - "source": "iana", - "compressible": true - }, - "application/cstadata+xml": { - "source": "iana", - "compressible": true - }, - "application/csvm+json": { - "source": "iana", - "compressible": true - }, - "application/cu-seeme": { - "source": "apache", - "extensions": ["cu"] - }, - "application/cwt": { - "source": "iana" - }, - "application/cybercash": { - "source": "iana" - }, - "application/dart": { - "compressible": true - }, - "application/dash+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mpd"] - }, - "application/dashdelta": { - "source": "iana" - }, - "application/davmount+xml": { - "source": "iana", - "compressible": true, - "extensions": ["davmount"] - }, - "application/dca-rft": { - "source": "iana" - }, - "application/dcd": { - "source": "iana" - }, - "application/dec-dx": { - "source": "iana" - }, - "application/dialog-info+xml": { - "source": "iana", - "compressible": true - }, - "application/dicom": { - "source": "iana" - }, - "application/dicom+json": { - "source": "iana", - "compressible": true - }, - "application/dicom+xml": { - "source": "iana", - "compressible": true - }, - "application/dii": { - "source": "iana" - }, - "application/dit": { - "source": "iana" - }, - "application/dns": { - "source": "iana" - }, - "application/dns+json": { - "source": "iana", - "compressible": true - }, - "application/dns-message": { - "source": "iana" - }, - "application/docbook+xml": { - "source": "apache", - "compressible": true, - "extensions": ["dbk"] - }, - "application/dskpp+xml": { - "source": "iana", - "compressible": true - }, - "application/dssc+der": { - "source": "iana", - "extensions": ["dssc"] - }, - "application/dssc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdssc"] - }, - "application/dvcs": { - "source": "iana" - }, - "application/ecmascript": { - "source": "iana", - "compressible": true, - "extensions": ["ecma","es"] - }, - "application/edi-consent": { - "source": "iana" - }, - "application/edi-x12": { - "source": "iana", - "compressible": false - }, - "application/edifact": { - "source": "iana", - "compressible": false - }, - "application/efi": { - "source": "iana" - }, - "application/emergencycalldata.comment+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.control+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.deviceinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.ecall.msd": { - "source": "iana" - }, - "application/emergencycalldata.providerinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.serviceinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.subscriberinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.veds+xml": { - "source": "iana", - "compressible": true - }, - "application/emma+xml": { - "source": "iana", - "compressible": true, - "extensions": ["emma"] - }, - "application/emotionml+xml": { - "source": "iana", - "compressible": true - }, - "application/encaprtp": { - "source": "iana" - }, - "application/epp+xml": { - "source": "iana", - "compressible": true - }, - "application/epub+zip": { - "source": "iana", - "compressible": false, - "extensions": ["epub"] - }, - "application/eshop": { - "source": "iana" - }, - "application/exi": { - "source": "iana", - "extensions": ["exi"] - }, - "application/expect-ct-report+json": { - "source": "iana", - "compressible": true - }, - "application/fastinfoset": { - "source": "iana" - }, - "application/fastsoap": { - "source": "iana" - }, - "application/fdt+xml": { - "source": "iana", - "compressible": true - }, - "application/fhir+json": { - "source": "iana", - "compressible": true - }, - "application/fhir+xml": { - "source": "iana", - "compressible": true - }, - "application/fido.trusted-apps+json": { - "compressible": true - }, - "application/fits": { - "source": "iana" - }, - "application/font-sfnt": { - "source": "iana" - }, - "application/font-tdpfr": { - "source": "iana", - "extensions": ["pfr"] - }, - "application/font-woff": { - "source": "iana", - "compressible": false - }, - "application/framework-attributes+xml": { - "source": "iana", - "compressible": true - }, - "application/geo+json": { - "source": "iana", - "compressible": true, - "extensions": ["geojson"] - }, - "application/geo+json-seq": { - "source": "iana" - }, - "application/geopackage+sqlite3": { - "source": "iana" - }, - "application/geoxacml+xml": { - "source": "iana", - "compressible": true - }, - "application/gltf-buffer": { - "source": "iana" - }, - "application/gml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["gml"] - }, - "application/gpx+xml": { - "source": "apache", - "compressible": true, - "extensions": ["gpx"] - }, - "application/gxf": { - "source": "apache", - "extensions": ["gxf"] - }, - "application/gzip": { - "source": "iana", - "compressible": false, - "extensions": ["gz"] - }, - "application/h224": { - "source": "iana" - }, - "application/held+xml": { - "source": "iana", - "compressible": true - }, - "application/hjson": { - "extensions": ["hjson"] - }, - "application/http": { - "source": "iana" - }, - "application/hyperstudio": { - "source": "iana", - "extensions": ["stk"] - }, - "application/ibe-key-request+xml": { - "source": "iana", - "compressible": true - }, - "application/ibe-pkg-reply+xml": { - "source": "iana", - "compressible": true - }, - "application/ibe-pp-data": { - "source": "iana" - }, - "application/iges": { - "source": "iana" - }, - "application/im-iscomposing+xml": { - "source": "iana", - "compressible": true - }, - "application/index": { - "source": "iana" - }, - "application/index.cmd": { - "source": "iana" - }, - "application/index.obj": { - "source": "iana" - }, - "application/index.response": { - "source": "iana" - }, - "application/index.vnd": { - "source": "iana" - }, - "application/inkml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ink","inkml"] - }, - "application/iotp": { - "source": "iana" - }, - "application/ipfix": { - "source": "iana", - "extensions": ["ipfix"] - }, - "application/ipp": { - "source": "iana" - }, - "application/isup": { - "source": "iana" - }, - "application/its+xml": { - "source": "iana", - "compressible": true - }, - "application/java-archive": { - "source": "apache", - "compressible": false, - "extensions": ["jar","war","ear"] - }, - "application/java-serialized-object": { - "source": "apache", - "compressible": false, - "extensions": ["ser"] - }, - "application/java-vm": { - "source": "apache", - "compressible": false, - "extensions": ["class"] - }, - "application/javascript": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["js","mjs"] - }, - "application/jf2feed+json": { - "source": "iana", - "compressible": true - }, - "application/jose": { - "source": "iana" - }, - "application/jose+json": { - "source": "iana", - "compressible": true - }, - "application/jrd+json": { - "source": "iana", - "compressible": true - }, - "application/json": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["json","map"] - }, - "application/json-patch+json": { - "source": "iana", - "compressible": true - }, - "application/json-seq": { - "source": "iana" - }, - "application/json5": { - "extensions": ["json5"] - }, - "application/jsonml+json": { - "source": "apache", - "compressible": true, - "extensions": ["jsonml"] - }, - "application/jwk+json": { - "source": "iana", - "compressible": true - }, - "application/jwk-set+json": { - "source": "iana", - "compressible": true - }, - "application/jwt": { - "source": "iana" - }, - "application/kpml-request+xml": { - "source": "iana", - "compressible": true - }, - "application/kpml-response+xml": { - "source": "iana", - "compressible": true - }, - "application/ld+json": { - "source": "iana", - "compressible": true, - "extensions": ["jsonld"] - }, - "application/lgr+xml": { - "source": "iana", - "compressible": true - }, - "application/link-format": { - "source": "iana" - }, - "application/load-control+xml": { - "source": "iana", - "compressible": true - }, - "application/lost+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lostxml"] - }, - "application/lostsync+xml": { - "source": "iana", - "compressible": true - }, - "application/lxf": { - "source": "iana" - }, - "application/mac-binhex40": { - "source": "iana", - "extensions": ["hqx"] - }, - "application/mac-compactpro": { - "source": "apache", - "extensions": ["cpt"] - }, - "application/macwriteii": { - "source": "iana" - }, - "application/mads+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mads"] - }, - "application/manifest+json": { - "charset": "UTF-8", - "compressible": true, - "extensions": ["webmanifest"] - }, - "application/marc": { - "source": "iana", - "extensions": ["mrc"] - }, - "application/marcxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mrcx"] - }, - "application/mathematica": { - "source": "iana", - "extensions": ["ma","nb","mb"] - }, - "application/mathml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mathml"] - }, - "application/mathml-content+xml": { - "source": "iana", - "compressible": true - }, - "application/mathml-presentation+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-associated-procedure-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-deregister+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-envelope+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-msk+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-msk-response+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-protection-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-reception-report+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-register+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-register-response+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-schedule+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-user-service-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbox": { - "source": "iana", - "extensions": ["mbox"] - }, - "application/media-policy-dataset+xml": { - "source": "iana", - "compressible": true - }, - "application/media_control+xml": { - "source": "iana", - "compressible": true - }, - "application/mediaservercontrol+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mscml"] - }, - "application/merge-patch+json": { - "source": "iana", - "compressible": true - }, - "application/metalink+xml": { - "source": "apache", - "compressible": true, - "extensions": ["metalink"] - }, - "application/metalink4+xml": { - "source": "iana", - "compressible": true, - "extensions": ["meta4"] - }, - "application/mets+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mets"] - }, - "application/mf4": { - "source": "iana" - }, - "application/mikey": { - "source": "iana" - }, - "application/mmt-aei+xml": { - "source": "iana", - "compressible": true - }, - "application/mmt-usd+xml": { - "source": "iana", - "compressible": true - }, - "application/mods+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mods"] - }, - "application/moss-keys": { - "source": "iana" - }, - "application/moss-signature": { - "source": "iana" - }, - "application/mosskey-data": { - "source": "iana" - }, - "application/mosskey-request": { - "source": "iana" - }, - "application/mp21": { - "source": "iana", - "extensions": ["m21","mp21"] - }, - "application/mp4": { - "source": "iana", - "extensions": ["mp4s","m4p"] - }, - "application/mpeg4-generic": { - "source": "iana" - }, - "application/mpeg4-iod": { - "source": "iana" - }, - "application/mpeg4-iod-xmt": { - "source": "iana" - }, - "application/mrb-consumer+xml": { - "source": "iana", - "compressible": true - }, - "application/mrb-publish+xml": { - "source": "iana", - "compressible": true - }, - "application/msc-ivr+xml": { - "source": "iana", - "compressible": true - }, - "application/msc-mixer+xml": { - "source": "iana", - "compressible": true - }, - "application/msword": { - "source": "iana", - "compressible": false, - "extensions": ["doc","dot"] - }, - "application/mud+json": { - "source": "iana", - "compressible": true - }, - "application/mxf": { - "source": "iana", - "extensions": ["mxf"] - }, - "application/n-quads": { - "source": "iana", - "extensions": ["nq"] - }, - "application/n-triples": { - "source": "iana", - "extensions": ["nt"] - }, - "application/nasdata": { - "source": "iana" - }, - "application/news-checkgroups": { - "source": "iana" - }, - "application/news-groupinfo": { - "source": "iana" - }, - "application/news-transmission": { - "source": "iana" - }, - "application/nlsml+xml": { - "source": "iana", - "compressible": true - }, - "application/node": { - "source": "iana" - }, - "application/nss": { - "source": "iana" - }, - "application/ocsp-request": { - "source": "iana" - }, - "application/ocsp-response": { - "source": "iana" - }, - "application/octet-stream": { - "source": "iana", - "compressible": false, - "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] - }, - "application/oda": { - "source": "iana", - "extensions": ["oda"] - }, - "application/odm+xml": { - "source": "iana", - "compressible": true - }, - "application/odx": { - "source": "iana" - }, - "application/oebps-package+xml": { - "source": "iana", - "compressible": true, - "extensions": ["opf"] - }, - "application/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["ogx"] - }, - "application/omdoc+xml": { - "source": "apache", - "compressible": true, - "extensions": ["omdoc"] - }, - "application/onenote": { - "source": "apache", - "extensions": ["onetoc","onetoc2","onetmp","onepkg"] - }, - "application/oscore": { - "source": "iana" - }, - "application/oxps": { - "source": "iana", - "extensions": ["oxps"] - }, - "application/p2p-overlay+xml": { - "source": "iana", - "compressible": true - }, - "application/parityfec": { - "source": "iana" - }, - "application/passport": { - "source": "iana" - }, - "application/patch-ops-error+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xer"] - }, - "application/pdf": { - "source": "iana", - "compressible": false, - "extensions": ["pdf"] - }, - "application/pdx": { - "source": "iana" - }, - "application/pem-certificate-chain": { - "source": "iana" - }, - "application/pgp-encrypted": { - "source": "iana", - "compressible": false, - "extensions": ["pgp"] - }, - "application/pgp-keys": { - "source": "iana" - }, - "application/pgp-signature": { - "source": "iana", - "extensions": ["asc","sig"] - }, - "application/pics-rules": { - "source": "apache", - "extensions": ["prf"] - }, - "application/pidf+xml": { - "source": "iana", - "compressible": true - }, - "application/pidf-diff+xml": { - "source": "iana", - "compressible": true - }, - "application/pkcs10": { - "source": "iana", - "extensions": ["p10"] - }, - "application/pkcs12": { - "source": "iana" - }, - "application/pkcs7-mime": { - "source": "iana", - "extensions": ["p7m","p7c"] - }, - "application/pkcs7-signature": { - "source": "iana", - "extensions": ["p7s"] - }, - "application/pkcs8": { - "source": "iana", - "extensions": ["p8"] - }, - "application/pkcs8-encrypted": { - "source": "iana" - }, - "application/pkix-attr-cert": { - "source": "iana", - "extensions": ["ac"] - }, - "application/pkix-cert": { - "source": "iana", - "extensions": ["cer"] - }, - "application/pkix-crl": { - "source": "iana", - "extensions": ["crl"] - }, - "application/pkix-pkipath": { - "source": "iana", - "extensions": ["pkipath"] - }, - "application/pkixcmp": { - "source": "iana", - "extensions": ["pki"] - }, - "application/pls+xml": { - "source": "iana", - "compressible": true, - "extensions": ["pls"] - }, - "application/poc-settings+xml": { - "source": "iana", - "compressible": true - }, - "application/postscript": { - "source": "iana", - "compressible": true, - "extensions": ["ai","eps","ps"] - }, - "application/ppsp-tracker+json": { - "source": "iana", - "compressible": true - }, - "application/problem+json": { - "source": "iana", - "compressible": true - }, - "application/problem+xml": { - "source": "iana", - "compressible": true - }, - "application/provenance+xml": { - "source": "iana", - "compressible": true - }, - "application/prs.alvestrand.titrax-sheet": { - "source": "iana" - }, - "application/prs.cww": { - "source": "iana", - "extensions": ["cww"] - }, - "application/prs.hpub+zip": { - "source": "iana", - "compressible": false - }, - "application/prs.nprend": { - "source": "iana" - }, - "application/prs.plucker": { - "source": "iana" - }, - "application/prs.rdf-xml-crypt": { - "source": "iana" - }, - "application/prs.xsf+xml": { - "source": "iana", - "compressible": true - }, - "application/pskc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["pskcxml"] - }, - "application/qsig": { - "source": "iana" - }, - "application/raml+yaml": { - "compressible": true, - "extensions": ["raml"] - }, - "application/raptorfec": { - "source": "iana" - }, - "application/rdap+json": { - "source": "iana", - "compressible": true - }, - "application/rdf+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rdf","owl"] - }, - "application/reginfo+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rif"] - }, - "application/relax-ng-compact-syntax": { - "source": "iana", - "extensions": ["rnc"] - }, - "application/remote-printing": { - "source": "iana" - }, - "application/reputon+json": { - "source": "iana", - "compressible": true - }, - "application/resource-lists+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rl"] - }, - "application/resource-lists-diff+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rld"] - }, - "application/rfc+xml": { - "source": "iana", - "compressible": true - }, - "application/riscos": { - "source": "iana" - }, - "application/rlmi+xml": { - "source": "iana", - "compressible": true - }, - "application/rls-services+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rs"] - }, - "application/route-apd+xml": { - "source": "iana", - "compressible": true - }, - "application/route-s-tsid+xml": { - "source": "iana", - "compressible": true - }, - "application/route-usd+xml": { - "source": "iana", - "compressible": true - }, - "application/rpki-ghostbusters": { - "source": "iana", - "extensions": ["gbr"] - }, - "application/rpki-manifest": { - "source": "iana", - "extensions": ["mft"] - }, - "application/rpki-publication": { - "source": "iana" - }, - "application/rpki-roa": { - "source": "iana", - "extensions": ["roa"] - }, - "application/rpki-updown": { - "source": "iana" - }, - "application/rsd+xml": { - "source": "apache", - "compressible": true, - "extensions": ["rsd"] - }, - "application/rss+xml": { - "source": "apache", - "compressible": true, - "extensions": ["rss"] - }, - "application/rtf": { - "source": "iana", - "compressible": true, - "extensions": ["rtf"] - }, - "application/rtploopback": { - "source": "iana" - }, - "application/rtx": { - "source": "iana" - }, - "application/samlassertion+xml": { - "source": "iana", - "compressible": true - }, - "application/samlmetadata+xml": { - "source": "iana", - "compressible": true - }, - "application/sbml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sbml"] - }, - "application/scaip+xml": { - "source": "iana", - "compressible": true - }, - "application/scim+json": { - "source": "iana", - "compressible": true - }, - "application/scvp-cv-request": { - "source": "iana", - "extensions": ["scq"] - }, - "application/scvp-cv-response": { - "source": "iana", - "extensions": ["scs"] - }, - "application/scvp-vp-request": { - "source": "iana", - "extensions": ["spq"] - }, - "application/scvp-vp-response": { - "source": "iana", - "extensions": ["spp"] - }, - "application/sdp": { - "source": "iana", - "extensions": ["sdp"] - }, - "application/secevent+jwt": { - "source": "iana" - }, - "application/senml+cbor": { - "source": "iana" - }, - "application/senml+json": { - "source": "iana", - "compressible": true - }, - "application/senml+xml": { - "source": "iana", - "compressible": true - }, - "application/senml-exi": { - "source": "iana" - }, - "application/sensml+cbor": { - "source": "iana" - }, - "application/sensml+json": { - "source": "iana", - "compressible": true - }, - "application/sensml+xml": { - "source": "iana", - "compressible": true - }, - "application/sensml-exi": { - "source": "iana" - }, - "application/sep+xml": { - "source": "iana", - "compressible": true - }, - "application/sep-exi": { - "source": "iana" - }, - "application/session-info": { - "source": "iana" - }, - "application/set-payment": { - "source": "iana" - }, - "application/set-payment-initiation": { - "source": "iana", - "extensions": ["setpay"] - }, - "application/set-registration": { - "source": "iana" - }, - "application/set-registration-initiation": { - "source": "iana", - "extensions": ["setreg"] - }, - "application/sgml": { - "source": "iana" - }, - "application/sgml-open-catalog": { - "source": "iana" - }, - "application/shf+xml": { - "source": "iana", - "compressible": true, - "extensions": ["shf"] - }, - "application/sieve": { - "source": "iana", - "extensions": ["siv","sieve"] - }, - "application/simple-filter+xml": { - "source": "iana", - "compressible": true - }, - "application/simple-message-summary": { - "source": "iana" - }, - "application/simplesymbolcontainer": { - "source": "iana" - }, - "application/slate": { - "source": "iana" - }, - "application/smil": { - "source": "iana" - }, - "application/smil+xml": { - "source": "iana", - "compressible": true, - "extensions": ["smi","smil"] - }, - "application/smpte336m": { - "source": "iana" - }, - "application/soap+fastinfoset": { - "source": "iana" - }, - "application/soap+xml": { - "source": "iana", - "compressible": true - }, - "application/sparql-query": { - "source": "iana", - "extensions": ["rq"] - }, - "application/sparql-results+xml": { - "source": "iana", - "compressible": true, - "extensions": ["srx"] - }, - "application/spirits-event+xml": { - "source": "iana", - "compressible": true - }, - "application/sql": { - "source": "iana" - }, - "application/srgs": { - "source": "iana", - "extensions": ["gram"] - }, - "application/srgs+xml": { - "source": "iana", - "compressible": true, - "extensions": ["grxml"] - }, - "application/sru+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sru"] - }, - "application/ssdl+xml": { - "source": "apache", - "compressible": true, - "extensions": ["ssdl"] - }, - "application/ssml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ssml"] - }, - "application/stix+json": { - "source": "iana", - "compressible": true - }, - "application/tamp-apex-update": { - "source": "iana" - }, - "application/tamp-apex-update-confirm": { - "source": "iana" - }, - "application/tamp-community-update": { - "source": "iana" - }, - "application/tamp-community-update-confirm": { - "source": "iana" - }, - "application/tamp-error": { - "source": "iana" - }, - "application/tamp-sequence-adjust": { - "source": "iana" - }, - "application/tamp-sequence-adjust-confirm": { - "source": "iana" - }, - "application/tamp-status-query": { - "source": "iana" - }, - "application/tamp-status-response": { - "source": "iana" - }, - "application/tamp-update": { - "source": "iana" - }, - "application/tamp-update-confirm": { - "source": "iana" - }, - "application/tar": { - "compressible": true - }, - "application/taxii+json": { - "source": "iana", - "compressible": true - }, - "application/tei+xml": { - "source": "iana", - "compressible": true, - "extensions": ["tei","teicorpus"] - }, - "application/tetra_isi": { - "source": "iana" - }, - "application/thraud+xml": { - "source": "iana", - "compressible": true, - "extensions": ["tfi"] - }, - "application/timestamp-query": { - "source": "iana" - }, - "application/timestamp-reply": { - "source": "iana" - }, - "application/timestamped-data": { - "source": "iana", - "extensions": ["tsd"] - }, - "application/tlsrpt+gzip": { - "source": "iana" - }, - "application/tlsrpt+json": { - "source": "iana", - "compressible": true - }, - "application/tnauthlist": { - "source": "iana" - }, - "application/trickle-ice-sdpfrag": { - "source": "iana" - }, - "application/trig": { - "source": "iana" - }, - "application/ttml+xml": { - "source": "iana", - "compressible": true - }, - "application/tve-trigger": { - "source": "iana" - }, - "application/tzif": { - "source": "iana" - }, - "application/tzif-leap": { - "source": "iana" - }, - "application/ulpfec": { - "source": "iana" - }, - "application/urc-grpsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/urc-ressheet+xml": { - "source": "iana", - "compressible": true - }, - "application/urc-targetdesc+xml": { - "source": "iana", - "compressible": true - }, - "application/urc-uisocketdesc+xml": { - "source": "iana", - "compressible": true - }, - "application/vcard+json": { - "source": "iana", - "compressible": true - }, - "application/vcard+xml": { - "source": "iana", - "compressible": true - }, - "application/vemmi": { - "source": "iana" - }, - "application/vividence.scriptfile": { - "source": "apache" - }, - "application/vnd.1000minds.decision-model+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp-prose+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp-prose-pc3ch+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp-v2x-local-service-information": { - "source": "iana" - }, - "application/vnd.3gpp.access-transfer-events+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.bsf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.gmop+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mc-signalling-ear": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-payload": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-signalling": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-floor-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-location-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-signed+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-affiliation-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-location-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mid-call+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.pic-bw-large": { - "source": "iana", - "extensions": ["plb"] - }, - "application/vnd.3gpp.pic-bw-small": { - "source": "iana", - "extensions": ["psb"] - }, - "application/vnd.3gpp.pic-bw-var": { - "source": "iana", - "extensions": ["pvb"] - }, - "application/vnd.3gpp.sms": { - "source": "iana" - }, - "application/vnd.3gpp.sms+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.srvcc-ext+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.srvcc-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.state-and-event-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.ussd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp2.bcmcsinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp2.sms": { - "source": "iana" - }, - "application/vnd.3gpp2.tcap": { - "source": "iana", - "extensions": ["tcap"] - }, - "application/vnd.3lightssoftware.imagescal": { - "source": "iana" - }, - "application/vnd.3m.post-it-notes": { - "source": "iana", - "extensions": ["pwn"] - }, - "application/vnd.accpac.simply.aso": { - "source": "iana", - "extensions": ["aso"] - }, - "application/vnd.accpac.simply.imp": { - "source": "iana", - "extensions": ["imp"] - }, - "application/vnd.acucobol": { - "source": "iana", - "extensions": ["acu"] - }, - "application/vnd.acucorp": { - "source": "iana", - "extensions": ["atc","acutc"] - }, - "application/vnd.adobe.air-application-installer-package+zip": { - "source": "apache", - "compressible": false, - "extensions": ["air"] - }, - "application/vnd.adobe.flash.movie": { - "source": "iana" - }, - "application/vnd.adobe.formscentral.fcdt": { - "source": "iana", - "extensions": ["fcdt"] - }, - "application/vnd.adobe.fxp": { - "source": "iana", - "extensions": ["fxp","fxpl"] - }, - "application/vnd.adobe.partial-upload": { - "source": "iana" - }, - "application/vnd.adobe.xdp+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdp"] - }, - "application/vnd.adobe.xfdf": { - "source": "iana", - "extensions": ["xfdf"] - }, - "application/vnd.aether.imp": { - "source": "iana" - }, - "application/vnd.afpc.afplinedata": { - "source": "iana" - }, - "application/vnd.afpc.modca": { - "source": "iana" - }, - "application/vnd.ah-barcode": { - "source": "iana" - }, - "application/vnd.ahead.space": { - "source": "iana", - "extensions": ["ahead"] - }, - "application/vnd.airzip.filesecure.azf": { - "source": "iana", - "extensions": ["azf"] - }, - "application/vnd.airzip.filesecure.azs": { - "source": "iana", - "extensions": ["azs"] - }, - "application/vnd.amadeus+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.amazon.ebook": { - "source": "apache", - "extensions": ["azw"] - }, - "application/vnd.amazon.mobi8-ebook": { - "source": "iana" - }, - "application/vnd.americandynamics.acc": { - "source": "iana", - "extensions": ["acc"] - }, - "application/vnd.amiga.ami": { - "source": "iana", - "extensions": ["ami"] - }, - "application/vnd.amundsen.maze+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.android.package-archive": { - "source": "apache", - "compressible": false, - "extensions": ["apk"] - }, - "application/vnd.anki": { - "source": "iana" - }, - "application/vnd.anser-web-certificate-issue-initiation": { - "source": "iana", - "extensions": ["cii"] - }, - "application/vnd.anser-web-funds-transfer-initiation": { - "source": "apache", - "extensions": ["fti"] - }, - "application/vnd.antix.game-component": { - "source": "iana", - "extensions": ["atx"] - }, - "application/vnd.apache.thrift.binary": { - "source": "iana" - }, - "application/vnd.apache.thrift.compact": { - "source": "iana" - }, - "application/vnd.apache.thrift.json": { - "source": "iana" - }, - "application/vnd.api+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.apothekende.reservation+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.apple.installer+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mpkg"] - }, - "application/vnd.apple.keynote": { - "source": "iana", - "extensions": ["keynote"] - }, - "application/vnd.apple.mpegurl": { - "source": "iana", - "extensions": ["m3u8"] - }, - "application/vnd.apple.numbers": { - "source": "iana", - "extensions": ["numbers"] - }, - "application/vnd.apple.pages": { - "source": "iana", - "extensions": ["pages"] - }, - "application/vnd.apple.pkpass": { - "compressible": false, - "extensions": ["pkpass"] - }, - "application/vnd.arastra.swi": { - "source": "iana" - }, - "application/vnd.aristanetworks.swi": { - "source": "iana", - "extensions": ["swi"] - }, - "application/vnd.artisan+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.artsquare": { - "source": "iana" - }, - "application/vnd.astraea-software.iota": { - "source": "iana", - "extensions": ["iota"] - }, - "application/vnd.audiograph": { - "source": "iana", - "extensions": ["aep"] - }, - "application/vnd.autopackage": { - "source": "iana" - }, - "application/vnd.avalon+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.avistar+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.balsamiq.bmml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.balsamiq.bmpr": { - "source": "iana" - }, - "application/vnd.banana-accounting": { - "source": "iana" - }, - "application/vnd.bbf.usp.msg": { - "source": "iana" - }, - "application/vnd.bbf.usp.msg+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.bekitzur-stech+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.bint.med-content": { - "source": "iana" - }, - "application/vnd.biopax.rdf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.blink-idb-value-wrapper": { - "source": "iana" - }, - "application/vnd.blueice.multipass": { - "source": "iana", - "extensions": ["mpm"] - }, - "application/vnd.bluetooth.ep.oob": { - "source": "iana" - }, - "application/vnd.bluetooth.le.oob": { - "source": "iana" - }, - "application/vnd.bmi": { - "source": "iana", - "extensions": ["bmi"] - }, - "application/vnd.businessobjects": { - "source": "iana", - "extensions": ["rep"] - }, - "application/vnd.byu.uapi+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cab-jscript": { - "source": "iana" - }, - "application/vnd.canon-cpdl": { - "source": "iana" - }, - "application/vnd.canon-lips": { - "source": "iana" - }, - "application/vnd.capasystems-pg+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cendio.thinlinc.clientconf": { - "source": "iana" - }, - "application/vnd.century-systems.tcp_stream": { - "source": "iana" - }, - "application/vnd.chemdraw+xml": { - "source": "iana", - "compressible": true, - "extensions": ["cdxml"] - }, - "application/vnd.chess-pgn": { - "source": "iana" - }, - "application/vnd.chipnuts.karaoke-mmd": { - "source": "iana", - "extensions": ["mmd"] - }, - "application/vnd.cinderella": { - "source": "iana", - "extensions": ["cdy"] - }, - "application/vnd.cirpack.isdn-ext": { - "source": "iana" - }, - "application/vnd.citationstyles.style+xml": { - "source": "iana", - "compressible": true, - "extensions": ["csl"] - }, - "application/vnd.claymore": { - "source": "iana", - "extensions": ["cla"] - }, - "application/vnd.cloanto.rp9": { - "source": "iana", - "extensions": ["rp9"] - }, - "application/vnd.clonk.c4group": { - "source": "iana", - "extensions": ["c4g","c4d","c4f","c4p","c4u"] - }, - "application/vnd.cluetrust.cartomobile-config": { - "source": "iana", - "extensions": ["c11amc"] - }, - "application/vnd.cluetrust.cartomobile-config-pkg": { - "source": "iana", - "extensions": ["c11amz"] - }, - "application/vnd.coffeescript": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.document": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.document-template": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.presentation": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.presentation-template": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - "source": "iana" - }, - "application/vnd.collection+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.collection.doc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.collection.next+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.comicbook+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.comicbook-rar": { - "source": "iana" - }, - "application/vnd.commerce-battelle": { - "source": "iana" - }, - "application/vnd.commonspace": { - "source": "iana", - "extensions": ["csp"] - }, - "application/vnd.contact.cmsg": { - "source": "iana", - "extensions": ["cdbcmsg"] - }, - "application/vnd.coreos.ignition+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cosmocaller": { - "source": "iana", - "extensions": ["cmc"] - }, - "application/vnd.crick.clicker": { - "source": "iana", - "extensions": ["clkx"] - }, - "application/vnd.crick.clicker.keyboard": { - "source": "iana", - "extensions": ["clkk"] - }, - "application/vnd.crick.clicker.palette": { - "source": "iana", - "extensions": ["clkp"] - }, - "application/vnd.crick.clicker.template": { - "source": "iana", - "extensions": ["clkt"] - }, - "application/vnd.crick.clicker.wordbank": { - "source": "iana", - "extensions": ["clkw"] - }, - "application/vnd.criticaltools.wbs+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wbs"] - }, - "application/vnd.ctc-posml": { - "source": "iana", - "extensions": ["pml"] - }, - "application/vnd.ctct.ws+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.cups-pdf": { - "source": "iana" - }, - "application/vnd.cups-postscript": { - "source": "iana" - }, - "application/vnd.cups-ppd": { - "source": "iana", - "extensions": ["ppd"] - }, - "application/vnd.cups-raster": { - "source": "iana" - }, - "application/vnd.cups-raw": { - "source": "iana" - }, - "application/vnd.curl": { - "source": "iana" - }, - "application/vnd.curl.car": { - "source": "apache", - "extensions": ["car"] - }, - "application/vnd.curl.pcurl": { - "source": "apache", - "extensions": ["pcurl"] - }, - "application/vnd.cyan.dean.root+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.cybank": { - "source": "iana" - }, - "application/vnd.d2l.coursepackage1p0+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.dart": { - "source": "iana", - "compressible": true, - "extensions": ["dart"] - }, - "application/vnd.data-vision.rdz": { - "source": "iana", - "extensions": ["rdz"] - }, - "application/vnd.datapackage+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.dataresource+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.debian.binary-package": { - "source": "iana" - }, - "application/vnd.dece.data": { - "source": "iana", - "extensions": ["uvf","uvvf","uvd","uvvd"] - }, - "application/vnd.dece.ttml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["uvt","uvvt"] - }, - "application/vnd.dece.unspecified": { - "source": "iana", - "extensions": ["uvx","uvvx"] - }, - "application/vnd.dece.zip": { - "source": "iana", - "extensions": ["uvz","uvvz"] - }, - "application/vnd.denovo.fcselayout-link": { - "source": "iana", - "extensions": ["fe_launch"] - }, - "application/vnd.desmume.movie": { - "source": "iana" - }, - "application/vnd.dir-bi.plate-dl-nosuffix": { - "source": "iana" - }, - "application/vnd.dm.delegation+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dna": { - "source": "iana", - "extensions": ["dna"] - }, - "application/vnd.document+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.dolby.mlp": { - "source": "apache", - "extensions": ["mlp"] - }, - "application/vnd.dolby.mobile.1": { - "source": "iana" - }, - "application/vnd.dolby.mobile.2": { - "source": "iana" - }, - "application/vnd.doremir.scorecloud-binary-document": { - "source": "iana" - }, - "application/vnd.dpgraph": { - "source": "iana", - "extensions": ["dpg"] - }, - "application/vnd.dreamfactory": { - "source": "iana", - "extensions": ["dfac"] - }, - "application/vnd.drive+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ds-keypoint": { - "source": "apache", - "extensions": ["kpxx"] - }, - "application/vnd.dtg.local": { - "source": "iana" - }, - "application/vnd.dtg.local.flash": { - "source": "iana" - }, - "application/vnd.dtg.local.html": { - "source": "iana" - }, - "application/vnd.dvb.ait": { - "source": "iana", - "extensions": ["ait"] - }, - "application/vnd.dvb.dvbj": { - "source": "iana" - }, - "application/vnd.dvb.esgcontainer": { - "source": "iana" - }, - "application/vnd.dvb.ipdcdftnotifaccess": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgaccess": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgaccess2": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgpdd": { - "source": "iana" - }, - "application/vnd.dvb.ipdcroaming": { - "source": "iana" - }, - "application/vnd.dvb.iptv.alfec-base": { - "source": "iana" - }, - "application/vnd.dvb.iptv.alfec-enhancement": { - "source": "iana" - }, - "application/vnd.dvb.notif-aggregate-root+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-container+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-generic+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-msglist+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-registration-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-registration-response+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-init+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.pfr": { - "source": "iana" - }, - "application/vnd.dvb.service": { - "source": "iana", - "extensions": ["svc"] - }, - "application/vnd.dxr": { - "source": "iana" - }, - "application/vnd.dynageo": { - "source": "iana", - "extensions": ["geo"] - }, - "application/vnd.dzr": { - "source": "iana" - }, - "application/vnd.easykaraoke.cdgdownload": { - "source": "iana" - }, - "application/vnd.ecdis-update": { - "source": "iana" - }, - "application/vnd.ecip.rlp": { - "source": "iana" - }, - "application/vnd.ecowin.chart": { - "source": "iana", - "extensions": ["mag"] - }, - "application/vnd.ecowin.filerequest": { - "source": "iana" - }, - "application/vnd.ecowin.fileupdate": { - "source": "iana" - }, - "application/vnd.ecowin.series": { - "source": "iana" - }, - "application/vnd.ecowin.seriesrequest": { - "source": "iana" - }, - "application/vnd.ecowin.seriesupdate": { - "source": "iana" - }, - "application/vnd.efi.img": { - "source": "iana" - }, - "application/vnd.efi.iso": { - "source": "iana" - }, - "application/vnd.emclient.accessrequest+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.enliven": { - "source": "iana", - "extensions": ["nml"] - }, - "application/vnd.enphase.envoy": { - "source": "iana" - }, - "application/vnd.eprints.data+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.epson.esf": { - "source": "iana", - "extensions": ["esf"] - }, - "application/vnd.epson.msf": { - "source": "iana", - "extensions": ["msf"] - }, - "application/vnd.epson.quickanime": { - "source": "iana", - "extensions": ["qam"] - }, - "application/vnd.epson.salt": { - "source": "iana", - "extensions": ["slt"] - }, - "application/vnd.epson.ssf": { - "source": "iana", - "extensions": ["ssf"] - }, - "application/vnd.ericsson.quickcall": { - "source": "iana" - }, - "application/vnd.espass-espass+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.eszigno3+xml": { - "source": "iana", - "compressible": true, - "extensions": ["es3","et3"] - }, - "application/vnd.etsi.aoc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.asic-e+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.etsi.asic-s+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.etsi.cug+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvcommand+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvdiscovery+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-bc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-cod+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-npvr+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvservice+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsync+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvueprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.mcid+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.mheg5": { - "source": "iana" - }, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.pstn+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.sci+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.simservs+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.timestamp-token": { - "source": "iana" - }, - "application/vnd.etsi.tsl+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.tsl.der": { - "source": "iana" - }, - "application/vnd.eudora.data": { - "source": "iana" - }, - "application/vnd.evolv.ecig.profile": { - "source": "iana" - }, - "application/vnd.evolv.ecig.settings": { - "source": "iana" - }, - "application/vnd.evolv.ecig.theme": { - "source": "iana" - }, - "application/vnd.exstream-empower+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.exstream-package": { - "source": "iana" - }, - "application/vnd.ezpix-album": { - "source": "iana", - "extensions": ["ez2"] - }, - "application/vnd.ezpix-package": { - "source": "iana", - "extensions": ["ez3"] - }, - "application/vnd.f-secure.mobile": { - "source": "iana" - }, - "application/vnd.fastcopy-disk-image": { - "source": "iana" - }, - "application/vnd.fdf": { - "source": "iana", - "extensions": ["fdf"] - }, - "application/vnd.fdsn.mseed": { - "source": "iana", - "extensions": ["mseed"] - }, - "application/vnd.fdsn.seed": { - "source": "iana", - "extensions": ["seed","dataless"] - }, - "application/vnd.ffsns": { - "source": "iana" - }, - "application/vnd.filmit.zfc": { - "source": "iana" - }, - "application/vnd.fints": { - "source": "iana" - }, - "application/vnd.firemonkeys.cloudcell": { - "source": "iana" - }, - "application/vnd.flographit": { - "source": "iana", - "extensions": ["gph"] - }, - "application/vnd.fluxtime.clip": { - "source": "iana", - "extensions": ["ftc"] - }, - "application/vnd.font-fontforge-sfd": { - "source": "iana" - }, - "application/vnd.framemaker": { - "source": "iana", - "extensions": ["fm","frame","maker","book"] - }, - "application/vnd.frogans.fnc": { - "source": "iana", - "extensions": ["fnc"] - }, - "application/vnd.frogans.ltf": { - "source": "iana", - "extensions": ["ltf"] - }, - "application/vnd.fsc.weblaunch": { - "source": "iana", - "extensions": ["fsc"] - }, - "application/vnd.fujitsu.oasys": { - "source": "iana", - "extensions": ["oas"] - }, - "application/vnd.fujitsu.oasys2": { - "source": "iana", - "extensions": ["oa2"] - }, - "application/vnd.fujitsu.oasys3": { - "source": "iana", - "extensions": ["oa3"] - }, - "application/vnd.fujitsu.oasysgp": { - "source": "iana", - "extensions": ["fg5"] - }, - "application/vnd.fujitsu.oasysprs": { - "source": "iana", - "extensions": ["bh2"] - }, - "application/vnd.fujixerox.art-ex": { - "source": "iana" - }, - "application/vnd.fujixerox.art4": { - "source": "iana" - }, - "application/vnd.fujixerox.ddd": { - "source": "iana", - "extensions": ["ddd"] - }, - "application/vnd.fujixerox.docuworks": { - "source": "iana", - "extensions": ["xdw"] - }, - "application/vnd.fujixerox.docuworks.binder": { - "source": "iana", - "extensions": ["xbd"] - }, - "application/vnd.fujixerox.docuworks.container": { - "source": "iana" - }, - "application/vnd.fujixerox.hbpl": { - "source": "iana" - }, - "application/vnd.fut-misnet": { - "source": "iana" - }, - "application/vnd.futoin+cbor": { - "source": "iana" - }, - "application/vnd.futoin+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.fuzzysheet": { - "source": "iana", - "extensions": ["fzs"] - }, - "application/vnd.genomatix.tuxedo": { - "source": "iana", - "extensions": ["txd"] - }, - "application/vnd.geo+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.geocube+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.geogebra.file": { - "source": "iana", - "extensions": ["ggb"] - }, - "application/vnd.geogebra.tool": { - "source": "iana", - "extensions": ["ggt"] - }, - "application/vnd.geometry-explorer": { - "source": "iana", - "extensions": ["gex","gre"] - }, - "application/vnd.geonext": { - "source": "iana", - "extensions": ["gxt"] - }, - "application/vnd.geoplan": { - "source": "iana", - "extensions": ["g2w"] - }, - "application/vnd.geospace": { - "source": "iana", - "extensions": ["g3w"] - }, - "application/vnd.gerber": { - "source": "iana" - }, - "application/vnd.globalplatform.card-content-mgt": { - "source": "iana" - }, - "application/vnd.globalplatform.card-content-mgt-response": { - "source": "iana" - }, - "application/vnd.gmx": { - "source": "iana", - "extensions": ["gmx"] - }, - "application/vnd.google-apps.document": { - "compressible": false, - "extensions": ["gdoc"] - }, - "application/vnd.google-apps.presentation": { - "compressible": false, - "extensions": ["gslides"] - }, - "application/vnd.google-apps.spreadsheet": { - "compressible": false, - "extensions": ["gsheet"] - }, - "application/vnd.google-earth.kml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["kml"] - }, - "application/vnd.google-earth.kmz": { - "source": "iana", - "compressible": false, - "extensions": ["kmz"] - }, - "application/vnd.gov.sk.e-form+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.gov.sk.e-form+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.gov.sk.xmldatacontainer+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.grafeq": { - "source": "iana", - "extensions": ["gqf","gqs"] - }, - "application/vnd.gridmp": { - "source": "iana" - }, - "application/vnd.groove-account": { - "source": "iana", - "extensions": ["gac"] - }, - "application/vnd.groove-help": { - "source": "iana", - "extensions": ["ghf"] - }, - "application/vnd.groove-identity-message": { - "source": "iana", - "extensions": ["gim"] - }, - "application/vnd.groove-injector": { - "source": "iana", - "extensions": ["grv"] - }, - "application/vnd.groove-tool-message": { - "source": "iana", - "extensions": ["gtm"] - }, - "application/vnd.groove-tool-template": { - "source": "iana", - "extensions": ["tpl"] - }, - "application/vnd.groove-vcard": { - "source": "iana", - "extensions": ["vcg"] - }, - "application/vnd.hal+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hal+xml": { - "source": "iana", - "compressible": true, - "extensions": ["hal"] - }, - "application/vnd.handheld-entertainment+xml": { - "source": "iana", - "compressible": true, - "extensions": ["zmm"] - }, - "application/vnd.hbci": { - "source": "iana", - "extensions": ["hbci"] - }, - "application/vnd.hc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hcl-bireports": { - "source": "iana" - }, - "application/vnd.hdt": { - "source": "iana" - }, - "application/vnd.heroku+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hhe.lesson-player": { - "source": "iana", - "extensions": ["les"] - }, - "application/vnd.hp-hpgl": { - "source": "iana", - "extensions": ["hpgl"] - }, - "application/vnd.hp-hpid": { - "source": "iana", - "extensions": ["hpid"] - }, - "application/vnd.hp-hps": { - "source": "iana", - "extensions": ["hps"] - }, - "application/vnd.hp-jlyt": { - "source": "iana", - "extensions": ["jlt"] - }, - "application/vnd.hp-pcl": { - "source": "iana", - "extensions": ["pcl"] - }, - "application/vnd.hp-pclxl": { - "source": "iana", - "extensions": ["pclxl"] - }, - "application/vnd.httphone": { - "source": "iana" - }, - "application/vnd.hydrostatix.sof-data": { - "source": "iana", - "extensions": ["sfd-hdstx"] - }, - "application/vnd.hyper+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hyper-item+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hyperdrive+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hzn-3d-crossword": { - "source": "iana" - }, - "application/vnd.ibm.afplinedata": { - "source": "iana" - }, - "application/vnd.ibm.electronic-media": { - "source": "iana" - }, - "application/vnd.ibm.minipay": { - "source": "iana", - "extensions": ["mpy"] - }, - "application/vnd.ibm.modcap": { - "source": "iana", - "extensions": ["afp","listafp","list3820"] - }, - "application/vnd.ibm.rights-management": { - "source": "iana", - "extensions": ["irm"] - }, - "application/vnd.ibm.secure-container": { - "source": "iana", - "extensions": ["sc"] - }, - "application/vnd.iccprofile": { - "source": "iana", - "extensions": ["icc","icm"] - }, - "application/vnd.ieee.1905": { - "source": "iana" - }, - "application/vnd.igloader": { - "source": "iana", - "extensions": ["igl"] - }, - "application/vnd.imagemeter.folder+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.imagemeter.image+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.immervision-ivp": { - "source": "iana", - "extensions": ["ivp"] - }, - "application/vnd.immervision-ivu": { - "source": "iana", - "extensions": ["ivu"] - }, - "application/vnd.ims.imsccv1p1": { - "source": "iana" - }, - "application/vnd.ims.imsccv1p2": { - "source": "iana" - }, - "application/vnd.ims.imsccv1p3": { - "source": "iana" - }, - "application/vnd.ims.lis.v2.result+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolproxy+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolsettings+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.informedcontrol.rms+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.informix-visionary": { - "source": "iana" - }, - "application/vnd.infotech.project": { - "source": "iana" - }, - "application/vnd.infotech.project+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.innopath.wamp.notification": { - "source": "iana" - }, - "application/vnd.insors.igm": { - "source": "iana", - "extensions": ["igm"] - }, - "application/vnd.intercon.formnet": { - "source": "iana", - "extensions": ["xpw","xpx"] - }, - "application/vnd.intergeo": { - "source": "iana", - "extensions": ["i2g"] - }, - "application/vnd.intertrust.digibox": { - "source": "iana" - }, - "application/vnd.intertrust.nncp": { - "source": "iana" - }, - "application/vnd.intu.qbo": { - "source": "iana", - "extensions": ["qbo"] - }, - "application/vnd.intu.qfx": { - "source": "iana", - "extensions": ["qfx"] - }, - "application/vnd.iptc.g2.catalogitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.conceptitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.knowledgeitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.newsitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.newsmessage+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.packageitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.planningitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ipunplugged.rcprofile": { - "source": "iana", - "extensions": ["rcprofile"] - }, - "application/vnd.irepository.package+xml": { - "source": "iana", - "compressible": true, - "extensions": ["irp"] - }, - "application/vnd.is-xpr": { - "source": "iana", - "extensions": ["xpr"] - }, - "application/vnd.isac.fcs": { - "source": "iana", - "extensions": ["fcs"] - }, - "application/vnd.jam": { - "source": "iana", - "extensions": ["jam"] - }, - "application/vnd.japannet-directory-service": { - "source": "iana" - }, - "application/vnd.japannet-jpnstore-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-payment-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-registration": { - "source": "iana" - }, - "application/vnd.japannet-registration-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-setstore-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-verification": { - "source": "iana" - }, - "application/vnd.japannet-verification-wakeup": { - "source": "iana" - }, - "application/vnd.jcp.javame.midlet-rms": { - "source": "iana", - "extensions": ["rms"] - }, - "application/vnd.jisp": { - "source": "iana", - "extensions": ["jisp"] - }, - "application/vnd.joost.joda-archive": { - "source": "iana", - "extensions": ["joda"] - }, - "application/vnd.jsk.isdn-ngn": { - "source": "iana" - }, - "application/vnd.kahootz": { - "source": "iana", - "extensions": ["ktz","ktr"] - }, - "application/vnd.kde.karbon": { - "source": "iana", - "extensions": ["karbon"] - }, - "application/vnd.kde.kchart": { - "source": "iana", - "extensions": ["chrt"] - }, - "application/vnd.kde.kformula": { - "source": "iana", - "extensions": ["kfo"] - }, - "application/vnd.kde.kivio": { - "source": "iana", - "extensions": ["flw"] - }, - "application/vnd.kde.kontour": { - "source": "iana", - "extensions": ["kon"] - }, - "application/vnd.kde.kpresenter": { - "source": "iana", - "extensions": ["kpr","kpt"] - }, - "application/vnd.kde.kspread": { - "source": "iana", - "extensions": ["ksp"] - }, - "application/vnd.kde.kword": { - "source": "iana", - "extensions": ["kwd","kwt"] - }, - "application/vnd.kenameaapp": { - "source": "iana", - "extensions": ["htke"] - }, - "application/vnd.kidspiration": { - "source": "iana", - "extensions": ["kia"] - }, - "application/vnd.kinar": { - "source": "iana", - "extensions": ["kne","knp"] - }, - "application/vnd.koan": { - "source": "iana", - "extensions": ["skp","skd","skt","skm"] - }, - "application/vnd.kodak-descriptor": { - "source": "iana", - "extensions": ["sse"] - }, - "application/vnd.las.las+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.las.las+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lasxml"] - }, - "application/vnd.leap+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.liberty-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.llamagraphics.life-balance.desktop": { - "source": "iana", - "extensions": ["lbd"] - }, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lbe"] - }, - "application/vnd.lotus-1-2-3": { - "source": "iana", - "extensions": ["123"] - }, - "application/vnd.lotus-approach": { - "source": "iana", - "extensions": ["apr"] - }, - "application/vnd.lotus-freelance": { - "source": "iana", - "extensions": ["pre"] - }, - "application/vnd.lotus-notes": { - "source": "iana", - "extensions": ["nsf"] - }, - "application/vnd.lotus-organizer": { - "source": "iana", - "extensions": ["org"] - }, - "application/vnd.lotus-screencam": { - "source": "iana", - "extensions": ["scm"] - }, - "application/vnd.lotus-wordpro": { - "source": "iana", - "extensions": ["lwp"] - }, - "application/vnd.macports.portpkg": { - "source": "iana", - "extensions": ["portpkg"] - }, - "application/vnd.mapbox-vector-tile": { - "source": "iana" - }, - "application/vnd.marlin.drm.actiontoken+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.conftoken+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.license+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.mdcf": { - "source": "iana" - }, - "application/vnd.mason+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.maxmind.maxmind-db": { - "source": "iana" - }, - "application/vnd.mcd": { - "source": "iana", - "extensions": ["mcd"] - }, - "application/vnd.medcalcdata": { - "source": "iana", - "extensions": ["mc1"] - }, - "application/vnd.mediastation.cdkey": { - "source": "iana", - "extensions": ["cdkey"] - }, - "application/vnd.meridian-slingshot": { - "source": "iana" - }, - "application/vnd.mfer": { - "source": "iana", - "extensions": ["mwf"] - }, - "application/vnd.mfmp": { - "source": "iana", - "extensions": ["mfm"] - }, - "application/vnd.micro+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.micrografx.flo": { - "source": "iana", - "extensions": ["flo"] - }, - "application/vnd.micrografx.igx": { - "source": "iana", - "extensions": ["igx"] - }, - "application/vnd.microsoft.portable-executable": { - "source": "iana" - }, - "application/vnd.microsoft.windows.thumbnail-cache": { - "source": "iana" - }, - "application/vnd.miele+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.mif": { - "source": "iana", - "extensions": ["mif"] - }, - "application/vnd.minisoft-hp3000-save": { - "source": "iana" - }, - "application/vnd.mitsubishi.misty-guard.trustweb": { - "source": "iana" - }, - "application/vnd.mobius.daf": { - "source": "iana", - "extensions": ["daf"] - }, - "application/vnd.mobius.dis": { - "source": "iana", - "extensions": ["dis"] - }, - "application/vnd.mobius.mbk": { - "source": "iana", - "extensions": ["mbk"] - }, - "application/vnd.mobius.mqy": { - "source": "iana", - "extensions": ["mqy"] - }, - "application/vnd.mobius.msl": { - "source": "iana", - "extensions": ["msl"] - }, - "application/vnd.mobius.plc": { - "source": "iana", - "extensions": ["plc"] - }, - "application/vnd.mobius.txf": { - "source": "iana", - "extensions": ["txf"] - }, - "application/vnd.mophun.application": { - "source": "iana", - "extensions": ["mpn"] - }, - "application/vnd.mophun.certificate": { - "source": "iana", - "extensions": ["mpc"] - }, - "application/vnd.motorola.flexsuite": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.adsi": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.fis": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.gotap": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.kmr": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.ttc": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.wem": { - "source": "iana" - }, - "application/vnd.motorola.iprm": { - "source": "iana" - }, - "application/vnd.mozilla.xul+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xul"] - }, - "application/vnd.ms-3mfdocument": { - "source": "iana" - }, - "application/vnd.ms-artgalry": { - "source": "iana", - "extensions": ["cil"] - }, - "application/vnd.ms-asf": { - "source": "iana" - }, - "application/vnd.ms-cab-compressed": { - "source": "iana", - "extensions": ["cab"] - }, - "application/vnd.ms-color.iccprofile": { - "source": "apache" - }, - "application/vnd.ms-excel": { - "source": "iana", - "compressible": false, - "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] - }, - "application/vnd.ms-excel.addin.macroenabled.12": { - "source": "iana", - "extensions": ["xlam"] - }, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - "source": "iana", - "extensions": ["xlsb"] - }, - "application/vnd.ms-excel.sheet.macroenabled.12": { - "source": "iana", - "extensions": ["xlsm"] - }, - "application/vnd.ms-excel.template.macroenabled.12": { - "source": "iana", - "extensions": ["xltm"] - }, - "application/vnd.ms-fontobject": { - "source": "iana", - "compressible": true, - "extensions": ["eot"] - }, - "application/vnd.ms-htmlhelp": { - "source": "iana", - "extensions": ["chm"] - }, - "application/vnd.ms-ims": { - "source": "iana", - "extensions": ["ims"] - }, - "application/vnd.ms-lrm": { - "source": "iana", - "extensions": ["lrm"] - }, - "application/vnd.ms-office.activex+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-officetheme": { - "source": "iana", - "extensions": ["thmx"] - }, - "application/vnd.ms-opentype": { - "source": "apache", - "compressible": true - }, - "application/vnd.ms-outlook": { - "compressible": false, - "extensions": ["msg"] - }, - "application/vnd.ms-package.obfuscated-opentype": { - "source": "apache" - }, - "application/vnd.ms-pki.seccat": { - "source": "apache", - "extensions": ["cat"] - }, - "application/vnd.ms-pki.stl": { - "source": "apache", - "extensions": ["stl"] - }, - "application/vnd.ms-playready.initiator+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-powerpoint": { - "source": "iana", - "compressible": false, - "extensions": ["ppt","pps","pot"] - }, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - "source": "iana", - "extensions": ["ppam"] - }, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - "source": "iana", - "extensions": ["pptm"] - }, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - "source": "iana", - "extensions": ["sldm"] - }, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - "source": "iana", - "extensions": ["ppsm"] - }, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - "source": "iana", - "extensions": ["potm"] - }, - "application/vnd.ms-printdevicecapabilities+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-printing.printticket+xml": { - "source": "apache", - "compressible": true - }, - "application/vnd.ms-printschematicket+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-project": { - "source": "iana", - "extensions": ["mpp","mpt"] - }, - "application/vnd.ms-tnef": { - "source": "iana" - }, - "application/vnd.ms-windows.devicepairing": { - "source": "iana" - }, - "application/vnd.ms-windows.nwprinting.oob": { - "source": "iana" - }, - "application/vnd.ms-windows.printerpairing": { - "source": "iana" - }, - "application/vnd.ms-windows.wsd.oob": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.lic-chlg-req": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.lic-resp": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.meter-chlg-req": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.meter-resp": { - "source": "iana" - }, - "application/vnd.ms-word.document.macroenabled.12": { - "source": "iana", - "extensions": ["docm"] - }, - "application/vnd.ms-word.template.macroenabled.12": { - "source": "iana", - "extensions": ["dotm"] - }, - "application/vnd.ms-works": { - "source": "iana", - "extensions": ["wps","wks","wcm","wdb"] - }, - "application/vnd.ms-wpl": { - "source": "iana", - "extensions": ["wpl"] - }, - "application/vnd.ms-xpsdocument": { - "source": "iana", - "compressible": false, - "extensions": ["xps"] - }, - "application/vnd.msa-disk-image": { - "source": "iana" - }, - "application/vnd.mseq": { - "source": "iana", - "extensions": ["mseq"] - }, - "application/vnd.msign": { - "source": "iana" - }, - "application/vnd.multiad.creator": { - "source": "iana" - }, - "application/vnd.multiad.creator.cif": { - "source": "iana" - }, - "application/vnd.music-niff": { - "source": "iana" - }, - "application/vnd.musician": { - "source": "iana", - "extensions": ["mus"] - }, - "application/vnd.muvee.style": { - "source": "iana", - "extensions": ["msty"] - }, - "application/vnd.mynfc": { - "source": "iana", - "extensions": ["taglet"] - }, - "application/vnd.ncd.control": { - "source": "iana" - }, - "application/vnd.ncd.reference": { - "source": "iana" - }, - "application/vnd.nearst.inv+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.nervana": { - "source": "iana" - }, - "application/vnd.netfpx": { - "source": "iana" - }, - "application/vnd.neurolanguage.nlu": { - "source": "iana", - "extensions": ["nlu"] - }, - "application/vnd.nimn": { - "source": "iana" - }, - "application/vnd.nintendo.nitro.rom": { - "source": "iana" - }, - "application/vnd.nintendo.snes.rom": { - "source": "iana" - }, - "application/vnd.nitf": { - "source": "iana", - "extensions": ["ntf","nitf"] - }, - "application/vnd.noblenet-directory": { - "source": "iana", - "extensions": ["nnd"] - }, - "application/vnd.noblenet-sealer": { - "source": "iana", - "extensions": ["nns"] - }, - "application/vnd.noblenet-web": { - "source": "iana", - "extensions": ["nnw"] - }, - "application/vnd.nokia.catalogs": { - "source": "iana" - }, - "application/vnd.nokia.conml+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.conml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.iptv.config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.isds-radio-presets": { - "source": "iana" - }, - "application/vnd.nokia.landmark+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.landmark+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.landmarkcollection+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.n-gage.ac+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.n-gage.data": { - "source": "iana", - "extensions": ["ngdat"] - }, - "application/vnd.nokia.n-gage.symbian.install": { - "source": "iana", - "extensions": ["n-gage"] - }, - "application/vnd.nokia.ncd": { - "source": "iana" - }, - "application/vnd.nokia.pcd+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.pcd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.radio-preset": { - "source": "iana", - "extensions": ["rpst"] - }, - "application/vnd.nokia.radio-presets": { - "source": "iana", - "extensions": ["rpss"] - }, - "application/vnd.novadigm.edm": { - "source": "iana", - "extensions": ["edm"] - }, - "application/vnd.novadigm.edx": { - "source": "iana", - "extensions": ["edx"] - }, - "application/vnd.novadigm.ext": { - "source": "iana", - "extensions": ["ext"] - }, - "application/vnd.ntt-local.content-share": { - "source": "iana" - }, - "application/vnd.ntt-local.file-transfer": { - "source": "iana" - }, - "application/vnd.ntt-local.ogw_remote-access": { - "source": "iana" - }, - "application/vnd.ntt-local.sip-ta_remote": { - "source": "iana" - }, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - "source": "iana" - }, - "application/vnd.oasis.opendocument.chart": { - "source": "iana", - "extensions": ["odc"] - }, - "application/vnd.oasis.opendocument.chart-template": { - "source": "iana", - "extensions": ["otc"] - }, - "application/vnd.oasis.opendocument.database": { - "source": "iana", - "extensions": ["odb"] - }, - "application/vnd.oasis.opendocument.formula": { - "source": "iana", - "extensions": ["odf"] - }, - "application/vnd.oasis.opendocument.formula-template": { - "source": "iana", - "extensions": ["odft"] - }, - "application/vnd.oasis.opendocument.graphics": { - "source": "iana", - "compressible": false, - "extensions": ["odg"] - }, - "application/vnd.oasis.opendocument.graphics-template": { - "source": "iana", - "extensions": ["otg"] - }, - "application/vnd.oasis.opendocument.image": { - "source": "iana", - "extensions": ["odi"] - }, - "application/vnd.oasis.opendocument.image-template": { - "source": "iana", - "extensions": ["oti"] - }, - "application/vnd.oasis.opendocument.presentation": { - "source": "iana", - "compressible": false, - "extensions": ["odp"] - }, - "application/vnd.oasis.opendocument.presentation-template": { - "source": "iana", - "extensions": ["otp"] - }, - "application/vnd.oasis.opendocument.spreadsheet": { - "source": "iana", - "compressible": false, - "extensions": ["ods"] - }, - "application/vnd.oasis.opendocument.spreadsheet-template": { - "source": "iana", - "extensions": ["ots"] - }, - "application/vnd.oasis.opendocument.text": { - "source": "iana", - "compressible": false, - "extensions": ["odt"] - }, - "application/vnd.oasis.opendocument.text-master": { - "source": "iana", - "extensions": ["odm"] - }, - "application/vnd.oasis.opendocument.text-template": { - "source": "iana", - "extensions": ["ott"] - }, - "application/vnd.oasis.opendocument.text-web": { - "source": "iana", - "extensions": ["oth"] - }, - "application/vnd.obn": { - "source": "iana" - }, - "application/vnd.ocf+cbor": { - "source": "iana" - }, - "application/vnd.oftn.l10n+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.contentaccessdownload+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.contentaccessstreaming+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.cspg-hexbinary": { - "source": "iana" - }, - "application/vnd.oipf.dae.svg+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.dae.xhtml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.mippvcontrolmessage+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.pae.gem": { - "source": "iana" - }, - "application/vnd.oipf.spdiscovery+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.spdlist+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.ueprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.userprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.olpc-sugar": { - "source": "iana", - "extensions": ["xo"] - }, - "application/vnd.oma-scws-config": { - "source": "iana" - }, - "application/vnd.oma-scws-http-request": { - "source": "iana" - }, - "application/vnd.oma-scws-http-response": { - "source": "iana" - }, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.drm-trigger+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.imd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.ltkm": { - "source": "iana" - }, - "application/vnd.oma.bcast.notification+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.provisioningtrigger": { - "source": "iana" - }, - "application/vnd.oma.bcast.sgboot": { - "source": "iana" - }, - "application/vnd.oma.bcast.sgdd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.sgdu": { - "source": "iana" - }, - "application/vnd.oma.bcast.simple-symbol-container": { - "source": "iana" - }, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.sprov+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.stkm": { - "source": "iana" - }, - "application/vnd.oma.cab-address-book+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-feature-handler+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-pcc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-subs-invite+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-user-prefs+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.dcd": { - "source": "iana" - }, - "application/vnd.oma.dcdc": { - "source": "iana" - }, - "application/vnd.oma.dd2+xml": { - "source": "iana", - "compressible": true, - "extensions": ["dd2"] - }, - "application/vnd.oma.drm.risd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.group-usage-list+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.lwm2m+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.lwm2m+tlv": { - "source": "iana" - }, - "application/vnd.oma.pal+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.detailed-progress-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.final-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.groups+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.invocation-descriptor+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.optimized-progress-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.push": { - "source": "iana" - }, - "application/vnd.oma.scidm.messages+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.xcap-directory+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.omads-email+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.omads-file+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.omads-folder+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.omaloc-supl-init": { - "source": "iana" - }, - "application/vnd.onepager": { - "source": "iana" - }, - "application/vnd.onepagertamp": { - "source": "iana" - }, - "application/vnd.onepagertamx": { - "source": "iana" - }, - "application/vnd.onepagertat": { - "source": "iana" - }, - "application/vnd.onepagertatp": { - "source": "iana" - }, - "application/vnd.onepagertatx": { - "source": "iana" - }, - "application/vnd.openblox.game+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openblox.game-binary": { - "source": "iana" - }, - "application/vnd.openeye.oeb": { - "source": "iana" - }, - "application/vnd.openofficeorg.extension": { - "source": "apache", - "extensions": ["oxt"] - }, - "application/vnd.openstreetmap.data+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - "source": "iana", - "compressible": false, - "extensions": ["pptx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - "source": "iana", - "extensions": ["sldx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - "source": "iana", - "extensions": ["ppsx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - "source": "iana", - "extensions": ["potx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - "source": "iana", - "compressible": false, - "extensions": ["xlsx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - "source": "iana", - "extensions": ["xltx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.theme+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - "source": "iana" - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - "source": "iana", - "compressible": false, - "extensions": ["docx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - "source": "iana", - "extensions": ["dotx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.core-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.relationships+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oracle.resource+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.orange.indata": { - "source": "iana" - }, - "application/vnd.osa.netdeploy": { - "source": "iana" - }, - "application/vnd.osgeo.mapguide.package": { - "source": "iana", - "extensions": ["mgp"] - }, - "application/vnd.osgi.bundle": { - "source": "iana" - }, - "application/vnd.osgi.dp": { - "source": "iana", - "extensions": ["dp"] - }, - "application/vnd.osgi.subsystem": { - "source": "iana", - "extensions": ["esa"] - }, - "application/vnd.otps.ct-kip+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oxli.countgraph": { - "source": "iana" - }, - "application/vnd.pagerduty+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.palm": { - "source": "iana", - "extensions": ["pdb","pqa","oprc"] - }, - "application/vnd.panoply": { - "source": "iana" - }, - "application/vnd.paos.xml": { - "source": "iana" - }, - "application/vnd.patentdive": { - "source": "iana" - }, - "application/vnd.patientecommsdoc": { - "source": "iana" - }, - "application/vnd.pawaafile": { - "source": "iana", - "extensions": ["paw"] - }, - "application/vnd.pcos": { - "source": "iana" - }, - "application/vnd.pg.format": { - "source": "iana", - "extensions": ["str"] - }, - "application/vnd.pg.osasli": { - "source": "iana", - "extensions": ["ei6"] - }, - "application/vnd.piaccess.application-licence": { - "source": "iana" - }, - "application/vnd.picsel": { - "source": "iana", - "extensions": ["efif"] - }, - "application/vnd.pmi.widget": { - "source": "iana", - "extensions": ["wg"] - }, - "application/vnd.poc.group-advertisement+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.pocketlearn": { - "source": "iana", - "extensions": ["plf"] - }, - "application/vnd.powerbuilder6": { - "source": "iana", - "extensions": ["pbd"] - }, - "application/vnd.powerbuilder6-s": { - "source": "iana" - }, - "application/vnd.powerbuilder7": { - "source": "iana" - }, - "application/vnd.powerbuilder7-s": { - "source": "iana" - }, - "application/vnd.powerbuilder75": { - "source": "iana" - }, - "application/vnd.powerbuilder75-s": { - "source": "iana" - }, - "application/vnd.preminet": { - "source": "iana" - }, - "application/vnd.previewsystems.box": { - "source": "iana", - "extensions": ["box"] - }, - "application/vnd.proteus.magazine": { - "source": "iana", - "extensions": ["mgz"] - }, - "application/vnd.psfs": { - "source": "iana" - }, - "application/vnd.publishare-delta-tree": { - "source": "iana", - "extensions": ["qps"] - }, - "application/vnd.pvi.ptid1": { - "source": "iana", - "extensions": ["ptid"] - }, - "application/vnd.pwg-multiplexed": { - "source": "iana" - }, - "application/vnd.pwg-xhtml-print+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.qualcomm.brew-app-res": { - "source": "iana" - }, - "application/vnd.quarantainenet": { - "source": "iana" - }, - "application/vnd.quark.quarkxpress": { - "source": "iana", - "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] - }, - "application/vnd.quobject-quoxdocument": { - "source": "iana" - }, - "application/vnd.radisys.moml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-conf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-conn+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-dialog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-stream+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-conf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-base+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-group+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-speech+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-transform+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.rainstor.data": { - "source": "iana" - }, - "application/vnd.rapid": { - "source": "iana" - }, - "application/vnd.rar": { - "source": "iana" - }, - "application/vnd.realvnc.bed": { - "source": "iana", - "extensions": ["bed"] - }, - "application/vnd.recordare.musicxml": { - "source": "iana", - "extensions": ["mxl"] - }, - "application/vnd.recordare.musicxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["musicxml"] - }, - "application/vnd.renlearn.rlprint": { - "source": "iana" - }, - "application/vnd.restful+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.rig.cryptonote": { - "source": "iana", - "extensions": ["cryptonote"] - }, - "application/vnd.rim.cod": { - "source": "apache", - "extensions": ["cod"] - }, - "application/vnd.rn-realmedia": { - "source": "apache", - "extensions": ["rm"] - }, - "application/vnd.rn-realmedia-vbr": { - "source": "apache", - "extensions": ["rmvb"] - }, - "application/vnd.route66.link66+xml": { - "source": "iana", - "compressible": true, - "extensions": ["link66"] - }, - "application/vnd.rs-274x": { - "source": "iana" - }, - "application/vnd.ruckus.download": { - "source": "iana" - }, - "application/vnd.s3sms": { - "source": "iana" - }, - "application/vnd.sailingtracker.track": { - "source": "iana", - "extensions": ["st"] - }, - "application/vnd.sbm.cid": { - "source": "iana" - }, - "application/vnd.sbm.mid2": { - "source": "iana" - }, - "application/vnd.scribus": { - "source": "iana" - }, - "application/vnd.sealed.3df": { - "source": "iana" - }, - "application/vnd.sealed.csf": { - "source": "iana" - }, - "application/vnd.sealed.doc": { - "source": "iana" - }, - "application/vnd.sealed.eml": { - "source": "iana" - }, - "application/vnd.sealed.mht": { - "source": "iana" - }, - "application/vnd.sealed.net": { - "source": "iana" - }, - "application/vnd.sealed.ppt": { - "source": "iana" - }, - "application/vnd.sealed.tiff": { - "source": "iana" - }, - "application/vnd.sealed.xls": { - "source": "iana" - }, - "application/vnd.sealedmedia.softseal.html": { - "source": "iana" - }, - "application/vnd.sealedmedia.softseal.pdf": { - "source": "iana" - }, - "application/vnd.seemail": { - "source": "iana", - "extensions": ["see"] - }, - "application/vnd.sema": { - "source": "iana", - "extensions": ["sema"] - }, - "application/vnd.semd": { - "source": "iana", - "extensions": ["semd"] - }, - "application/vnd.semf": { - "source": "iana", - "extensions": ["semf"] - }, - "application/vnd.shana.informed.formdata": { - "source": "iana", - "extensions": ["ifm"] - }, - "application/vnd.shana.informed.formtemplate": { - "source": "iana", - "extensions": ["itp"] - }, - "application/vnd.shana.informed.interchange": { - "source": "iana", - "extensions": ["iif"] - }, - "application/vnd.shana.informed.package": { - "source": "iana", - "extensions": ["ipk"] - }, - "application/vnd.shootproof+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.sigrok.session": { - "source": "iana" - }, - "application/vnd.simtech-mindmapper": { - "source": "iana", - "extensions": ["twd","twds"] - }, - "application/vnd.siren+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.smaf": { - "source": "iana", - "extensions": ["mmf"] - }, - "application/vnd.smart.notebook": { - "source": "iana" - }, - "application/vnd.smart.teacher": { - "source": "iana", - "extensions": ["teacher"] - }, - "application/vnd.software602.filler.form+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.software602.filler.form-xml-zip": { - "source": "iana" - }, - "application/vnd.solent.sdkm+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sdkm","sdkd"] - }, - "application/vnd.spotfire.dxp": { - "source": "iana", - "extensions": ["dxp"] - }, - "application/vnd.spotfire.sfs": { - "source": "iana", - "extensions": ["sfs"] - }, - "application/vnd.sqlite3": { - "source": "iana" - }, - "application/vnd.sss-cod": { - "source": "iana" - }, - "application/vnd.sss-dtf": { - "source": "iana" - }, - "application/vnd.sss-ntf": { - "source": "iana" - }, - "application/vnd.stardivision.calc": { - "source": "apache", - "extensions": ["sdc"] - }, - "application/vnd.stardivision.draw": { - "source": "apache", - "extensions": ["sda"] - }, - "application/vnd.stardivision.impress": { - "source": "apache", - "extensions": ["sdd"] - }, - "application/vnd.stardivision.math": { - "source": "apache", - "extensions": ["smf"] - }, - "application/vnd.stardivision.writer": { - "source": "apache", - "extensions": ["sdw","vor"] - }, - "application/vnd.stardivision.writer-global": { - "source": "apache", - "extensions": ["sgl"] - }, - "application/vnd.stepmania.package": { - "source": "iana", - "extensions": ["smzip"] - }, - "application/vnd.stepmania.stepchart": { - "source": "iana", - "extensions": ["sm"] - }, - "application/vnd.street-stream": { - "source": "iana" - }, - "application/vnd.sun.wadl+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wadl"] - }, - "application/vnd.sun.xml.calc": { - "source": "apache", - "extensions": ["sxc"] - }, - "application/vnd.sun.xml.calc.template": { - "source": "apache", - "extensions": ["stc"] - }, - "application/vnd.sun.xml.draw": { - "source": "apache", - "extensions": ["sxd"] - }, - "application/vnd.sun.xml.draw.template": { - "source": "apache", - "extensions": ["std"] - }, - "application/vnd.sun.xml.impress": { - "source": "apache", - "extensions": ["sxi"] - }, - "application/vnd.sun.xml.impress.template": { - "source": "apache", - "extensions": ["sti"] - }, - "application/vnd.sun.xml.math": { - "source": "apache", - "extensions": ["sxm"] - }, - "application/vnd.sun.xml.writer": { - "source": "apache", - "extensions": ["sxw"] - }, - "application/vnd.sun.xml.writer.global": { - "source": "apache", - "extensions": ["sxg"] - }, - "application/vnd.sun.xml.writer.template": { - "source": "apache", - "extensions": ["stw"] - }, - "application/vnd.sus-calendar": { - "source": "iana", - "extensions": ["sus","susp"] - }, - "application/vnd.svd": { - "source": "iana", - "extensions": ["svd"] - }, - "application/vnd.swiftview-ics": { - "source": "iana" - }, - "application/vnd.symbian.install": { - "source": "apache", - "extensions": ["sis","sisx"] - }, - "application/vnd.syncml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xsm"] - }, - "application/vnd.syncml.dm+wbxml": { - "source": "iana", - "extensions": ["bdm"] - }, - "application/vnd.syncml.dm+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdm"] - }, - "application/vnd.syncml.dm.notification": { - "source": "iana" - }, - "application/vnd.syncml.dmddf+wbxml": { - "source": "iana" - }, - "application/vnd.syncml.dmddf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.syncml.dmtnds+wbxml": { - "source": "iana" - }, - "application/vnd.syncml.dmtnds+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.syncml.ds.notification": { - "source": "iana" - }, - "application/vnd.tableschema+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.tao.intent-module-archive": { - "source": "iana", - "extensions": ["tao"] - }, - "application/vnd.tcpdump.pcap": { - "source": "iana", - "extensions": ["pcap","cap","dmp"] - }, - "application/vnd.think-cell.ppttc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.tmd.mediaflex.api+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.tml": { - "source": "iana" - }, - "application/vnd.tmobile-livetv": { - "source": "iana", - "extensions": ["tmo"] - }, - "application/vnd.tri.onesource": { - "source": "iana" - }, - "application/vnd.trid.tpt": { - "source": "iana", - "extensions": ["tpt"] - }, - "application/vnd.triscape.mxs": { - "source": "iana", - "extensions": ["mxs"] - }, - "application/vnd.trueapp": { - "source": "iana", - "extensions": ["tra"] - }, - "application/vnd.truedoc": { - "source": "iana" - }, - "application/vnd.ubisoft.webplayer": { - "source": "iana" - }, - "application/vnd.ufdl": { - "source": "iana", - "extensions": ["ufd","ufdl"] - }, - "application/vnd.uiq.theme": { - "source": "iana", - "extensions": ["utz"] - }, - "application/vnd.umajin": { - "source": "iana", - "extensions": ["umj"] - }, - "application/vnd.unity": { - "source": "iana", - "extensions": ["unityweb"] - }, - "application/vnd.uoml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["uoml"] - }, - "application/vnd.uplanet.alert": { - "source": "iana" - }, - "application/vnd.uplanet.alert-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.bearer-choice": { - "source": "iana" - }, - "application/vnd.uplanet.bearer-choice-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.cacheop": { - "source": "iana" - }, - "application/vnd.uplanet.cacheop-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.channel": { - "source": "iana" - }, - "application/vnd.uplanet.channel-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.list": { - "source": "iana" - }, - "application/vnd.uplanet.list-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.listcmd": { - "source": "iana" - }, - "application/vnd.uplanet.listcmd-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.signal": { - "source": "iana" - }, - "application/vnd.uri-map": { - "source": "iana" - }, - "application/vnd.valve.source.material": { - "source": "iana" - }, - "application/vnd.vcx": { - "source": "iana", - "extensions": ["vcx"] - }, - "application/vnd.vd-study": { - "source": "iana" - }, - "application/vnd.vectorworks": { - "source": "iana" - }, - "application/vnd.vel+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.verimatrix.vcas": { - "source": "iana" - }, - "application/vnd.veryant.thin": { - "source": "iana" - }, - "application/vnd.vidsoft.vidconference": { - "source": "iana" - }, - "application/vnd.visio": { - "source": "iana", - "extensions": ["vsd","vst","vss","vsw"] - }, - "application/vnd.visionary": { - "source": "iana", - "extensions": ["vis"] - }, - "application/vnd.vividence.scriptfile": { - "source": "iana" - }, - "application/vnd.vsf": { - "source": "iana", - "extensions": ["vsf"] - }, - "application/vnd.wap.sic": { - "source": "iana" - }, - "application/vnd.wap.slc": { - "source": "iana" - }, - "application/vnd.wap.wbxml": { - "source": "iana", - "extensions": ["wbxml"] - }, - "application/vnd.wap.wmlc": { - "source": "iana", - "extensions": ["wmlc"] - }, - "application/vnd.wap.wmlscriptc": { - "source": "iana", - "extensions": ["wmlsc"] - }, - "application/vnd.webturbo": { - "source": "iana", - "extensions": ["wtb"] - }, - "application/vnd.wfa.p2p": { - "source": "iana" - }, - "application/vnd.wfa.wsc": { - "source": "iana" - }, - "application/vnd.windows.devicepairing": { - "source": "iana" - }, - "application/vnd.wmc": { - "source": "iana" - }, - "application/vnd.wmf.bootstrap": { - "source": "iana" - }, - "application/vnd.wolfram.mathematica": { - "source": "iana" - }, - "application/vnd.wolfram.mathematica.package": { - "source": "iana" - }, - "application/vnd.wolfram.player": { - "source": "iana", - "extensions": ["nbp"] - }, - "application/vnd.wordperfect": { - "source": "iana", - "extensions": ["wpd"] - }, - "application/vnd.wqd": { - "source": "iana", - "extensions": ["wqd"] - }, - "application/vnd.wrq-hp3000-labelled": { - "source": "iana" - }, - "application/vnd.wt.stf": { - "source": "iana", - "extensions": ["stf"] - }, - "application/vnd.wv.csp+wbxml": { - "source": "iana" - }, - "application/vnd.wv.csp+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.wv.ssp+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.xacml+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.xara": { - "source": "iana", - "extensions": ["xar"] - }, - "application/vnd.xfdl": { - "source": "iana", - "extensions": ["xfdl"] - }, - "application/vnd.xfdl.webform": { - "source": "iana" - }, - "application/vnd.xmi+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.xmpie.cpkg": { - "source": "iana" - }, - "application/vnd.xmpie.dpkg": { - "source": "iana" - }, - "application/vnd.xmpie.plan": { - "source": "iana" - }, - "application/vnd.xmpie.ppkg": { - "source": "iana" - }, - "application/vnd.xmpie.xlim": { - "source": "iana" - }, - "application/vnd.yamaha.hv-dic": { - "source": "iana", - "extensions": ["hvd"] - }, - "application/vnd.yamaha.hv-script": { - "source": "iana", - "extensions": ["hvs"] - }, - "application/vnd.yamaha.hv-voice": { - "source": "iana", - "extensions": ["hvp"] - }, - "application/vnd.yamaha.openscoreformat": { - "source": "iana", - "extensions": ["osf"] - }, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - "source": "iana", - "compressible": true, - "extensions": ["osfpvg"] - }, - "application/vnd.yamaha.remote-setup": { - "source": "iana" - }, - "application/vnd.yamaha.smaf-audio": { - "source": "iana", - "extensions": ["saf"] - }, - "application/vnd.yamaha.smaf-phrase": { - "source": "iana", - "extensions": ["spf"] - }, - "application/vnd.yamaha.through-ngn": { - "source": "iana" - }, - "application/vnd.yamaha.tunnel-udpencap": { - "source": "iana" - }, - "application/vnd.yaoweme": { - "source": "iana" - }, - "application/vnd.yellowriver-custom-menu": { - "source": "iana", - "extensions": ["cmp"] - }, - "application/vnd.youtube.yt": { - "source": "iana" - }, - "application/vnd.zul": { - "source": "iana", - "extensions": ["zir","zirz"] - }, - "application/vnd.zzazz.deck+xml": { - "source": "iana", - "compressible": true, - "extensions": ["zaz"] - }, - "application/voicexml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["vxml"] - }, - "application/voucher-cms+json": { - "source": "iana", - "compressible": true - }, - "application/vq-rtcpxr": { - "source": "iana" - }, - "application/wasm": { - "compressible": true, - "extensions": ["wasm"] - }, - "application/watcherinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/webpush-options+json": { - "source": "iana", - "compressible": true - }, - "application/whoispp-query": { - "source": "iana" - }, - "application/whoispp-response": { - "source": "iana" - }, - "application/widget": { - "source": "iana", - "extensions": ["wgt"] - }, - "application/winhlp": { - "source": "apache", - "extensions": ["hlp"] - }, - "application/wita": { - "source": "iana" - }, - "application/wordperfect5.1": { - "source": "iana" - }, - "application/wsdl+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wsdl"] - }, - "application/wspolicy+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wspolicy"] - }, - "application/x-7z-compressed": { - "source": "apache", - "compressible": false, - "extensions": ["7z"] - }, - "application/x-abiword": { - "source": "apache", - "extensions": ["abw"] - }, - "application/x-ace-compressed": { - "source": "apache", - "extensions": ["ace"] - }, - "application/x-amf": { - "source": "apache" - }, - "application/x-apple-diskimage": { - "source": "apache", - "extensions": ["dmg"] - }, - "application/x-arj": { - "compressible": false, - "extensions": ["arj"] - }, - "application/x-authorware-bin": { - "source": "apache", - "extensions": ["aab","x32","u32","vox"] - }, - "application/x-authorware-map": { - "source": "apache", - "extensions": ["aam"] - }, - "application/x-authorware-seg": { - "source": "apache", - "extensions": ["aas"] - }, - "application/x-bcpio": { - "source": "apache", - "extensions": ["bcpio"] - }, - "application/x-bdoc": { - "compressible": false, - "extensions": ["bdoc"] - }, - "application/x-bittorrent": { - "source": "apache", - "extensions": ["torrent"] - }, - "application/x-blorb": { - "source": "apache", - "extensions": ["blb","blorb"] - }, - "application/x-bzip": { - "source": "apache", - "compressible": false, - "extensions": ["bz"] - }, - "application/x-bzip2": { - "source": "apache", - "compressible": false, - "extensions": ["bz2","boz"] - }, - "application/x-cbr": { - "source": "apache", - "extensions": ["cbr","cba","cbt","cbz","cb7"] - }, - "application/x-cdlink": { - "source": "apache", - "extensions": ["vcd"] - }, - "application/x-cfs-compressed": { - "source": "apache", - "extensions": ["cfs"] - }, - "application/x-chat": { - "source": "apache", - "extensions": ["chat"] - }, - "application/x-chess-pgn": { - "source": "apache", - "extensions": ["pgn"] - }, - "application/x-chrome-extension": { - "extensions": ["crx"] - }, - "application/x-cocoa": { - "source": "nginx", - "extensions": ["cco"] - }, - "application/x-compress": { - "source": "apache" - }, - "application/x-conference": { - "source": "apache", - "extensions": ["nsc"] - }, - "application/x-cpio": { - "source": "apache", - "extensions": ["cpio"] - }, - "application/x-csh": { - "source": "apache", - "extensions": ["csh"] - }, - "application/x-deb": { - "compressible": false - }, - "application/x-debian-package": { - "source": "apache", - "extensions": ["deb","udeb"] - }, - "application/x-dgc-compressed": { - "source": "apache", - "extensions": ["dgc"] - }, - "application/x-director": { - "source": "apache", - "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] - }, - "application/x-doom": { - "source": "apache", - "extensions": ["wad"] - }, - "application/x-dtbncx+xml": { - "source": "apache", - "compressible": true, - "extensions": ["ncx"] - }, - "application/x-dtbook+xml": { - "source": "apache", - "compressible": true, - "extensions": ["dtb"] - }, - "application/x-dtbresource+xml": { - "source": "apache", - "compressible": true, - "extensions": ["res"] - }, - "application/x-dvi": { - "source": "apache", - "compressible": false, - "extensions": ["dvi"] - }, - "application/x-envoy": { - "source": "apache", - "extensions": ["evy"] - }, - "application/x-eva": { - "source": "apache", - "extensions": ["eva"] - }, - "application/x-font-bdf": { - "source": "apache", - "extensions": ["bdf"] - }, - "application/x-font-dos": { - "source": "apache" - }, - "application/x-font-framemaker": { - "source": "apache" - }, - "application/x-font-ghostscript": { - "source": "apache", - "extensions": ["gsf"] - }, - "application/x-font-libgrx": { - "source": "apache" - }, - "application/x-font-linux-psf": { - "source": "apache", - "extensions": ["psf"] - }, - "application/x-font-pcf": { - "source": "apache", - "extensions": ["pcf"] - }, - "application/x-font-snf": { - "source": "apache", - "extensions": ["snf"] - }, - "application/x-font-speedo": { - "source": "apache" - }, - "application/x-font-sunos-news": { - "source": "apache" - }, - "application/x-font-type1": { - "source": "apache", - "extensions": ["pfa","pfb","pfm","afm"] - }, - "application/x-font-vfont": { - "source": "apache" - }, - "application/x-freearc": { - "source": "apache", - "extensions": ["arc"] - }, - "application/x-futuresplash": { - "source": "apache", - "extensions": ["spl"] - }, - "application/x-gca-compressed": { - "source": "apache", - "extensions": ["gca"] - }, - "application/x-glulx": { - "source": "apache", - "extensions": ["ulx"] - }, - "application/x-gnumeric": { - "source": "apache", - "extensions": ["gnumeric"] - }, - "application/x-gramps-xml": { - "source": "apache", - "extensions": ["gramps"] - }, - "application/x-gtar": { - "source": "apache", - "extensions": ["gtar"] - }, - "application/x-gzip": { - "source": "apache" - }, - "application/x-hdf": { - "source": "apache", - "extensions": ["hdf"] - }, - "application/x-httpd-php": { - "compressible": true, - "extensions": ["php"] - }, - "application/x-install-instructions": { - "source": "apache", - "extensions": ["install"] - }, - "application/x-iso9660-image": { - "source": "apache", - "extensions": ["iso"] - }, - "application/x-java-archive-diff": { - "source": "nginx", - "extensions": ["jardiff"] - }, - "application/x-java-jnlp-file": { - "source": "apache", - "compressible": false, - "extensions": ["jnlp"] - }, - "application/x-javascript": { - "compressible": true - }, - "application/x-latex": { - "source": "apache", - "compressible": false, - "extensions": ["latex"] - }, - "application/x-lua-bytecode": { - "extensions": ["luac"] - }, - "application/x-lzh-compressed": { - "source": "apache", - "extensions": ["lzh","lha"] - }, - "application/x-makeself": { - "source": "nginx", - "extensions": ["run"] - }, - "application/x-mie": { - "source": "apache", - "extensions": ["mie"] - }, - "application/x-mobipocket-ebook": { - "source": "apache", - "extensions": ["prc","mobi"] - }, - "application/x-mpegurl": { - "compressible": false - }, - "application/x-ms-application": { - "source": "apache", - "extensions": ["application"] - }, - "application/x-ms-shortcut": { - "source": "apache", - "extensions": ["lnk"] - }, - "application/x-ms-wmd": { - "source": "apache", - "extensions": ["wmd"] - }, - "application/x-ms-wmz": { - "source": "apache", - "extensions": ["wmz"] - }, - "application/x-ms-xbap": { - "source": "apache", - "extensions": ["xbap"] - }, - "application/x-msaccess": { - "source": "apache", - "extensions": ["mdb"] - }, - "application/x-msbinder": { - "source": "apache", - "extensions": ["obd"] - }, - "application/x-mscardfile": { - "source": "apache", - "extensions": ["crd"] - }, - "application/x-msclip": { - "source": "apache", - "extensions": ["clp"] - }, - "application/x-msdos-program": { - "extensions": ["exe"] - }, - "application/x-msdownload": { - "source": "apache", - "extensions": ["exe","dll","com","bat","msi"] - }, - "application/x-msmediaview": { - "source": "apache", - "extensions": ["mvb","m13","m14"] - }, - "application/x-msmetafile": { - "source": "apache", - "extensions": ["wmf","wmz","emf","emz"] - }, - "application/x-msmoney": { - "source": "apache", - "extensions": ["mny"] - }, - "application/x-mspublisher": { - "source": "apache", - "extensions": ["pub"] - }, - "application/x-msschedule": { - "source": "apache", - "extensions": ["scd"] - }, - "application/x-msterminal": { - "source": "apache", - "extensions": ["trm"] - }, - "application/x-mswrite": { - "source": "apache", - "extensions": ["wri"] - }, - "application/x-netcdf": { - "source": "apache", - "extensions": ["nc","cdf"] - }, - "application/x-ns-proxy-autoconfig": { - "compressible": true, - "extensions": ["pac"] - }, - "application/x-nzb": { - "source": "apache", - "extensions": ["nzb"] - }, - "application/x-perl": { - "source": "nginx", - "extensions": ["pl","pm"] - }, - "application/x-pilot": { - "source": "nginx", - "extensions": ["prc","pdb"] - }, - "application/x-pkcs12": { - "source": "apache", - "compressible": false, - "extensions": ["p12","pfx"] - }, - "application/x-pkcs7-certificates": { - "source": "apache", - "extensions": ["p7b","spc"] - }, - "application/x-pkcs7-certreqresp": { - "source": "apache", - "extensions": ["p7r"] - }, - "application/x-rar-compressed": { - "source": "apache", - "compressible": false, - "extensions": ["rar"] - }, - "application/x-redhat-package-manager": { - "source": "nginx", - "extensions": ["rpm"] - }, - "application/x-research-info-systems": { - "source": "apache", - "extensions": ["ris"] - }, - "application/x-sea": { - "source": "nginx", - "extensions": ["sea"] - }, - "application/x-sh": { - "source": "apache", - "compressible": true, - "extensions": ["sh"] - }, - "application/x-shar": { - "source": "apache", - "extensions": ["shar"] - }, - "application/x-shockwave-flash": { - "source": "apache", - "compressible": false, - "extensions": ["swf"] - }, - "application/x-silverlight-app": { - "source": "apache", - "extensions": ["xap"] - }, - "application/x-sql": { - "source": "apache", - "extensions": ["sql"] - }, - "application/x-stuffit": { - "source": "apache", - "compressible": false, - "extensions": ["sit"] - }, - "application/x-stuffitx": { - "source": "apache", - "extensions": ["sitx"] - }, - "application/x-subrip": { - "source": "apache", - "extensions": ["srt"] - }, - "application/x-sv4cpio": { - "source": "apache", - "extensions": ["sv4cpio"] - }, - "application/x-sv4crc": { - "source": "apache", - "extensions": ["sv4crc"] - }, - "application/x-t3vm-image": { - "source": "apache", - "extensions": ["t3"] - }, - "application/x-tads": { - "source": "apache", - "extensions": ["gam"] - }, - "application/x-tar": { - "source": "apache", - "compressible": true, - "extensions": ["tar"] - }, - "application/x-tcl": { - "source": "apache", - "extensions": ["tcl","tk"] - }, - "application/x-tex": { - "source": "apache", - "extensions": ["tex"] - }, - "application/x-tex-tfm": { - "source": "apache", - "extensions": ["tfm"] - }, - "application/x-texinfo": { - "source": "apache", - "extensions": ["texinfo","texi"] - }, - "application/x-tgif": { - "source": "apache", - "extensions": ["obj"] - }, - "application/x-ustar": { - "source": "apache", - "extensions": ["ustar"] - }, - "application/x-virtualbox-hdd": { - "compressible": true, - "extensions": ["hdd"] - }, - "application/x-virtualbox-ova": { - "compressible": true, - "extensions": ["ova"] - }, - "application/x-virtualbox-ovf": { - "compressible": true, - "extensions": ["ovf"] - }, - "application/x-virtualbox-vbox": { - "compressible": true, - "extensions": ["vbox"] - }, - "application/x-virtualbox-vbox-extpack": { - "compressible": false, - "extensions": ["vbox-extpack"] - }, - "application/x-virtualbox-vdi": { - "compressible": true, - "extensions": ["vdi"] - }, - "application/x-virtualbox-vhd": { - "compressible": true, - "extensions": ["vhd"] - }, - "application/x-virtualbox-vmdk": { - "compressible": true, - "extensions": ["vmdk"] - }, - "application/x-wais-source": { - "source": "apache", - "extensions": ["src"] - }, - "application/x-web-app-manifest+json": { - "compressible": true, - "extensions": ["webapp"] - }, - "application/x-www-form-urlencoded": { - "source": "iana", - "compressible": true - }, - "application/x-x509-ca-cert": { - "source": "apache", - "extensions": ["der","crt","pem"] - }, - "application/x-xfig": { - "source": "apache", - "extensions": ["fig"] - }, - "application/x-xliff+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xlf"] - }, - "application/x-xpinstall": { - "source": "apache", - "compressible": false, - "extensions": ["xpi"] - }, - "application/x-xz": { - "source": "apache", - "extensions": ["xz"] - }, - "application/x-zmachine": { - "source": "apache", - "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] - }, - "application/x400-bp": { - "source": "iana" - }, - "application/xacml+xml": { - "source": "iana", - "compressible": true - }, - "application/xaml+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xaml"] - }, - "application/xcap-att+xml": { - "source": "iana", - "compressible": true - }, - "application/xcap-caps+xml": { - "source": "iana", - "compressible": true - }, - "application/xcap-diff+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdf"] - }, - "application/xcap-el+xml": { - "source": "iana", - "compressible": true - }, - "application/xcap-error+xml": { - "source": "iana", - "compressible": true - }, - "application/xcap-ns+xml": { - "source": "iana", - "compressible": true - }, - "application/xcon-conference-info+xml": { - "source": "iana", - "compressible": true - }, - "application/xcon-conference-info-diff+xml": { - "source": "iana", - "compressible": true - }, - "application/xenc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xenc"] - }, - "application/xhtml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xhtml","xht"] - }, - "application/xhtml-voice+xml": { - "source": "apache", - "compressible": true - }, - "application/xliff+xml": { - "source": "iana", - "compressible": true - }, - "application/xml": { - "source": "iana", - "compressible": true, - "extensions": ["xml","xsl","xsd","rng"] - }, - "application/xml-dtd": { - "source": "iana", - "compressible": true, - "extensions": ["dtd"] - }, - "application/xml-external-parsed-entity": { - "source": "iana" - }, - "application/xml-patch+xml": { - "source": "iana", - "compressible": true - }, - "application/xmpp+xml": { - "source": "iana", - "compressible": true - }, - "application/xop+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xop"] - }, - "application/xproc+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xpl"] - }, - "application/xslt+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xslt"] - }, - "application/xspf+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xspf"] - }, - "application/xv+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mxml","xhvml","xvml","xvm"] - }, - "application/yang": { - "source": "iana", - "extensions": ["yang"] - }, - "application/yang-data+json": { - "source": "iana", - "compressible": true - }, - "application/yang-data+xml": { - "source": "iana", - "compressible": true - }, - "application/yang-patch+json": { - "source": "iana", - "compressible": true - }, - "application/yang-patch+xml": { - "source": "iana", - "compressible": true - }, - "application/yin+xml": { - "source": "iana", - "compressible": true, - "extensions": ["yin"] - }, - "application/zip": { - "source": "iana", - "compressible": false, - "extensions": ["zip"] - }, - "application/zlib": { - "source": "iana" - }, - "application/zstd": { - "source": "iana" - }, - "audio/1d-interleaved-parityfec": { - "source": "iana" - }, - "audio/32kadpcm": { - "source": "iana" - }, - "audio/3gpp": { - "source": "iana", - "compressible": false, - "extensions": ["3gpp"] - }, - "audio/3gpp2": { - "source": "iana" - }, - "audio/aac": { - "source": "iana" - }, - "audio/ac3": { - "source": "iana" - }, - "audio/adpcm": { - "source": "apache", - "extensions": ["adp"] - }, - "audio/amr": { - "source": "iana" - }, - "audio/amr-wb": { - "source": "iana" - }, - "audio/amr-wb+": { - "source": "iana" - }, - "audio/aptx": { - "source": "iana" - }, - "audio/asc": { - "source": "iana" - }, - "audio/atrac-advanced-lossless": { - "source": "iana" - }, - "audio/atrac-x": { - "source": "iana" - }, - "audio/atrac3": { - "source": "iana" - }, - "audio/basic": { - "source": "iana", - "compressible": false, - "extensions": ["au","snd"] - }, - "audio/bv16": { - "source": "iana" - }, - "audio/bv32": { - "source": "iana" - }, - "audio/clearmode": { - "source": "iana" - }, - "audio/cn": { - "source": "iana" - }, - "audio/dat12": { - "source": "iana" - }, - "audio/dls": { - "source": "iana" - }, - "audio/dsr-es201108": { - "source": "iana" - }, - "audio/dsr-es202050": { - "source": "iana" - }, - "audio/dsr-es202211": { - "source": "iana" - }, - "audio/dsr-es202212": { - "source": "iana" - }, - "audio/dv": { - "source": "iana" - }, - "audio/dvi4": { - "source": "iana" - }, - "audio/eac3": { - "source": "iana" - }, - "audio/encaprtp": { - "source": "iana" - }, - "audio/evrc": { - "source": "iana" - }, - "audio/evrc-qcp": { - "source": "iana" - }, - "audio/evrc0": { - "source": "iana" - }, - "audio/evrc1": { - "source": "iana" - }, - "audio/evrcb": { - "source": "iana" - }, - "audio/evrcb0": { - "source": "iana" - }, - "audio/evrcb1": { - "source": "iana" - }, - "audio/evrcnw": { - "source": "iana" - }, - "audio/evrcnw0": { - "source": "iana" - }, - "audio/evrcnw1": { - "source": "iana" - }, - "audio/evrcwb": { - "source": "iana" - }, - "audio/evrcwb0": { - "source": "iana" - }, - "audio/evrcwb1": { - "source": "iana" - }, - "audio/evs": { - "source": "iana" - }, - "audio/fwdred": { - "source": "iana" - }, - "audio/g711-0": { - "source": "iana" - }, - "audio/g719": { - "source": "iana" - }, - "audio/g722": { - "source": "iana" - }, - "audio/g7221": { - "source": "iana" - }, - "audio/g723": { - "source": "iana" - }, - "audio/g726-16": { - "source": "iana" - }, - "audio/g726-24": { - "source": "iana" - }, - "audio/g726-32": { - "source": "iana" - }, - "audio/g726-40": { - "source": "iana" - }, - "audio/g728": { - "source": "iana" - }, - "audio/g729": { - "source": "iana" - }, - "audio/g7291": { - "source": "iana" - }, - "audio/g729d": { - "source": "iana" - }, - "audio/g729e": { - "source": "iana" - }, - "audio/gsm": { - "source": "iana" - }, - "audio/gsm-efr": { - "source": "iana" - }, - "audio/gsm-hr-08": { - "source": "iana" - }, - "audio/ilbc": { - "source": "iana" - }, - "audio/ip-mr_v2.5": { - "source": "iana" - }, - "audio/isac": { - "source": "apache" - }, - "audio/l16": { - "source": "iana" - }, - "audio/l20": { - "source": "iana" - }, - "audio/l24": { - "source": "iana", - "compressible": false - }, - "audio/l8": { - "source": "iana" - }, - "audio/lpc": { - "source": "iana" - }, - "audio/melp": { - "source": "iana" - }, - "audio/melp1200": { - "source": "iana" - }, - "audio/melp2400": { - "source": "iana" - }, - "audio/melp600": { - "source": "iana" - }, - "audio/midi": { - "source": "apache", - "extensions": ["mid","midi","kar","rmi"] - }, - "audio/mobile-xmf": { - "source": "iana" - }, - "audio/mp3": { - "compressible": false, - "extensions": ["mp3"] - }, - "audio/mp4": { - "source": "iana", - "compressible": false, - "extensions": ["m4a","mp4a"] - }, - "audio/mp4a-latm": { - "source": "iana" - }, - "audio/mpa": { - "source": "iana" - }, - "audio/mpa-robust": { - "source": "iana" - }, - "audio/mpeg": { - "source": "iana", - "compressible": false, - "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] - }, - "audio/mpeg4-generic": { - "source": "iana" - }, - "audio/musepack": { - "source": "apache" - }, - "audio/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["oga","ogg","spx"] - }, - "audio/opus": { - "source": "iana" - }, - "audio/parityfec": { - "source": "iana" - }, - "audio/pcma": { - "source": "iana" - }, - "audio/pcma-wb": { - "source": "iana" - }, - "audio/pcmu": { - "source": "iana" - }, - "audio/pcmu-wb": { - "source": "iana" - }, - "audio/prs.sid": { - "source": "iana" - }, - "audio/qcelp": { - "source": "iana" - }, - "audio/raptorfec": { - "source": "iana" - }, - "audio/red": { - "source": "iana" - }, - "audio/rtp-enc-aescm128": { - "source": "iana" - }, - "audio/rtp-midi": { - "source": "iana" - }, - "audio/rtploopback": { - "source": "iana" - }, - "audio/rtx": { - "source": "iana" - }, - "audio/s3m": { - "source": "apache", - "extensions": ["s3m"] - }, - "audio/silk": { - "source": "apache", - "extensions": ["sil"] - }, - "audio/smv": { - "source": "iana" - }, - "audio/smv-qcp": { - "source": "iana" - }, - "audio/smv0": { - "source": "iana" - }, - "audio/sp-midi": { - "source": "iana" - }, - "audio/speex": { - "source": "iana" - }, - "audio/t140c": { - "source": "iana" - }, - "audio/t38": { - "source": "iana" - }, - "audio/telephone-event": { - "source": "iana" - }, - "audio/tetra_acelp": { - "source": "iana" - }, - "audio/tone": { - "source": "iana" - }, - "audio/uemclip": { - "source": "iana" - }, - "audio/ulpfec": { - "source": "iana" - }, - "audio/usac": { - "source": "iana" - }, - "audio/vdvi": { - "source": "iana" - }, - "audio/vmr-wb": { - "source": "iana" - }, - "audio/vnd.3gpp.iufp": { - "source": "iana" - }, - "audio/vnd.4sb": { - "source": "iana" - }, - "audio/vnd.audiokoz": { - "source": "iana" - }, - "audio/vnd.celp": { - "source": "iana" - }, - "audio/vnd.cisco.nse": { - "source": "iana" - }, - "audio/vnd.cmles.radio-events": { - "source": "iana" - }, - "audio/vnd.cns.anp1": { - "source": "iana" - }, - "audio/vnd.cns.inf1": { - "source": "iana" - }, - "audio/vnd.dece.audio": { - "source": "iana", - "extensions": ["uva","uvva"] - }, - "audio/vnd.digital-winds": { - "source": "iana", - "extensions": ["eol"] - }, - "audio/vnd.dlna.adts": { - "source": "iana" - }, - "audio/vnd.dolby.heaac.1": { - "source": "iana" - }, - "audio/vnd.dolby.heaac.2": { - "source": "iana" - }, - "audio/vnd.dolby.mlp": { - "source": "iana" - }, - "audio/vnd.dolby.mps": { - "source": "iana" - }, - "audio/vnd.dolby.pl2": { - "source": "iana" - }, - "audio/vnd.dolby.pl2x": { - "source": "iana" - }, - "audio/vnd.dolby.pl2z": { - "source": "iana" - }, - "audio/vnd.dolby.pulse.1": { - "source": "iana" - }, - "audio/vnd.dra": { - "source": "iana", - "extensions": ["dra"] - }, - "audio/vnd.dts": { - "source": "iana", - "extensions": ["dts"] - }, - "audio/vnd.dts.hd": { - "source": "iana", - "extensions": ["dtshd"] - }, - "audio/vnd.dts.uhd": { - "source": "iana" - }, - "audio/vnd.dvb.file": { - "source": "iana" - }, - "audio/vnd.everad.plj": { - "source": "iana" - }, - "audio/vnd.hns.audio": { - "source": "iana" - }, - "audio/vnd.lucent.voice": { - "source": "iana", - "extensions": ["lvp"] - }, - "audio/vnd.ms-playready.media.pya": { - "source": "iana", - "extensions": ["pya"] - }, - "audio/vnd.nokia.mobile-xmf": { - "source": "iana" - }, - "audio/vnd.nortel.vbk": { - "source": "iana" - }, - "audio/vnd.nuera.ecelp4800": { - "source": "iana", - "extensions": ["ecelp4800"] - }, - "audio/vnd.nuera.ecelp7470": { - "source": "iana", - "extensions": ["ecelp7470"] - }, - "audio/vnd.nuera.ecelp9600": { - "source": "iana", - "extensions": ["ecelp9600"] - }, - "audio/vnd.octel.sbc": { - "source": "iana" - }, - "audio/vnd.presonus.multitrack": { - "source": "iana" - }, - "audio/vnd.qcelp": { - "source": "iana" - }, - "audio/vnd.rhetorex.32kadpcm": { - "source": "iana" - }, - "audio/vnd.rip": { - "source": "iana", - "extensions": ["rip"] - }, - "audio/vnd.rn-realaudio": { - "compressible": false - }, - "audio/vnd.sealedmedia.softseal.mpeg": { - "source": "iana" - }, - "audio/vnd.vmx.cvsd": { - "source": "iana" - }, - "audio/vnd.wave": { - "compressible": false - }, - "audio/vorbis": { - "source": "iana", - "compressible": false - }, - "audio/vorbis-config": { - "source": "iana" - }, - "audio/wav": { - "compressible": false, - "extensions": ["wav"] - }, - "audio/wave": { - "compressible": false, - "extensions": ["wav"] - }, - "audio/webm": { - "source": "apache", - "compressible": false, - "extensions": ["weba"] - }, - "audio/x-aac": { - "source": "apache", - "compressible": false, - "extensions": ["aac"] - }, - "audio/x-aiff": { - "source": "apache", - "extensions": ["aif","aiff","aifc"] - }, - "audio/x-caf": { - "source": "apache", - "compressible": false, - "extensions": ["caf"] - }, - "audio/x-flac": { - "source": "apache", - "extensions": ["flac"] - }, - "audio/x-m4a": { - "source": "nginx", - "extensions": ["m4a"] - }, - "audio/x-matroska": { - "source": "apache", - "extensions": ["mka"] - }, - "audio/x-mpegurl": { - "source": "apache", - "extensions": ["m3u"] - }, - "audio/x-ms-wax": { - "source": "apache", - "extensions": ["wax"] - }, - "audio/x-ms-wma": { - "source": "apache", - "extensions": ["wma"] - }, - "audio/x-pn-realaudio": { - "source": "apache", - "extensions": ["ram","ra"] - }, - "audio/x-pn-realaudio-plugin": { - "source": "apache", - "extensions": ["rmp"] - }, - "audio/x-realaudio": { - "source": "nginx", - "extensions": ["ra"] - }, - "audio/x-tta": { - "source": "apache" - }, - "audio/x-wav": { - "source": "apache", - "extensions": ["wav"] - }, - "audio/xm": { - "source": "apache", - "extensions": ["xm"] - }, - "chemical/x-cdx": { - "source": "apache", - "extensions": ["cdx"] - }, - "chemical/x-cif": { - "source": "apache", - "extensions": ["cif"] - }, - "chemical/x-cmdf": { - "source": "apache", - "extensions": ["cmdf"] - }, - "chemical/x-cml": { - "source": "apache", - "extensions": ["cml"] - }, - "chemical/x-csml": { - "source": "apache", - "extensions": ["csml"] - }, - "chemical/x-pdb": { - "source": "apache" - }, - "chemical/x-xyz": { - "source": "apache", - "extensions": ["xyz"] - }, - "font/collection": { - "source": "iana", - "extensions": ["ttc"] - }, - "font/otf": { - "source": "iana", - "compressible": true, - "extensions": ["otf"] - }, - "font/sfnt": { - "source": "iana" - }, - "font/ttf": { - "source": "iana", - "extensions": ["ttf"] - }, - "font/woff": { - "source": "iana", - "extensions": ["woff"] - }, - "font/woff2": { - "source": "iana", - "extensions": ["woff2"] - }, - "image/aces": { - "source": "iana", - "extensions": ["exr"] - }, - "image/apng": { - "compressible": false, - "extensions": ["apng"] - }, - "image/avci": { - "source": "iana" - }, - "image/avcs": { - "source": "iana" - }, - "image/bmp": { - "source": "iana", - "compressible": true, - "extensions": ["bmp"] - }, - "image/cgm": { - "source": "iana", - "extensions": ["cgm"] - }, - "image/dicom-rle": { - "source": "iana", - "extensions": ["drle"] - }, - "image/emf": { - "source": "iana", - "extensions": ["emf"] - }, - "image/fits": { - "source": "iana", - "extensions": ["fits"] - }, - "image/g3fax": { - "source": "iana", - "extensions": ["g3"] - }, - "image/gif": { - "source": "iana", - "compressible": false, - "extensions": ["gif"] - }, - "image/heic": { - "source": "iana", - "extensions": ["heic"] - }, - "image/heic-sequence": { - "source": "iana", - "extensions": ["heics"] - }, - "image/heif": { - "source": "iana", - "extensions": ["heif"] - }, - "image/heif-sequence": { - "source": "iana", - "extensions": ["heifs"] - }, - "image/ief": { - "source": "iana", - "extensions": ["ief"] - }, - "image/jls": { - "source": "iana", - "extensions": ["jls"] - }, - "image/jp2": { - "source": "iana", - "compressible": false, - "extensions": ["jp2","jpg2"] - }, - "image/jpeg": { - "source": "iana", - "compressible": false, - "extensions": ["jpeg","jpg","jpe"] - }, - "image/jpm": { - "source": "iana", - "compressible": false, - "extensions": ["jpm"] - }, - "image/jpx": { - "source": "iana", - "compressible": false, - "extensions": ["jpx","jpf"] - }, - "image/jxr": { - "source": "iana", - "extensions": ["jxr"] - }, - "image/ktx": { - "source": "iana", - "extensions": ["ktx"] - }, - "image/naplps": { - "source": "iana" - }, - "image/pjpeg": { - "compressible": false - }, - "image/png": { - "source": "iana", - "compressible": false, - "extensions": ["png"] - }, - "image/prs.btif": { - "source": "iana", - "extensions": ["btif"] - }, - "image/prs.pti": { - "source": "iana", - "extensions": ["pti"] - }, - "image/pwg-raster": { - "source": "iana" - }, - "image/sgi": { - "source": "apache", - "extensions": ["sgi"] - }, - "image/svg+xml": { - "source": "iana", - "compressible": true, - "extensions": ["svg","svgz"] - }, - "image/t38": { - "source": "iana", - "extensions": ["t38"] - }, - "image/tiff": { - "source": "iana", - "compressible": false, - "extensions": ["tif","tiff"] - }, - "image/tiff-fx": { - "source": "iana", - "extensions": ["tfx"] - }, - "image/vnd.adobe.photoshop": { - "source": "iana", - "compressible": true, - "extensions": ["psd"] - }, - "image/vnd.airzip.accelerator.azv": { - "source": "iana", - "extensions": ["azv"] - }, - "image/vnd.cns.inf2": { - "source": "iana" - }, - "image/vnd.dece.graphic": { - "source": "iana", - "extensions": ["uvi","uvvi","uvg","uvvg"] - }, - "image/vnd.djvu": { - "source": "iana", - "extensions": ["djvu","djv"] - }, - "image/vnd.dvb.subtitle": { - "source": "iana", - "extensions": ["sub"] - }, - "image/vnd.dwg": { - "source": "iana", - "extensions": ["dwg"] - }, - "image/vnd.dxf": { - "source": "iana", - "extensions": ["dxf"] - }, - "image/vnd.fastbidsheet": { - "source": "iana", - "extensions": ["fbs"] - }, - "image/vnd.fpx": { - "source": "iana", - "extensions": ["fpx"] - }, - "image/vnd.fst": { - "source": "iana", - "extensions": ["fst"] - }, - "image/vnd.fujixerox.edmics-mmr": { - "source": "iana", - "extensions": ["mmr"] - }, - "image/vnd.fujixerox.edmics-rlc": { - "source": "iana", - "extensions": ["rlc"] - }, - "image/vnd.globalgraphics.pgb": { - "source": "iana" - }, - "image/vnd.microsoft.icon": { - "source": "iana", - "extensions": ["ico"] - }, - "image/vnd.mix": { - "source": "iana" - }, - "image/vnd.mozilla.apng": { - "source": "iana" - }, - "image/vnd.ms-modi": { - "source": "iana", - "extensions": ["mdi"] - }, - "image/vnd.ms-photo": { - "source": "apache", - "extensions": ["wdp"] - }, - "image/vnd.net-fpx": { - "source": "iana", - "extensions": ["npx"] - }, - "image/vnd.radiance": { - "source": "iana" - }, - "image/vnd.sealed.png": { - "source": "iana" - }, - "image/vnd.sealedmedia.softseal.gif": { - "source": "iana" - }, - "image/vnd.sealedmedia.softseal.jpg": { - "source": "iana" - }, - "image/vnd.svf": { - "source": "iana" - }, - "image/vnd.tencent.tap": { - "source": "iana", - "extensions": ["tap"] - }, - "image/vnd.valve.source.texture": { - "source": "iana", - "extensions": ["vtf"] - }, - "image/vnd.wap.wbmp": { - "source": "iana", - "extensions": ["wbmp"] - }, - "image/vnd.xiff": { - "source": "iana", - "extensions": ["xif"] - }, - "image/vnd.zbrush.pcx": { - "source": "iana", - "extensions": ["pcx"] - }, - "image/webp": { - "source": "apache", - "extensions": ["webp"] - }, - "image/wmf": { - "source": "iana", - "extensions": ["wmf"] - }, - "image/x-3ds": { - "source": "apache", - "extensions": ["3ds"] - }, - "image/x-cmu-raster": { - "source": "apache", - "extensions": ["ras"] - }, - "image/x-cmx": { - "source": "apache", - "extensions": ["cmx"] - }, - "image/x-freehand": { - "source": "apache", - "extensions": ["fh","fhc","fh4","fh5","fh7"] - }, - "image/x-icon": { - "source": "apache", - "compressible": true, - "extensions": ["ico"] - }, - "image/x-jng": { - "source": "nginx", - "extensions": ["jng"] - }, - "image/x-mrsid-image": { - "source": "apache", - "extensions": ["sid"] - }, - "image/x-ms-bmp": { - "source": "nginx", - "compressible": true, - "extensions": ["bmp"] - }, - "image/x-pcx": { - "source": "apache", - "extensions": ["pcx"] - }, - "image/x-pict": { - "source": "apache", - "extensions": ["pic","pct"] - }, - "image/x-portable-anymap": { - "source": "apache", - "extensions": ["pnm"] - }, - "image/x-portable-bitmap": { - "source": "apache", - "extensions": ["pbm"] - }, - "image/x-portable-graymap": { - "source": "apache", - "extensions": ["pgm"] - }, - "image/x-portable-pixmap": { - "source": "apache", - "extensions": ["ppm"] - }, - "image/x-rgb": { - "source": "apache", - "extensions": ["rgb"] - }, - "image/x-tga": { - "source": "apache", - "extensions": ["tga"] - }, - "image/x-xbitmap": { - "source": "apache", - "extensions": ["xbm"] - }, - "image/x-xcf": { - "compressible": false - }, - "image/x-xpixmap": { - "source": "apache", - "extensions": ["xpm"] - }, - "image/x-xwindowdump": { - "source": "apache", - "extensions": ["xwd"] - }, - "message/cpim": { - "source": "iana" - }, - "message/delivery-status": { - "source": "iana" - }, - "message/disposition-notification": { - "source": "iana", - "extensions": [ - "disposition-notification" - ] - }, - "message/external-body": { - "source": "iana" - }, - "message/feedback-report": { - "source": "iana" - }, - "message/global": { - "source": "iana", - "extensions": ["u8msg"] - }, - "message/global-delivery-status": { - "source": "iana", - "extensions": ["u8dsn"] - }, - "message/global-disposition-notification": { - "source": "iana", - "extensions": ["u8mdn"] - }, - "message/global-headers": { - "source": "iana", - "extensions": ["u8hdr"] - }, - "message/http": { - "source": "iana", - "compressible": false - }, - "message/imdn+xml": { - "source": "iana", - "compressible": true - }, - "message/news": { - "source": "iana" - }, - "message/partial": { - "source": "iana", - "compressible": false - }, - "message/rfc822": { - "source": "iana", - "compressible": true, - "extensions": ["eml","mime"] - }, - "message/s-http": { - "source": "iana" - }, - "message/sip": { - "source": "iana" - }, - "message/sipfrag": { - "source": "iana" - }, - "message/tracking-status": { - "source": "iana" - }, - "message/vnd.si.simp": { - "source": "iana" - }, - "message/vnd.wfa.wsc": { - "source": "iana", - "extensions": ["wsc"] - }, - "model/3mf": { - "source": "iana", - "extensions": ["3mf"] - }, - "model/gltf+json": { - "source": "iana", - "compressible": true, - "extensions": ["gltf"] - }, - "model/gltf-binary": { - "source": "iana", - "compressible": true, - "extensions": ["glb"] - }, - "model/iges": { - "source": "iana", - "compressible": false, - "extensions": ["igs","iges"] - }, - "model/mesh": { - "source": "iana", - "compressible": false, - "extensions": ["msh","mesh","silo"] - }, - "model/stl": { - "source": "iana", - "extensions": ["stl"] - }, - "model/vnd.collada+xml": { - "source": "iana", - "compressible": true, - "extensions": ["dae"] - }, - "model/vnd.dwf": { - "source": "iana", - "extensions": ["dwf"] - }, - "model/vnd.flatland.3dml": { - "source": "iana" - }, - "model/vnd.gdl": { - "source": "iana", - "extensions": ["gdl"] - }, - "model/vnd.gs-gdl": { - "source": "apache" - }, - "model/vnd.gs.gdl": { - "source": "iana" - }, - "model/vnd.gtw": { - "source": "iana", - "extensions": ["gtw"] - }, - "model/vnd.moml+xml": { - "source": "iana", - "compressible": true - }, - "model/vnd.mts": { - "source": "iana", - "extensions": ["mts"] - }, - "model/vnd.opengex": { - "source": "iana", - "extensions": ["ogex"] - }, - "model/vnd.parasolid.transmit.binary": { - "source": "iana", - "extensions": ["x_b"] - }, - "model/vnd.parasolid.transmit.text": { - "source": "iana", - "extensions": ["x_t"] - }, - "model/vnd.rosette.annotated-data-model": { - "source": "iana" - }, - "model/vnd.usdz+zip": { - "source": "iana", - "compressible": false, - "extensions": ["usdz"] - }, - "model/vnd.valve.source.compiled-map": { - "source": "iana", - "extensions": ["bsp"] - }, - "model/vnd.vtu": { - "source": "iana", - "extensions": ["vtu"] - }, - "model/vrml": { - "source": "iana", - "compressible": false, - "extensions": ["wrl","vrml"] - }, - "model/x3d+binary": { - "source": "apache", - "compressible": false, - "extensions": ["x3db","x3dbz"] - }, - "model/x3d+fastinfoset": { - "source": "iana", - "extensions": ["x3db"] - }, - "model/x3d+vrml": { - "source": "apache", - "compressible": false, - "extensions": ["x3dv","x3dvz"] - }, - "model/x3d+xml": { - "source": "iana", - "compressible": true, - "extensions": ["x3d","x3dz"] - }, - "model/x3d-vrml": { - "source": "iana", - "extensions": ["x3dv"] - }, - "multipart/alternative": { - "source": "iana", - "compressible": false - }, - "multipart/appledouble": { - "source": "iana" - }, - "multipart/byteranges": { - "source": "iana" - }, - "multipart/digest": { - "source": "iana" - }, - "multipart/encrypted": { - "source": "iana", - "compressible": false - }, - "multipart/form-data": { - "source": "iana", - "compressible": false - }, - "multipart/header-set": { - "source": "iana" - }, - "multipart/mixed": { - "source": "iana", - "compressible": false - }, - "multipart/multilingual": { - "source": "iana" - }, - "multipart/parallel": { - "source": "iana" - }, - "multipart/related": { - "source": "iana", - "compressible": false - }, - "multipart/report": { - "source": "iana" - }, - "multipart/signed": { - "source": "iana", - "compressible": false - }, - "multipart/vnd.bint.med-plus": { - "source": "iana" - }, - "multipart/voice-message": { - "source": "iana" - }, - "multipart/x-mixed-replace": { - "source": "iana" - }, - "text/1d-interleaved-parityfec": { - "source": "iana" - }, - "text/cache-manifest": { - "source": "iana", - "compressible": true, - "extensions": ["appcache","manifest"] - }, - "text/calendar": { - "source": "iana", - "extensions": ["ics","ifb"] - }, - "text/calender": { - "compressible": true - }, - "text/cmd": { - "compressible": true - }, - "text/coffeescript": { - "extensions": ["coffee","litcoffee"] - }, - "text/css": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["css"] - }, - "text/csv": { - "source": "iana", - "compressible": true, - "extensions": ["csv"] - }, - "text/csv-schema": { - "source": "iana" - }, - "text/directory": { - "source": "iana" - }, - "text/dns": { - "source": "iana" - }, - "text/ecmascript": { - "source": "iana" - }, - "text/encaprtp": { - "source": "iana" - }, - "text/enriched": { - "source": "iana" - }, - "text/fwdred": { - "source": "iana" - }, - "text/grammar-ref-list": { - "source": "iana" - }, - "text/html": { - "source": "iana", - "compressible": true, - "extensions": ["html","htm","shtml"] - }, - "text/jade": { - "extensions": ["jade"] - }, - "text/javascript": { - "source": "iana", - "compressible": true - }, - "text/jcr-cnd": { - "source": "iana" - }, - "text/jsx": { - "compressible": true, - "extensions": ["jsx"] - }, - "text/less": { - "compressible": true, - "extensions": ["less"] - }, - "text/markdown": { - "source": "iana", - "compressible": true, - "extensions": ["markdown","md"] - }, - "text/mathml": { - "source": "nginx", - "extensions": ["mml"] - }, - "text/mdx": { - "compressible": true, - "extensions": ["mdx"] - }, - "text/mizar": { - "source": "iana" - }, - "text/n3": { - "source": "iana", - "compressible": true, - "extensions": ["n3"] - }, - "text/parameters": { - "source": "iana" - }, - "text/parityfec": { - "source": "iana" - }, - "text/plain": { - "source": "iana", - "compressible": true, - "extensions": ["txt","text","conf","def","list","log","in","ini"] - }, - "text/provenance-notation": { - "source": "iana" - }, - "text/prs.fallenstein.rst": { - "source": "iana" - }, - "text/prs.lines.tag": { - "source": "iana", - "extensions": ["dsc"] - }, - "text/prs.prop.logic": { - "source": "iana" - }, - "text/raptorfec": { - "source": "iana" - }, - "text/red": { - "source": "iana" - }, - "text/rfc822-headers": { - "source": "iana" - }, - "text/richtext": { - "source": "iana", - "compressible": true, - "extensions": ["rtx"] - }, - "text/rtf": { - "source": "iana", - "compressible": true, - "extensions": ["rtf"] - }, - "text/rtp-enc-aescm128": { - "source": "iana" - }, - "text/rtploopback": { - "source": "iana" - }, - "text/rtx": { - "source": "iana" - }, - "text/sgml": { - "source": "iana", - "extensions": ["sgml","sgm"] - }, - "text/shex": { - "extensions": ["shex"] - }, - "text/slim": { - "extensions": ["slim","slm"] - }, - "text/strings": { - "source": "iana" - }, - "text/stylus": { - "extensions": ["stylus","styl"] - }, - "text/t140": { - "source": "iana" - }, - "text/tab-separated-values": { - "source": "iana", - "compressible": true, - "extensions": ["tsv"] - }, - "text/troff": { - "source": "iana", - "extensions": ["t","tr","roff","man","me","ms"] - }, - "text/turtle": { - "source": "iana", - "charset": "UTF-8", - "extensions": ["ttl"] - }, - "text/ulpfec": { - "source": "iana" - }, - "text/uri-list": { - "source": "iana", - "compressible": true, - "extensions": ["uri","uris","urls"] - }, - "text/vcard": { - "source": "iana", - "compressible": true, - "extensions": ["vcard"] - }, - "text/vnd.a": { - "source": "iana" - }, - "text/vnd.abc": { - "source": "iana" - }, - "text/vnd.ascii-art": { - "source": "iana" - }, - "text/vnd.curl": { - "source": "iana", - "extensions": ["curl"] - }, - "text/vnd.curl.dcurl": { - "source": "apache", - "extensions": ["dcurl"] - }, - "text/vnd.curl.mcurl": { - "source": "apache", - "extensions": ["mcurl"] - }, - "text/vnd.curl.scurl": { - "source": "apache", - "extensions": ["scurl"] - }, - "text/vnd.debian.copyright": { - "source": "iana" - }, - "text/vnd.dmclientscript": { - "source": "iana" - }, - "text/vnd.dvb.subtitle": { - "source": "iana", - "extensions": ["sub"] - }, - "text/vnd.esmertec.theme-descriptor": { - "source": "iana" - }, - "text/vnd.fly": { - "source": "iana", - "extensions": ["fly"] - }, - "text/vnd.fmi.flexstor": { - "source": "iana", - "extensions": ["flx"] - }, - "text/vnd.gml": { - "source": "iana" - }, - "text/vnd.graphviz": { - "source": "iana", - "extensions": ["gv"] - }, - "text/vnd.hgl": { - "source": "iana" - }, - "text/vnd.in3d.3dml": { - "source": "iana", - "extensions": ["3dml"] - }, - "text/vnd.in3d.spot": { - "source": "iana", - "extensions": ["spot"] - }, - "text/vnd.iptc.newsml": { - "source": "iana" - }, - "text/vnd.iptc.nitf": { - "source": "iana" - }, - "text/vnd.latex-z": { - "source": "iana" - }, - "text/vnd.motorola.reflex": { - "source": "iana" - }, - "text/vnd.ms-mediapackage": { - "source": "iana" - }, - "text/vnd.net2phone.commcenter.command": { - "source": "iana" - }, - "text/vnd.radisys.msml-basic-layout": { - "source": "iana" - }, - "text/vnd.senx.warpscript": { - "source": "iana" - }, - "text/vnd.si.uricatalogue": { - "source": "iana" - }, - "text/vnd.sun.j2me.app-descriptor": { - "source": "iana", - "extensions": ["jad"] - }, - "text/vnd.trolltech.linguist": { - "source": "iana" - }, - "text/vnd.wap.si": { - "source": "iana" - }, - "text/vnd.wap.sl": { - "source": "iana" - }, - "text/vnd.wap.wml": { - "source": "iana", - "extensions": ["wml"] - }, - "text/vnd.wap.wmlscript": { - "source": "iana", - "extensions": ["wmls"] - }, - "text/vtt": { - "charset": "UTF-8", - "compressible": true, - "extensions": ["vtt"] - }, - "text/x-asm": { - "source": "apache", - "extensions": ["s","asm"] - }, - "text/x-c": { - "source": "apache", - "extensions": ["c","cc","cxx","cpp","h","hh","dic"] - }, - "text/x-component": { - "source": "nginx", - "extensions": ["htc"] - }, - "text/x-fortran": { - "source": "apache", - "extensions": ["f","for","f77","f90"] - }, - "text/x-gwt-rpc": { - "compressible": true - }, - "text/x-handlebars-template": { - "extensions": ["hbs"] - }, - "text/x-java-source": { - "source": "apache", - "extensions": ["java"] - }, - "text/x-jquery-tmpl": { - "compressible": true - }, - "text/x-lua": { - "extensions": ["lua"] - }, - "text/x-markdown": { - "compressible": true, - "extensions": ["mkd"] - }, - "text/x-nfo": { - "source": "apache", - "extensions": ["nfo"] - }, - "text/x-opml": { - "source": "apache", - "extensions": ["opml"] - }, - "text/x-org": { - "compressible": true, - "extensions": ["org"] - }, - "text/x-pascal": { - "source": "apache", - "extensions": ["p","pas"] - }, - "text/x-processing": { - "compressible": true, - "extensions": ["pde"] - }, - "text/x-sass": { - "extensions": ["sass"] - }, - "text/x-scss": { - "extensions": ["scss"] - }, - "text/x-setext": { - "source": "apache", - "extensions": ["etx"] - }, - "text/x-sfv": { - "source": "apache", - "extensions": ["sfv"] - }, - "text/x-suse-ymp": { - "compressible": true, - "extensions": ["ymp"] - }, - "text/x-uuencode": { - "source": "apache", - "extensions": ["uu"] - }, - "text/x-vcalendar": { - "source": "apache", - "extensions": ["vcs"] - }, - "text/x-vcard": { - "source": "apache", - "extensions": ["vcf"] - }, - "text/xml": { - "source": "iana", - "compressible": true, - "extensions": ["xml"] - }, - "text/xml-external-parsed-entity": { - "source": "iana" - }, - "text/yaml": { - "extensions": ["yaml","yml"] - }, - "video/1d-interleaved-parityfec": { - "source": "iana" - }, - "video/3gpp": { - "source": "iana", - "extensions": ["3gp","3gpp"] - }, - "video/3gpp-tt": { - "source": "iana" - }, - "video/3gpp2": { - "source": "iana", - "extensions": ["3g2"] - }, - "video/bmpeg": { - "source": "iana" - }, - "video/bt656": { - "source": "iana" - }, - "video/celb": { - "source": "iana" - }, - "video/dv": { - "source": "iana" - }, - "video/encaprtp": { - "source": "iana" - }, - "video/h261": { - "source": "iana", - "extensions": ["h261"] - }, - "video/h263": { - "source": "iana", - "extensions": ["h263"] - }, - "video/h263-1998": { - "source": "iana" - }, - "video/h263-2000": { - "source": "iana" - }, - "video/h264": { - "source": "iana", - "extensions": ["h264"] - }, - "video/h264-rcdo": { - "source": "iana" - }, - "video/h264-svc": { - "source": "iana" - }, - "video/h265": { - "source": "iana" - }, - "video/iso.segment": { - "source": "iana" - }, - "video/jpeg": { - "source": "iana", - "extensions": ["jpgv"] - }, - "video/jpeg2000": { - "source": "iana" - }, - "video/jpm": { - "source": "apache", - "extensions": ["jpm","jpgm"] - }, - "video/mj2": { - "source": "iana", - "extensions": ["mj2","mjp2"] - }, - "video/mp1s": { - "source": "iana" - }, - "video/mp2p": { - "source": "iana" - }, - "video/mp2t": { - "source": "iana", - "extensions": ["ts"] - }, - "video/mp4": { - "source": "iana", - "compressible": false, - "extensions": ["mp4","mp4v","mpg4"] - }, - "video/mp4v-es": { - "source": "iana" - }, - "video/mpeg": { - "source": "iana", - "compressible": false, - "extensions": ["mpeg","mpg","mpe","m1v","m2v"] - }, - "video/mpeg4-generic": { - "source": "iana" - }, - "video/mpv": { - "source": "iana" - }, - "video/nv": { - "source": "iana" - }, - "video/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["ogv"] - }, - "video/parityfec": { - "source": "iana" - }, - "video/pointer": { - "source": "iana" - }, - "video/quicktime": { - "source": "iana", - "compressible": false, - "extensions": ["qt","mov"] - }, - "video/raptorfec": { - "source": "iana" - }, - "video/raw": { - "source": "iana" - }, - "video/rtp-enc-aescm128": { - "source": "iana" - }, - "video/rtploopback": { - "source": "iana" - }, - "video/rtx": { - "source": "iana" - }, - "video/smpte291": { - "source": "iana" - }, - "video/smpte292m": { - "source": "iana" - }, - "video/ulpfec": { - "source": "iana" - }, - "video/vc1": { - "source": "iana" - }, - "video/vc2": { - "source": "iana" - }, - "video/vnd.cctv": { - "source": "iana" - }, - "video/vnd.dece.hd": { - "source": "iana", - "extensions": ["uvh","uvvh"] - }, - "video/vnd.dece.mobile": { - "source": "iana", - "extensions": ["uvm","uvvm"] - }, - "video/vnd.dece.mp4": { - "source": "iana" - }, - "video/vnd.dece.pd": { - "source": "iana", - "extensions": ["uvp","uvvp"] - }, - "video/vnd.dece.sd": { - "source": "iana", - "extensions": ["uvs","uvvs"] - }, - "video/vnd.dece.video": { - "source": "iana", - "extensions": ["uvv","uvvv"] - }, - "video/vnd.directv.mpeg": { - "source": "iana" - }, - "video/vnd.directv.mpeg-tts": { - "source": "iana" - }, - "video/vnd.dlna.mpeg-tts": { - "source": "iana" - }, - "video/vnd.dvb.file": { - "source": "iana", - "extensions": ["dvb"] - }, - "video/vnd.fvt": { - "source": "iana", - "extensions": ["fvt"] - }, - "video/vnd.hns.video": { - "source": "iana" - }, - "video/vnd.iptvforum.1dparityfec-1010": { - "source": "iana" - }, - "video/vnd.iptvforum.1dparityfec-2005": { - "source": "iana" - }, - "video/vnd.iptvforum.2dparityfec-1010": { - "source": "iana" - }, - "video/vnd.iptvforum.2dparityfec-2005": { - "source": "iana" - }, - "video/vnd.iptvforum.ttsavc": { - "source": "iana" - }, - "video/vnd.iptvforum.ttsmpeg2": { - "source": "iana" - }, - "video/vnd.motorola.video": { - "source": "iana" - }, - "video/vnd.motorola.videop": { - "source": "iana" - }, - "video/vnd.mpegurl": { - "source": "iana", - "extensions": ["mxu","m4u"] - }, - "video/vnd.ms-playready.media.pyv": { - "source": "iana", - "extensions": ["pyv"] - }, - "video/vnd.nokia.interleaved-multimedia": { - "source": "iana" - }, - "video/vnd.nokia.mp4vr": { - "source": "iana" - }, - "video/vnd.nokia.videovoip": { - "source": "iana" - }, - "video/vnd.objectvideo": { - "source": "iana" - }, - "video/vnd.radgamettools.bink": { - "source": "iana" - }, - "video/vnd.radgamettools.smacker": { - "source": "iana" - }, - "video/vnd.sealed.mpeg1": { - "source": "iana" - }, - "video/vnd.sealed.mpeg4": { - "source": "iana" - }, - "video/vnd.sealed.swf": { - "source": "iana" - }, - "video/vnd.sealedmedia.softseal.mov": { - "source": "iana" - }, - "video/vnd.uvvu.mp4": { - "source": "iana", - "extensions": ["uvu","uvvu"] - }, - "video/vnd.vivo": { - "source": "iana", - "extensions": ["viv"] - }, - "video/vp8": { - "source": "iana" - }, - "video/webm": { - "source": "apache", - "compressible": false, - "extensions": ["webm"] - }, - "video/x-f4v": { - "source": "apache", - "extensions": ["f4v"] - }, - "video/x-fli": { - "source": "apache", - "extensions": ["fli"] - }, - "video/x-flv": { - "source": "apache", - "compressible": false, - "extensions": ["flv"] - }, - "video/x-m4v": { - "source": "apache", - "extensions": ["m4v"] - }, - "video/x-matroska": { - "source": "apache", - "compressible": false, - "extensions": ["mkv","mk3d","mks"] - }, - "video/x-mng": { - "source": "apache", - "extensions": ["mng"] - }, - "video/x-ms-asf": { - "source": "apache", - "extensions": ["asf","asx"] - }, - "video/x-ms-vob": { - "source": "apache", - "extensions": ["vob"] - }, - "video/x-ms-wm": { - "source": "apache", - "extensions": ["wm"] - }, - "video/x-ms-wmv": { - "source": "apache", - "compressible": false, - "extensions": ["wmv"] - }, - "video/x-ms-wmx": { - "source": "apache", - "extensions": ["wmx"] - }, - "video/x-ms-wvx": { - "source": "apache", - "extensions": ["wvx"] - }, - "video/x-msvideo": { - "source": "apache", - "extensions": ["avi"] - }, - "video/x-sgi-movie": { - "source": "apache", - "extensions": ["movie"] - }, - "video/x-smv": { - "source": "apache", - "extensions": ["smv"] - }, - "x-conference/x-cooltalk": { - "source": "apache", - "extensions": ["ice"] - }, - "x-shader/x-fragment": { - "compressible": true - }, - "x-shader/x-vertex": { - "compressible": true - } -} - -},{}],1301:[function(require,module,exports){ -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = require('./db.json') - -},{"./db.json":1300}],1302:[function(require,module,exports){ -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var db = require('mime-db') -var extname = require('path').extname - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) - -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false - } - - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } - - return mime -} - -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - - if (!exts || !exts.length) { - return false - } - - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false - } - - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type - } - }) -} - -},{"mime-db":1301,"path":1425}],1303:[function(require,module,exports){ +},{"bn.js":135,"brorand":145}],1129:[function(require,module,exports){ module.exports = assert; function assert(val, msg) { @@ -155551,7 +121677,7 @@ assert.equal = function assertEqual(l, r, msg) { throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; -},{}],1304:[function(require,module,exports){ +},{}],1130:[function(require,module,exports){ 'use strict'; var utils = exports; @@ -155611,7 +121737,7 @@ utils.encode = function encode(arr, enc) { return arr; }; -},{}],1305:[function(require,module,exports){ +},{}],1131:[function(require,module,exports){ const EventEmitter = require('events').EventEmitter const shortid = require('shortid') const { @@ -155735,7 +121861,7 @@ module.exports = (options) => { } } -},{"./constants":1306,"events":370,"globalthis":391,"observable-webworkers":1393,"shortid":1623}],1306:[function(require,module,exports){ +},{"./constants":1132,"events":272,"globalthis":283,"observable-webworkers":1227,"shortid":1393}],1132:[function(require,module,exports){ module.exports = { WORKER_REQUEST_READ_LOCK: 'lock:worker:request-read', @@ -155747,7 +121873,7 @@ module.exports = { MASTER_GRANT_WRITE_LOCK: 'lock:master:grant-write' } -},{}],1307:[function(require,module,exports){ +},{}],1133:[function(require,module,exports){ (function (global){ const node = require('./node') const browser = require('./browser') @@ -155910,7 +122036,7 @@ module.exports.Worker = function (script, Impl) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./browser":1305,"./node":1308,"observable-webworkers":1393,"p-queue":1400,"promise-timeout":1440}],1308:[function(require,module,exports){ +},{"./browser":1131,"./node":1134,"observable-webworkers":1227,"p-queue":1234,"promise-timeout":1260}],1134:[function(require,module,exports){ (function (process){ const EventEmitter = require('events').EventEmitter const shortid = require('shortid') @@ -156011,7 +122137,7 @@ module.exports = (options) => { } }).call(this,require('_process')) -},{"./constants":1306,"_process":1438,"cluster":182,"events":370,"shortid":1623}],1309:[function(require,module,exports){ +},{"./constants":1132,"_process":1258,"cluster":146,"events":272,"shortid":1393}],1135:[function(require,module,exports){ 'use strict' const exp = Math.exp @@ -156081,7 +122207,7 @@ function MovingAverage (timespan) { return ret } -},{}],1310:[function(require,module,exports){ +},{}],1136:[function(require,module,exports){ /** * Helpers. */ @@ -156090,6 +122216,7 @@ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; +var w = d * 7; var y = d * 365.25; /** @@ -156133,7 +122260,7 @@ function parse(str) { if (str.length > 100) { return; } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { @@ -156148,6 +122275,10 @@ function parse(str) { case 'yr': case 'y': return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; case 'days': case 'day': case 'd': @@ -156190,16 +122321,17 @@ function parse(str) { */ function fmtShort(ms) { - if (ms >= d) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { return Math.round(ms / d) + 'd'; } - if (ms >= h) { + if (msAbs >= h) { return Math.round(ms / h) + 'h'; } - if (ms >= m) { + if (msAbs >= m) { return Math.round(ms / m) + 'm'; } - if (ms >= s) { + if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; @@ -156214,28 +122346,32 @@ function fmtShort(ms) { */ function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; } /** * Pluralization helper. */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -},{}],1311:[function(require,module,exports){ +},{}],1137:[function(require,module,exports){ const Multiaddr = require('multiaddr') const reduceValue = (_, v) => v @@ -156295,7 +122431,7 @@ module.exports = (multiaddr, opts) => ( }, '') ) -},{"multiaddr":1314}],1312:[function(require,module,exports){ +},{"multiaddr":1140}],1138:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -156520,7 +122656,7 @@ function protoFromTuple (tup) { } }).call(this,require("buffer").Buffer) -},{"./convert":1313,"./protocols-table":1315,"buffer":217,"varint":1785}],1313:[function(require,module,exports){ +},{"./convert":1139,"./protocols-table":1141,"buffer":181,"varint":1521}],1139:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -156712,7 +122848,7 @@ function buf2onion (buf) { } }).call(this,require("buffer").Buffer) -},{"./protocols-table":1315,"bs58":213,"buffer":217,"hi-base32":439,"ip":463,"is-ip":774,"varint":1785}],1314:[function(require,module,exports){ +},{"./protocols-table":1141,"bs58":177,"buffer":181,"hi-base32":309,"ip":327,"is-ip":613,"varint":1521}],1140:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -157177,7 +123313,7 @@ Multiaddr.resolve = function resolve (addr, callback) { exports = module.exports = Multiaddr }).call(this,require("buffer").Buffer) -},{"./codec":1312,"./protocols-table":1315,"bs58":213,"buffer":217,"class-is":224,"varint":1785}],1315:[function(require,module,exports){ +},{"./codec":1138,"./protocols-table":1141,"bs58":177,"buffer":181,"class-is":187,"varint":1521}],1141:[function(require,module,exports){ 'use strict' function Protocols (proto) { @@ -157263,7 +123399,7 @@ function p (code, size, name, resolvable, path) { module.exports = Protocols -},{}],1316:[function(require,module,exports){ +},{}],1142:[function(require,module,exports){ // base-x encoding // Forked from https://github.com/cryptocoinjs/bs58 // Originally written by Mike Hearn for BitcoinJ @@ -157357,7 +123493,7 @@ module.exports = function base (ALPHABET) { } } -},{"safe-buffer":1593}],1317:[function(require,module,exports){ +},{"safe-buffer":1371}],1143:[function(require,module,exports){ 'use strict' class Base { @@ -157385,7 +123521,7 @@ class Base { module.exports = Base -},{}],1318:[function(require,module,exports){ +},{}],1144:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -157409,7 +123545,7 @@ module.exports = function base16 (alphabet) { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],1319:[function(require,module,exports){ +},{"buffer":181}],1145:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -157494,7 +123630,7 @@ module.exports = function base32 (alphabet) { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],1320:[function(require,module,exports){ +},{"buffer":181}],1146:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -157541,7 +123677,7 @@ module.exports = function base64 (alphabet) { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],1321:[function(require,module,exports){ +},{"buffer":181}],1147:[function(require,module,exports){ 'use strict' const Base = require('./base.js') @@ -157585,7 +123721,7 @@ module.exports = { codes: codes } -},{"./base.js":1317,"./base16":1318,"./base32":1319,"./base64":1320,"base-x":1316}],1322:[function(require,module,exports){ +},{"./base.js":1143,"./base16":1144,"./base32":1145,"./base64":1146,"base-x":1142}],1148:[function(require,module,exports){ (function (Buffer){ /** * Implementation of the [multibase](https://github.com/multiformats/multibase) specification. @@ -157720,7 +123856,7 @@ function getBase (nameOrCode) { } }).call(this,require("buffer").Buffer) -},{"./constants":1321,"buffer":217}],1323:[function(require,module,exports){ +},{"./constants":1147,"buffer":181}],1149:[function(require,module,exports){ (function (Buffer){ // THIS FILE IS GENERATED, DO NO EDIT MANUALLY // For more information see the README.md @@ -158170,7 +124306,7 @@ exports['holochain-sig-v0'] = Buffer.from('a27124', 'hex') exports['holochain-sig-v1'] = Buffer.from('a37124', 'hex') }).call(this,require("buffer").Buffer) -},{"buffer":217}],1324:[function(require,module,exports){ +},{"buffer":181}],1150:[function(require,module,exports){ // THIS FILE IS GENERATED, DO NO EDIT MANUALLY // For more information see the README.md /* eslint-disable dot-notation */ @@ -158620,7 +124756,7 @@ module.exports = Object.freeze({ HOLOCHAIN_SIG_V1: 0xa37124 }) -},{}],1325:[function(require,module,exports){ +},{}],1151:[function(require,module,exports){ (function (Buffer){ /** * Implementation of the multicodec specification. @@ -158750,7 +124886,7 @@ Object.assign(exports, constants) exports.print = require('./print') }).call(this,require("buffer").Buffer) -},{"./constants":1324,"./name-table":1326,"./print":1327,"./util":1328,"./varint-table":1329,"buffer":217,"varint":1785}],1326:[function(require,module,exports){ +},{"./constants":1150,"./name-table":1152,"./print":1153,"./util":1154,"./varint-table":1155,"buffer":181,"varint":1521}],1152:[function(require,module,exports){ 'use strict' const baseTable = require('./base-table') @@ -158764,7 +124900,7 @@ for (let encodingName in baseTable) { nameTable[code.toString('hex')] = encodingName } -},{"./base-table":1323}],1327:[function(require,module,exports){ +},{"./base-table":1149}],1153:[function(require,module,exports){ // THIS FILE IS GENERATED, DO NO EDIT MANUALLY // For more information see the README.md /* eslint-disable dot-notation */ @@ -159213,7 +125349,7 @@ module.exports = Object.freeze({ 0xa37124: 'holochain-sig-v1' }) -},{}],1328:[function(require,module,exports){ +},{}],1154:[function(require,module,exports){ (function (Buffer){ 'use strict' const varint = require('varint') @@ -159246,7 +125382,7 @@ function varintBufferDecode (input) { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"varint":1785}],1329:[function(require,module,exports){ +},{"buffer":181,"varint":1521}],1155:[function(require,module,exports){ 'use strict' const baseTable = require('./base-table') const varintBufferEncode = require('./util').varintBufferEncode @@ -159261,7 +125397,7 @@ for (let encodingName in baseTable) { varintTable[encodingName] = varintBufferEncode(code) } -},{"./base-table":1323,"./util":1328}],1330:[function(require,module,exports){ +},{"./base-table":1149,"./util":1154}],1156:[function(require,module,exports){ /* eslint quote-props: off */ /* eslint key-spacing: off */ 'use strict' @@ -160292,7 +126428,7 @@ exports.defaultLengths = Object.freeze({ 0xb3e0: 0x80 }) -},{}],1331:[function(require,module,exports){ +},{}],1157:[function(require,module,exports){ (function (Buffer){ /** * Multihash implementation in JavaScript. @@ -160521,15 +126657,13 @@ exports.prefix = function prefix (multihash) { } }).call(this,require("buffer").Buffer) -},{"./constants":1330,"bs58":213,"buffer":217,"varint":1785}],1332:[function(require,module,exports){ -arguments[4][467][0].apply(exports,arguments) -},{"_process":1438,"dup":467}],1333:[function(require,module,exports){ -arguments[4][469][0].apply(exports,arguments) -},{"./utils":1337,"blakejs":168,"buffer":217,"dup":469}],1334:[function(require,module,exports){ -arguments[4][470][0].apply(exports,arguments) -},{"buffer":217,"dup":470,"nodeify":1384}],1335:[function(require,module,exports){ -arguments[4][471][0].apply(exports,arguments) -},{"./blake":1333,"./crypto-sha1-2":1334,"./utils":1337,"buffer":217,"dup":471,"js-sha3":1332,"murmurhash3js":1354}],1336:[function(require,module,exports){ +},{"./constants":1156,"bs58":177,"buffer":181,"varint":1521}],1158:[function(require,module,exports){ +arguments[4][331][0].apply(exports,arguments) +},{"./utils":1162,"blakejs":132,"buffer":181,"dup":331}],1159:[function(require,module,exports){ +arguments[4][332][0].apply(exports,arguments) +},{"buffer":181,"dup":332,"nodeify":1225}],1160:[function(require,module,exports){ +arguments[4][333][0].apply(exports,arguments) +},{"./blake":1158,"./crypto-sha1-2":1159,"./utils":1162,"buffer":181,"dup":333,"js-sha3":666,"murmurhash3js":1179}],1161:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -160682,17 +126816,1615 @@ Multihashing.validate = (data, hash, callback) => { } }).call(this,require("buffer").Buffer) -},{"./crypto":1335,"buffer":217,"multihashes":1331}],1337:[function(require,module,exports){ -arguments[4][473][0].apply(exports,arguments) -},{"_process":1438,"buffer":217,"dup":473}],1338:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1339,"_process":1438,"dup":247}],1339:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1341}],1340:[function(require,module,exports){ -arguments[4][249][0].apply(exports,arguments) -},{"dup":249}],1341:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1342:[function(require,module,exports){ +},{"./crypto":1160,"buffer":181,"multihashes":1157}],1162:[function(require,module,exports){ +arguments[4][335][0].apply(exports,arguments) +},{"_process":1258,"buffer":181,"dup":335}],1163:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":1164,"_process":1258,"dup":208}],1164:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],1165:[function(require,module,exports){ +arguments[4][210][0].apply(exports,arguments) +},{"dup":210}],1166:[function(require,module,exports){ +(function (process){ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' + +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' + +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' + +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' + +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' + +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version, options) { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) +} + +}).call(this,require('_process')) +},{"_process":1258}],1167:[function(require,module,exports){ 'use strict' exports = module.exports @@ -160703,7 +128435,7 @@ exports.errors = { MULTICODEC_NOT_SUPPORTED: 'ERR_MULTICODEC_NOT_SUPPORTED' } -},{}],1343:[function(require,module,exports){ +},{}],1168:[function(require,module,exports){ 'use strict' const varint = require('varint') @@ -160861,7 +128593,7 @@ function collectLs (conn) { module.exports = Dialer -},{"../select":1350,"../util":1351,"./../constants":1342,"interface-connection":455,"once":1394,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"pull-stream/throughs/map":1518,"pull-stream/throughs/take":1520,"varint":1785}],1344:[function(require,module,exports){ +},{"../select":1175,"../util":1176,"./../constants":1167,"interface-connection":319,"once":1228,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"pull-stream/throughs/map":1334,"pull-stream/throughs/take":1336,"varint":1521}],1169:[function(require,module,exports){ 'use strict' exports.Listener = exports.listener = require('./listener') @@ -160870,7 +128602,7 @@ exports.matchSemver = require('./listener/match-semver') exports.matchExact = require('./listener/match-exact') exports.constants = require('./constants') -},{"./constants":1342,"./dialer":1343,"./listener":1345,"./listener/match-exact":1347,"./listener/match-semver":1348}],1345:[function(require,module,exports){ +},{"./constants":1167,"./dialer":1168,"./listener":1170,"./listener/match-exact":1172,"./listener/match-semver":1173}],1170:[function(require,module,exports){ 'use strict' const pull = require('pull-stream/pull') @@ -160982,7 +128714,7 @@ class Listener { module.exports = Listener -},{"../select":1350,"./../constants":1342,"./../util":1351,"./ls-handler":1346,"./match-exact":1347,"./select-handler":1349,"assert":78,"interface-connection":455,"pull-stream/pull":1496}],1346:[function(require,module,exports){ +},{"../select":1175,"./../constants":1167,"./../util":1176,"./ls-handler":1171,"./match-exact":1172,"./select-handler":1174,"assert":26,"interface-connection":319,"pull-stream/pull":1312}],1171:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -161022,7 +128754,7 @@ function lsHandler (self, conn) { module.exports = lsHandler }).call(this,require("buffer").Buffer) -},{"buffer":217,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sources/values":1512,"varint":1785}],1347:[function(require,module,exports){ +},{"buffer":181,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sources/values":1328,"varint":1521}],1172:[function(require,module,exports){ 'use strict' /** @@ -161041,7 +128773,7 @@ function matchExact (myProtocol, senderProtocol, callback) { module.exports = matchExact -},{}],1348:[function(require,module,exports){ +},{}],1173:[function(require,module,exports){ 'use strict' const semver = require('semver') @@ -161075,7 +128807,7 @@ function matchSemver (myProtocol, senderProtocol, callback) { module.exports = matchSemver -},{"semver":1613}],1349:[function(require,module,exports){ +},{"semver":1166}],1174:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -161155,7 +128887,7 @@ function matcher (protocol, handlers, callback) { module.exports = selectHandler }).call(this,require("buffer").Buffer) -},{"../util.js":1351,"async/some":147,"buffer":217,"interface-connection":455,"pull-handshake":1472,"pull-length-prefixed":1475}],1350:[function(require,module,exports){ +},{"../util.js":1176,"async/some":97,"buffer":181,"interface-connection":319,"pull-handshake":1289,"pull-length-prefixed":1292}],1175:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -161199,7 +128931,7 @@ function select (multicodec, callback, log) { module.exports = select }).call(this,require("buffer").Buffer) -},{"./constants":1342,"./util":1351,"buffer":217,"err-code":1340,"pull-handshake":1472,"pull-length-prefixed":1475}],1351:[function(require,module,exports){ +},{"./constants":1167,"./util":1176,"buffer":181,"err-code":1165,"pull-handshake":1289,"pull-length-prefixed":1292}],1176:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -161267,10 +128999,10 @@ exports.log.listener = () => { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"debug":1338,"pull-length-prefixed":1475,"pull-stream/pull":1496,"pull-stream/sinks/collect":1497,"pull-stream/sources/values":1512}],1352:[function(require,module,exports){ +},{"buffer":181,"debug":1163,"pull-length-prefixed":1292,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313,"pull-stream/sources/values":1328}],1177:[function(require,module,exports){ module.exports = require('./lib/murmurHash3js'); -},{"./lib/murmurHash3js":1353}],1353:[function(require,module,exports){ +},{"./lib/murmurHash3js":1178}],1178:[function(require,module,exports){ /* jshint -W086: true */ // +----------------------------------------------------------------------+ // | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js @@ -161853,9 +129585,9 @@ module.exports = require('./lib/murmurHash3js'); } })(this); -},{}],1354:[function(require,module,exports){ -arguments[4][1352][0].apply(exports,arguments) -},{"./lib/murmurHash3js":1355,"dup":1352}],1355:[function(require,module,exports){ +},{}],1179:[function(require,module,exports){ +arguments[4][1177][0].apply(exports,arguments) +},{"./lib/murmurHash3js":1180,"dup":1177}],1180:[function(require,module,exports){ /* jshint -W086: true */ // +----------------------------------------------------------------------+ // | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js @@ -162419,7 +130151,7 @@ arguments[4][1352][0].apply(exports,arguments) } })(this); -},{}],1356:[function(require,module,exports){ +},{}],1181:[function(require,module,exports){ /** * Secure random string generator with custom alphabet. * @@ -162472,7 +130204,7 @@ module.exports = function (random, alphabet, size) { * @return {number[]} Random bytes. */ -},{}],1357:[function(require,module,exports){ +},{}],1182:[function(require,module,exports){ var through = require('through2') var split = require('split2') var EOL = require('os').EOL @@ -162505,35 +130237,43 @@ function serialize (opts) { }) } -},{"json-stringify-safe":828,"os":1395,"split2":1673,"through2":1358}],1358:[function(require,module,exports){ -arguments[4][966][0].apply(exports,arguments) -},{"_process":1438,"dup":966,"readable-stream":1569,"util":1776}],1359:[function(require,module,exports){ -(function (global){ -"use strict"; - -// ref: https://github.com/tc39/proposal-global -var getGlobal = function () { - // the only reliable means to get the global object is - // `Function('return this')()` - // However, this causes CSP violations in Chrome apps. - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof global !== 'undefined') { return global; } - throw new Error('unable to locate global object'); -} - -var global = getGlobal(); - -module.exports = exports = global.fetch; - -// Needed for TypeScript and Webpack. -exports.default = global.fetch.bind(global); - -exports.Headers = global.Headers; -exports.Request = global.Request; -exports.Response = global.Response; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1360:[function(require,module,exports){ +},{"json-stringify-safe":667,"os":1229,"split2":1440,"through2":1200}],1183:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],1184:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],1185:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":1187,"./_stream_writable":1189,"_process":1258,"dup":38,"inherits":317}],1186:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":1188,"dup":39,"inherits":317}],1187:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":1183,"../experimentalWarning":1184,"./_stream_duplex":1185,"./internal/streams/async_iterator":1190,"./internal/streams/buffer_list":1191,"./internal/streams/destroy":1192,"./internal/streams/state":1195,"./internal/streams/stream":1196,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":1199,"util":146}],1188:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":1183,"./_stream_duplex":1185,"dup":41,"inherits":317}],1189:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":1183,"./_stream_duplex":1185,"./internal/streams/destroy":1192,"./internal/streams/state":1195,"./internal/streams/stream":1196,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],1190:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":1193,"_process":1258,"dup":43}],1191:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],1192:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],1193:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":1183,"dup":46}],1194:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":1183,"./end-of-stream":1193,"dup":47}],1195:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":1183,"dup":48}],1196:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],1197:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":1185,"./lib/_stream_passthrough.js":1186,"./lib/_stream_readable.js":1187,"./lib/_stream_transform.js":1188,"./lib/_stream_writable.js":1189,"./lib/internal/streams/end-of-stream.js":1193,"./lib/internal/streams/pipeline.js":1194,"dup":50}],1198:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],1199:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":1198}],1200:[function(require,module,exports){ +arguments[4][807][0].apply(exports,arguments) +},{"_process":1258,"dup":807,"readable-stream":1197,"util":1512}],1201:[function(require,module,exports){ /** * Advanced Encryption Standard (AES) implementation. * @@ -163626,7 +131366,7 @@ function _createCipher(options) { return cipher; } -},{"./cipher":1363,"./cipherModes":1364,"./forge":1366,"./util":1383}],1361:[function(require,module,exports){ +},{"./cipher":1204,"./cipherModes":1205,"./forge":1207,"./util":1224}],1202:[function(require,module,exports){ /** * Javascript implementation of Abstract Syntax Notation Number One. * @@ -165036,11 +132776,11 @@ asn1.prettyPrint = function(obj, level, indentation) { return rval; }; -},{"./forge":1366,"./oids":1370,"./util":1383}],1362:[function(require,module,exports){ -arguments[4][1058][0].apply(exports,arguments) -},{"buffer":182,"dup":1058}],1363:[function(require,module,exports){ -arguments[4][1059][0].apply(exports,arguments) -},{"./forge":1366,"./util":1383,"dup":1059}],1364:[function(require,module,exports){ +},{"./forge":1207,"./oids":1211,"./util":1224}],1203:[function(require,module,exports){ +arguments[4][898][0].apply(exports,arguments) +},{"buffer":146,"dup":898}],1204:[function(require,module,exports){ +arguments[4][899][0].apply(exports,arguments) +},{"./forge":1207,"./util":1224,"dup":899}],1205:[function(require,module,exports){ /** * Supported cipher modes. * @@ -166029,7 +133769,7 @@ function from64To32(num) { return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; } -},{"./forge":1366,"./util":1383}],1365:[function(require,module,exports){ +},{"./forge":1207,"./util":1224}],1206:[function(require,module,exports){ /** * DES (Data Encryption Standard) implementation. * @@ -166527,15 +134267,15 @@ function _createCipher(options) { return cipher; } -},{"./cipher":1363,"./cipherModes":1364,"./forge":1366,"./util":1383}],1366:[function(require,module,exports){ -arguments[4][1062][0].apply(exports,arguments) -},{"dup":1062}],1367:[function(require,module,exports){ -arguments[4][1063][0].apply(exports,arguments) -},{"./forge":1366,"./md":1369,"./util":1383,"dup":1063}],1368:[function(require,module,exports){ -arguments[4][1064][0].apply(exports,arguments) -},{"./forge":1366,"dup":1064}],1369:[function(require,module,exports){ -arguments[4][1065][0].apply(exports,arguments) -},{"./forge":1366,"dup":1065}],1370:[function(require,module,exports){ +},{"./cipher":1204,"./cipherModes":1205,"./forge":1207,"./util":1224}],1207:[function(require,module,exports){ +arguments[4][902][0].apply(exports,arguments) +},{"dup":902}],1208:[function(require,module,exports){ +arguments[4][903][0].apply(exports,arguments) +},{"./forge":1207,"./md":1210,"./util":1224,"dup":903}],1209:[function(require,module,exports){ +arguments[4][904][0].apply(exports,arguments) +},{"./forge":1207,"dup":904}],1210:[function(require,module,exports){ +arguments[4][905][0].apply(exports,arguments) +},{"./forge":1207,"dup":905}],1211:[function(require,module,exports){ /** * Object IDs for ASN.1. * @@ -166700,9 +134440,9 @@ _IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); _IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); _IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); -},{"./forge":1366}],1371:[function(require,module,exports){ -arguments[4][1069][0].apply(exports,arguments) -},{"./aes":1360,"./asn1":1361,"./des":1365,"./forge":1366,"./md":1369,"./oids":1370,"./pbkdf2":1372,"./pem":1373,"./random":1377,"./rc2":1378,"./rsa":1379,"./util":1383,"dup":1069}],1372:[function(require,module,exports){ +},{"./forge":1207}],1212:[function(require,module,exports){ +arguments[4][909][0].apply(exports,arguments) +},{"./aes":1201,"./asn1":1202,"./des":1206,"./forge":1207,"./md":1210,"./oids":1211,"./pbkdf2":1213,"./pem":1214,"./random":1218,"./rc2":1219,"./rsa":1220,"./util":1224,"dup":909}],1213:[function(require,module,exports){ (function (Buffer){ /** * Password-Based Key-Derivation Function #2 implementation. @@ -166917,9 +134657,9 @@ module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( }; }).call(this,require("buffer").Buffer) -},{"./forge":1366,"./hmac":1367,"./md":1369,"./util":1383,"buffer":182,"crypto":182}],1373:[function(require,module,exports){ -arguments[4][1071][0].apply(exports,arguments) -},{"./forge":1366,"./util":1383,"dup":1071}],1374:[function(require,module,exports){ +},{"./forge":1207,"./hmac":1208,"./md":1210,"./util":1224,"buffer":146,"crypto":146}],1214:[function(require,module,exports){ +arguments[4][911][0].apply(exports,arguments) +},{"./forge":1207,"./util":1224,"dup":911}],1215:[function(require,module,exports){ /** * Partial implementation of PKCS#1 v2.2: RSA-OEAP * @@ -167197,9 +134937,9 @@ function rsa_mgf1(seed, maskLength, hash) { return t.substring(0, maskLength); } -},{"./forge":1366,"./random":1377,"./sha1":1380,"./util":1383}],1375:[function(require,module,exports){ -arguments[4][1075][0].apply(exports,arguments) -},{"./forge":1366,"./jsbn":1368,"./random":1377,"./util":1383,"dup":1075}],1376:[function(require,module,exports){ +},{"./forge":1207,"./random":1218,"./sha1":1221,"./util":1224}],1216:[function(require,module,exports){ +arguments[4][915][0].apply(exports,arguments) +},{"./forge":1207,"./jsbn":1209,"./random":1218,"./util":1224,"dup":915}],1217:[function(require,module,exports){ (function (process){ /** * A javascript implementation of a cryptographically-secure @@ -167622,7 +135362,7 @@ prng.create = function(plugin) { }; }).call(this,require('_process')) -},{"./forge":1366,"./util":1383,"_process":1438,"crypto":182}],1377:[function(require,module,exports){ +},{"./forge":1207,"./util":1224,"_process":1258,"crypto":146}],1218:[function(require,module,exports){ /** * An API for getting cryptographically-secure random bytes. The bytes are * generated using the Fortuna algorithm devised by Bruce Schneier and @@ -167815,9 +135555,9 @@ module.exports = forge.random; })(); -},{"./aes":1360,"./forge":1366,"./prng":1376,"./sha256":1381,"./util":1383}],1378:[function(require,module,exports){ -arguments[4][1079][0].apply(exports,arguments) -},{"./forge":1366,"./util":1383,"dup":1079}],1379:[function(require,module,exports){ +},{"./aes":1201,"./forge":1207,"./prng":1217,"./sha256":1222,"./util":1224}],1219:[function(require,module,exports){ +arguments[4][919][0].apply(exports,arguments) +},{"./forge":1207,"./util":1224,"dup":919}],1220:[function(require,module,exports){ /** * Javascript implementation of basic RSA algorithms. * @@ -169677,7 +137417,7 @@ function _base64ToBigInt(b64) { return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); } -},{"./asn1":1361,"./forge":1366,"./jsbn":1368,"./oids":1370,"./pkcs1":1374,"./prime":1375,"./random":1377,"./util":1383,"crypto":182}],1380:[function(require,module,exports){ +},{"./asn1":1202,"./forge":1207,"./jsbn":1209,"./oids":1211,"./pkcs1":1215,"./prime":1216,"./random":1218,"./util":1224,"crypto":146}],1221:[function(require,module,exports){ /** * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. * @@ -169998,9 +137738,9 @@ function _update(s, w, bytes) { } } -},{"./forge":1366,"./md":1369,"./util":1383}],1381:[function(require,module,exports){ -arguments[4][1082][0].apply(exports,arguments) -},{"./forge":1366,"./md":1369,"./util":1383,"dup":1082}],1382:[function(require,module,exports){ +},{"./forge":1207,"./md":1210,"./util":1224}],1222:[function(require,module,exports){ +arguments[4][922][0].apply(exports,arguments) +},{"./forge":1207,"./md":1210,"./util":1224,"dup":922}],1223:[function(require,module,exports){ /** * Secure Hash Algorithm with a 1024-bit block size implementation. * @@ -170563,7 +138303,7 @@ function _update(s, w, bytes) { } } -},{"./forge":1366,"./md":1369,"./util":1383}],1383:[function(require,module,exports){ +},{"./forge":1207,"./md":1210,"./util":1224}],1224:[function(require,module,exports){ (function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,setImmediate){ /** * Utility functions for web applications. @@ -173560,7 +141300,7 @@ util.estimateCores = function(options, callback) { }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],require("timers").setImmediate) -},{"./baseN":1362,"./forge":1366,"_process":1438,"buffer":182,"timers":1749}],1384:[function(require,module,exports){ +},{"./baseN":1203,"./forge":1207,"_process":1258,"buffer":146,"timers":1500}],1225:[function(require,module,exports){ (function (process,setImmediate){ var Promise = require('promise'); var isPromise = require('is-promise'); @@ -173617,196 +141357,7 @@ function NodeifyPromise(fn) { NodeifyPromise.prototype = Object.create(Promise.prototype); NodeifyPromise.prototype.constructor = NodeifyPromise; }).call(this,require('_process'),require("timers").setImmediate) -},{"_process":1438,"is-promise":777,"promise":1442,"timers":1749}],1385:[function(require,module,exports){ -arguments[4][368][0].apply(exports,arguments) -},{"dup":368}],1386:[function(require,module,exports){ -var BN = require('bn.js'); -var stripHexPrefix = require('strip-hex-prefix'); - -/** - * Returns a BN object, converts a number value to a BN - * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object - * @return {Object} `output` BN object of the number - * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number - */ -module.exports = function numberToBN(arg) { - if (typeof arg === 'string' || typeof arg === 'number') { - var multiplier = new BN(1); // eslint-disable-line - var formattedString = String(arg).toLowerCase().trim(); - var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; - var stringArg = stripHexPrefix(formattedString); // eslint-disable-line - if (stringArg.substr(0, 1) === '-') { - stringArg = stripHexPrefix(stringArg.slice(1)); - multiplier = new BN(-1, 10); - } - stringArg = stringArg === '' ? '0' : stringArg; - - if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) - || stringArg.match(/^[a-fA-F]+$/) - || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { - return new BN(stringArg, 16).mul(multiplier); - } - - if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { - return new BN(stringArg, 10).mul(multiplier); - } - } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { - if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { - return new BN(arg.toString(10), 10); - } - } - - throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); -} - -},{"bn.js":1385,"strip-hex-prefix":1742}],1387:[function(require,module,exports){ -var crypto = require('crypto') - -function sha (key, body, algorithm) { - return crypto.createHmac(algorithm, key).update(body).digest('base64') -} - -function rsa (key, body) { - return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') -} - -function rfc3986 (str) { - return encodeURIComponent(str) - .replace(/!/g,'%21') - .replace(/\*/g,'%2A') - .replace(/\(/g,'%28') - .replace(/\)/g,'%29') - .replace(/'/g,'%27') -} - -// Maps object to bi-dimensional array -// Converts { foo: 'A', bar: [ 'b', 'B' ]} to -// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] -function map (obj) { - var key, val, arr = [] - for (key in obj) { - val = obj[key] - if (Array.isArray(val)) - for (var i = 0; i < val.length; i++) - arr.push([key, val[i]]) - else if (typeof val === 'object') - for (var prop in val) - arr.push([key + '[' + prop + ']', val[prop]]) - else - arr.push([key, val]) - } - return arr -} - -// Compare function for sort -function compare (a, b) { - return a > b ? 1 : a < b ? -1 : 0 -} - -function generateBase (httpMethod, base_uri, params) { - // adapted from https://dev.twitter.com/docs/auth/oauth and - // https://dev.twitter.com/docs/auth/creating-signature - - // Parameter normalization - // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 - var normalized = map(params) - // 1. First, the name and value of each parameter are encoded - .map(function (p) { - return [ rfc3986(p[0]), rfc3986(p[1] || '') ] - }) - // 2. The parameters are sorted by name, using ascending byte value - // ordering. If two or more parameters share the same name, they - // are sorted by their value. - .sort(function (a, b) { - return compare(a[0], b[0]) || compare(a[1], b[1]) - }) - // 3. The name of each parameter is concatenated to its corresponding - // value using an "=" character (ASCII code 61) as a separator, even - // if the value is empty. - .map(function (p) { return p.join('=') }) - // 4. The sorted name/value pairs are concatenated together into a - // single string by using an "&" character (ASCII code 38) as - // separator. - .join('&') - - var base = [ - rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), - rfc3986(base_uri), - rfc3986(normalized) - ].join('&') - - return base -} - -function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') - - return sha(key, base, 'sha1') -} - -function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') - - return sha(key, base, 'sha256') -} - -function rsasign (httpMethod, base_uri, params, private_key, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = private_key || '' - - return rsa(key, base) -} - -function plaintext (consumer_secret, token_secret) { - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') - - return key -} - -function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { - var method - var skipArgs = 1 - - switch (signMethod) { - case 'RSA-SHA1': - method = rsasign - break - case 'HMAC-SHA1': - method = hmacsign - break - case 'HMAC-SHA256': - method = hmacsign256 - break - case 'PLAINTEXT': - method = plaintext - skipArgs = 4 - break - default: - throw new Error('Signature method not supported: ' + signMethod) - } - - return method.apply(null, [].slice.call(arguments, skipArgs)) -} - -exports.hmacsign = hmacsign -exports.hmacsign256 = hmacsign256 -exports.rsasign = rsasign -exports.plaintext = plaintext -exports.sign = sign -exports.rfc3986 = rfc3986 -exports.generateBase = generateBase -},{"crypto":236}],1388:[function(require,module,exports){ +},{"_process":1258,"is-promise":616,"promise":1262,"timers":1500}],1226:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @@ -173898,2892 +141449,7 @@ module.exports = shouldUseNative() ? Object.assign : function (target, source) { return to; }; -},{}],1389:[function(require,module,exports){ -'use strict'; - -var keysShim; -if (!Object.keys) { - // modified from https://github.com/es-shims/es5-shim - var has = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var isArgs = require('./isArguments'); // eslint-disable-line global-require - var isEnumerable = Object.prototype.propertyIsEnumerable; - var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); - var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); - var dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ]; - var equalsConstructorPrototype = function (o) { - var ctor = o.constructor; - return ctor && ctor.prototype === o; - }; - var excludedKeys = { - $applicationCache: true, - $console: true, - $external: true, - $frame: true, - $frameElement: true, - $frames: true, - $innerHeight: true, - $innerWidth: true, - $onmozfullscreenchange: true, - $onmozfullscreenerror: true, - $outerHeight: true, - $outerWidth: true, - $pageXOffset: true, - $pageYOffset: true, - $parent: true, - $scrollLeft: true, - $scrollTop: true, - $scrollX: true, - $scrollY: true, - $self: true, - $webkitIndexedDB: true, - $webkitStorageInfo: true, - $window: true - }; - var hasAutomationEqualityBug = (function () { - /* global window */ - if (typeof window === 'undefined') { return false; } - for (var k in window) { - try { - if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { - try { - equalsConstructorPrototype(window[k]); - } catch (e) { - return true; - } - } - } catch (e) { - return true; - } - } - return false; - }()); - var equalsConstructorPrototypeIfNotBuggy = function (o) { - /* global window */ - if (typeof window === 'undefined' || !hasAutomationEqualityBug) { - return equalsConstructorPrototype(o); - } - try { - return equalsConstructorPrototype(o); - } catch (e) { - return false; - } - }; - - keysShim = function keys(object) { - var isObject = object !== null && typeof object === 'object'; - var isFunction = toStr.call(object) === '[object Function]'; - var isArguments = isArgs(object); - var isString = isObject && toStr.call(object) === '[object String]'; - var theKeys = []; - - if (!isObject && !isFunction && !isArguments) { - throw new TypeError('Object.keys called on a non-object'); - } - - var skipProto = hasProtoEnumBug && isFunction; - if (isString && object.length > 0 && !has.call(object, 0)) { - for (var i = 0; i < object.length; ++i) { - theKeys.push(String(i)); - } - } - - if (isArguments && object.length > 0) { - for (var j = 0; j < object.length; ++j) { - theKeys.push(String(j)); - } - } else { - for (var name in object) { - if (!(skipProto && name === 'prototype') && has.call(object, name)) { - theKeys.push(String(name)); - } - } - } - - if (hasDontEnumBug) { - var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); - - for (var k = 0; k < dontEnums.length; ++k) { - if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { - theKeys.push(dontEnums[k]); - } - } - } - return theKeys; - }; -} -module.exports = keysShim; - -},{"./isArguments":1391}],1390:[function(require,module,exports){ -'use strict'; - -var slice = Array.prototype.slice; -var isArgs = require('./isArguments'); - -var origKeys = Object.keys; -var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); - -var originalKeys = Object.keys; - -keysShim.shim = function shimObjectKeys() { - if (Object.keys) { - var keysWorksWithArguments = (function () { - // Safari 5.0 bug - var args = Object.keys(arguments); - return args && args.length === arguments.length; - }(1, 2)); - if (!keysWorksWithArguments) { - Object.keys = function keys(object) { // eslint-disable-line func-name-matching - if (isArgs(object)) { - return originalKeys(slice.call(object)); - } - return originalKeys(object); - }; - } - } else { - Object.keys = keysShim; - } - return Object.keys || keysShim; -}; - -module.exports = keysShim; - -},{"./implementation":1389,"./isArguments":1391}],1391:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; - -module.exports = function isArguments(value) { - var str = toStr.call(value); - var isArgs = str === '[object Arguments]'; - if (!isArgs) { - isArgs = str !== '[object Array]' && - value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - toStr.call(value.callee) === '[object Function]'; - } - return isArgs; -}; - -},{}],1392:[function(require,module,exports){ -// This file is the concatenation of many js files. -// See http://github.com/jimhigson/oboe.js for the raw source - -// having a local undefined, window, Object etc allows slightly better minification: -(function (window, Object, Array, Error, JSON, undefined ) { - - // v2.1.3-15-g7432b49 - -/* - -Copyright (c) 2013, Jim Higson - -All rights reserved. - -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. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT -HOLDER OR CONTRIBUTORS 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. - -*/ - -/** - * Partially complete a function. - * - * var add3 = partialComplete( function add(a,b){return a+b}, 3 ); - * - * add3(4) // gives 7 - * - * function wrap(left, right, cen){return left + " " + cen + " " + right;} - * - * var pirateGreeting = partialComplete( wrap , "I'm", ", a mighty pirate!" ); - * - * pirateGreeting("Guybrush Threepwood"); - * // gives "I'm Guybrush Threepwood, a mighty pirate!" - */ -var partialComplete = varArgs(function( fn, args ) { - - // this isn't the shortest way to write this but it does - // avoid creating a new array each time to pass to fn.apply, - // otherwise could just call boundArgs.concat(callArgs) - - var numBoundArgs = args.length; - - return varArgs(function( callArgs ) { - - for (var i = 0; i < callArgs.length; i++) { - args[numBoundArgs + i] = callArgs[i]; - } - - args.length = numBoundArgs + callArgs.length; - - return fn.apply(this, args); - }); - }), - -/** - * Compose zero or more functions: - * - * compose(f1, f2, f3)(x) = f1(f2(f3(x)))) - * - * The last (inner-most) function may take more than one parameter: - * - * compose(f1, f2, f3)(x,y) = f1(f2(f3(x,y)))) - */ - compose = varArgs(function(fns) { - - var fnsList = arrayAsList(fns); - - function next(params, curFn) { - return [apply(params, curFn)]; - } - - return varArgs(function(startParams){ - - return foldR(next, startParams, fnsList)[0]; - }); - }); - -/** - * A more optimised version of compose that takes exactly two functions - * @param f1 - * @param f2 - */ -function compose2(f1, f2){ - return function(){ - return f1.call(this,f2.apply(this,arguments)); - } -} - -/** - * Generic form for a function to get a property from an object - * - * var o = { - * foo:'bar' - * } - * - * var getFoo = attr('foo') - * - * fetFoo(o) // returns 'bar' - * - * @param {String} key the property name - */ -function attr(key) { - return function(o) { return o[key]; }; -} - -/** - * Call a list of functions with the same args until one returns a - * truthy result. Similar to the || operator. - * - * So: - * lazyUnion([f1,f2,f3 ... fn])( p1, p2 ... pn ) - * - * Is equivalent to: - * apply([p1, p2 ... pn], f1) || - * apply([p1, p2 ... pn], f2) || - * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn]) - * - * @returns the first return value that is given that is truthy. - */ - var lazyUnion = varArgs(function(fns) { - - return varArgs(function(params){ - - var maybeValue; - - for (var i = 0; i < len(fns); i++) { - - maybeValue = apply(params, fns[i]); - - if( maybeValue ) { - return maybeValue; - } - } - }); - }); - -/** - * This file declares various pieces of functional programming. - * - * This isn't a general purpose functional library, to keep things small it - * has just the parts useful for Oboe.js. - */ - - -/** - * Call a single function with the given arguments array. - * Basically, a functional-style version of the OO-style Function#apply for - * when we don't care about the context ('this') of the call. - * - * The order of arguments allows partial completion of the arguments array - */ -function apply(args, fn) { - return fn.apply(undefined, args); -} - -/** - * Define variable argument functions but cut out all that tedious messing about - * with the arguments object. Delivers the variable-length part of the arguments - * list as an array. - * - * Eg: - * - * var myFunction = varArgs( - * function( fixedArgument, otherFixedArgument, variableNumberOfArguments ){ - * console.log( variableNumberOfArguments ); - * } - * ) - * - * myFunction('a', 'b', 1, 2, 3); // logs [1,2,3] - * - * var myOtherFunction = varArgs(function( variableNumberOfArguments ){ - * console.log( variableNumberOfArguments ); - * }) - * - * myFunction(1, 2, 3); // logs [1,2,3] - * - */ -function varArgs(fn){ - - var numberOfFixedArguments = fn.length -1, - slice = Array.prototype.slice; - - - if( numberOfFixedArguments == 0 ) { - // an optimised case for when there are no fixed args: - - return function(){ - return fn.call(this, slice.call(arguments)); - } - - } else if( numberOfFixedArguments == 1 ) { - // an optimised case for when there are is one fixed args: - - return function(){ - return fn.call(this, arguments[0], slice.call(arguments, 1)); - } - } - - // general case - - // we know how many arguments fn will always take. Create a - // fixed-size array to hold that many, to be re-used on - // every call to the returned function - var argsHolder = Array(fn.length); - - return function(){ - - for (var i = 0; i < numberOfFixedArguments; i++) { - argsHolder[i] = arguments[i]; - } - - argsHolder[numberOfFixedArguments] = - slice.call(arguments, numberOfFixedArguments); - - return fn.apply( this, argsHolder); - } -} - - -/** - * Swap the order of parameters to a binary function - * - * A bit like this flip: http://zvon.org/other/haskell/Outputprelude/flip_f.html - */ -function flip(fn){ - return function(a, b){ - return fn(b,a); - } -} - - -/** - * Create a function which is the intersection of two other functions. - * - * Like the && operator, if the first is truthy, the second is never called, - * otherwise the return value from the second is returned. - */ -function lazyIntersection(fn1, fn2) { - - return function (param) { - - return fn1(param) && fn2(param); - }; -} - -/** - * A function which does nothing - */ -function noop(){} - -/** - * A function which is always happy - */ -function always(){return true} - -/** - * Create a function which always returns the same - * value - * - * var return3 = functor(3); - * - * return3() // gives 3 - * return3() // still gives 3 - * return3() // will always give 3 - */ -function functor(val){ - return function(){ - return val; - } -} - -/** - * This file defines some loosely associated syntactic sugar for - * Javascript programming - */ - - -/** - * Returns true if the given candidate is of type T - */ -function isOfType(T, maybeSomething){ - return maybeSomething && maybeSomething.constructor === T; -} - -var len = attr('length'), - isString = partialComplete(isOfType, String); - -/** - * I don't like saying this: - * - * foo !=== undefined - * - * because of the double-negative. I find this: - * - * defined(foo) - * - * easier to read. - */ -function defined( value ) { - return value !== undefined; -} - -/** - * Returns true if object o has a key named like every property in - * the properties array. Will give false if any are missing, or if o - * is not an object. - */ -function hasAllProperties(fieldList, o) { - - return (o instanceof Object) - && - all(function (field) { - return (field in o); - }, fieldList); -} -/** - * Like cons in Lisp - */ -function cons(x, xs) { - - /* Internally lists are linked 2-element Javascript arrays. - - Ideally the return here would be Object.freeze([x,xs]) - so that bugs related to mutation are found fast. - However, cons is right on the critical path for - performance and this slows oboe-mark down by - ~25%. Under theoretical future JS engines that freeze more - efficiently (possibly even use immutability to - run faster) this should be considered for - restoration. - */ - - return [x,xs]; -} - -/** - * The empty list - */ -var emptyList = null, - -/** - * Get the head of a list. - * - * Ie, head(cons(a,b)) = a - */ - head = attr(0), - -/** - * Get the tail of a list. - * - * Ie, tail(cons(a,b)) = b - */ - tail = attr(1); - - -/** - * Converts an array to a list - * - * asList([a,b,c]) - * - * is equivalent to: - * - * cons(a, cons(b, cons(c, emptyList))) - **/ -function arrayAsList(inputArray){ - - return reverseList( - inputArray.reduce( - flip(cons), - emptyList - ) - ); -} - -/** - * A varargs version of arrayAsList. Works a bit like list - * in LISP. - * - * list(a,b,c) - * - * is equivalent to: - * - * cons(a, cons(b, cons(c, emptyList))) - */ -var list = varArgs(arrayAsList); - -/** - * Convert a list back to a js native array - */ -function listAsArray(list){ - - return foldR( function(arraySoFar, listItem){ - - arraySoFar.unshift(listItem); - return arraySoFar; - - }, [], list ); - -} - -/** - * Map a function over a list - */ -function map(fn, list) { - - return list - ? cons(fn(head(list)), map(fn,tail(list))) - : emptyList - ; -} - -/** - * foldR implementation. Reduce a list down to a single value. - * - * @pram {Function} fn (rightEval, curVal) -> result - */ -function foldR(fn, startValue, list) { - - return list - ? fn(foldR(fn, startValue, tail(list)), head(list)) - : startValue - ; -} - -/** - * foldR implementation. Reduce a list down to a single value. - * - * @pram {Function} fn (rightEval, curVal) -> result - */ -function foldR1(fn, list) { - - return tail(list) - ? fn(foldR1(fn, tail(list)), head(list)) - : head(list) - ; -} - - -/** - * Return a list like the one given but with the first instance equal - * to item removed - */ -function without(list, test, removedFn) { - - return withoutInner(list, removedFn || noop); - - function withoutInner(subList, removedFn) { - return subList - ? ( test(head(subList)) - ? (removedFn(head(subList)), tail(subList)) - : cons(head(subList), withoutInner(tail(subList), removedFn)) - ) - : emptyList - ; - } -} - -/** - * Returns true if the given function holds for every item in - * the list, false otherwise - */ -function all(fn, list) { - - return !list || - ( fn(head(list)) && all(fn, tail(list)) ); -} - -/** - * Call every function in a list of functions with the same arguments - * - * This doesn't make any sense if we're doing pure functional because - * it doesn't return anything. Hence, this is only really useful if the - * functions being called have side-effects. - */ -function applyEach(fnList, args) { - - if( fnList ) { - head(fnList).apply(null, args); - - applyEach(tail(fnList), args); - } -} - -/** - * Reverse the order of a list - */ -function reverseList(list){ - - // js re-implementation of 3rd solution from: - // http://www.haskell.org/haskellwiki/99_questions/Solutions/5 - function reverseInner( list, reversedAlready ) { - if( !list ) { - return reversedAlready; - } - - return reverseInner(tail(list), cons(head(list), reversedAlready)) - } - - return reverseInner(list, emptyList); -} - -function first(test, list) { - return list && - (test(head(list)) - ? head(list) - : first(test,tail(list))); -} - -/* - This is a slightly hacked-up browser only version of clarinet - - * some features removed to help keep browser Oboe under - the 5k micro-library limit - * plug directly into event bus - - For the original go here: - https://github.com/dscape/clarinet - - We receive the events: - STREAM_DATA - STREAM_END - - We emit the events: - SAX_KEY - SAX_VALUE_OPEN - SAX_VALUE_CLOSE - FAIL_EVENT - */ - -function clarinet(eventBus) { - "use strict"; - - var - // shortcut some events on the bus - emitSaxKey = eventBus(SAX_KEY).emit, - emitValueOpen = eventBus(SAX_VALUE_OPEN).emit, - emitValueClose = eventBus(SAX_VALUE_CLOSE).emit, - emitFail = eventBus(FAIL_EVENT).emit, - - MAX_BUFFER_LENGTH = 64 * 1024 - , stringTokenPattern = /[\\"\n]/g - , _n = 0 - - // states - , BEGIN = _n++ - , VALUE = _n++ // general stuff - , OPEN_OBJECT = _n++ // { - , CLOSE_OBJECT = _n++ // } - , OPEN_ARRAY = _n++ // [ - , CLOSE_ARRAY = _n++ // ] - , STRING = _n++ // "" - , OPEN_KEY = _n++ // , "a" - , CLOSE_KEY = _n++ // : - , TRUE = _n++ // r - , TRUE2 = _n++ // u - , TRUE3 = _n++ // e - , FALSE = _n++ // a - , FALSE2 = _n++ // l - , FALSE3 = _n++ // s - , FALSE4 = _n++ // e - , NULL = _n++ // u - , NULL2 = _n++ // l - , NULL3 = _n++ // l - , NUMBER_DECIMAL_POINT = _n++ // . - , NUMBER_DIGIT = _n // [0-9] - - // setup initial parser values - , bufferCheckPosition = MAX_BUFFER_LENGTH - , latestError - , c - , p - , textNode = undefined - , numberNode = "" - , slashed = false - , closed = false - , state = BEGIN - , stack = [] - , unicodeS = null - , unicodeI = 0 - , depth = 0 - , position = 0 - , column = 0 //mostly for error reporting - , line = 1 - ; - - function checkBufferLength () { - - var maxActual = 0; - - if (textNode !== undefined && textNode.length > MAX_BUFFER_LENGTH) { - emitError("Max buffer length exceeded: textNode"); - maxActual = Math.max(maxActual, textNode.length); - } - if (numberNode.length > MAX_BUFFER_LENGTH) { - emitError("Max buffer length exceeded: numberNode"); - maxActual = Math.max(maxActual, numberNode.length); - } - - bufferCheckPosition = (MAX_BUFFER_LENGTH - maxActual) - + position; - } - - eventBus(STREAM_DATA).on(handleData); - - /* At the end of the http content close the clarinet - This will provide an error if the total content provided was not - valid json, ie if not all arrays, objects and Strings closed properly */ - eventBus(STREAM_END).on(handleStreamEnd); - - function emitError (errorString) { - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - - latestError = Error(errorString + "\nLn: "+line+ - "\nCol: "+column+ - "\nChr: "+c); - - emitFail(errorReport(undefined, undefined, latestError)); - } - - function handleStreamEnd() { - if( state == BEGIN ) { - // Handle the case where the stream closes without ever receiving - // any input. This isn't an error - response bodies can be blank, - // particularly for 204 http responses - - // Because of how Oboe is currently implemented, we parse a - // completely empty stream as containing an empty object. - // This is because Oboe's done event is only fired when the - // root object of the JSON stream closes. - - // This should be decoupled and attached instead to the input stream - // from the http (or whatever) resource ending. - // If this decoupling could happen the SAX parser could simply emit - // zero events on a completely empty input. - emitValueOpen({}); - emitValueClose(); - - closed = true; - return; - } - - if (state !== VALUE || depth !== 0) - emitError("Unexpected end"); - - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - - closed = true; - } - - function whitespace(c){ - return c == '\r' || c == '\n' || c == ' ' || c == '\t'; - } - - function handleData (chunk) { - - // this used to throw the error but inside Oboe we will have already - // gotten the error when it was emitted. The important thing is to - // not continue with the parse. - if (latestError) - return; - - if (closed) { - return emitError("Cannot write after close"); - } - - var i = 0; - c = chunk[0]; - - while (c) { - if (i > 0) { - p = c; - } - c = chunk[i++]; - if(!c) break; - - position ++; - if (c == "\n") { - line ++; - column = 0; - } else column ++; - switch (state) { - - case BEGIN: - if (c === "{") state = OPEN_OBJECT; - else if (c === "[") state = OPEN_ARRAY; - else if (!whitespace(c)) - return emitError("Non-whitespace before {[."); - continue; - - case OPEN_KEY: - case OPEN_OBJECT: - if (whitespace(c)) continue; - if(state === OPEN_KEY) stack.push(CLOSE_KEY); - else { - if(c === '}') { - emitValueOpen({}); - emitValueClose(); - state = stack.pop() || VALUE; - continue; - } else stack.push(CLOSE_OBJECT); - } - if(c === '"') - state = STRING; - else - return emitError("Malformed object key should start with \" "); - continue; - - case CLOSE_KEY: - case CLOSE_OBJECT: - if (whitespace(c)) continue; - - if(c===':') { - if(state === CLOSE_OBJECT) { - stack.push(CLOSE_OBJECT); - - if (textNode !== undefined) { - // was previously (in upstream Clarinet) one event - // - object open came with the text of the first - emitValueOpen({}); - emitSaxKey(textNode); - textNode = undefined; - } - depth++; - } else { - if (textNode !== undefined) { - emitSaxKey(textNode); - textNode = undefined; - } - } - state = VALUE; - } else if (c==='}') { - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - emitValueClose(); - depth--; - state = stack.pop() || VALUE; - } else if(c===',') { - if(state === CLOSE_OBJECT) - stack.push(CLOSE_OBJECT); - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - state = OPEN_KEY; - } else - return emitError('Bad object'); - continue; - - case OPEN_ARRAY: // after an array there always a value - case VALUE: - if (whitespace(c)) continue; - if(state===OPEN_ARRAY) { - emitValueOpen([]); - depth++; - state = VALUE; - if(c === ']') { - emitValueClose(); - depth--; - state = stack.pop() || VALUE; - continue; - } else { - stack.push(CLOSE_ARRAY); - } - } - if(c === '"') state = STRING; - else if(c === '{') state = OPEN_OBJECT; - else if(c === '[') state = OPEN_ARRAY; - else if(c === 't') state = TRUE; - else if(c === 'f') state = FALSE; - else if(c === 'n') state = NULL; - else if(c === '-') { // keep and continue - numberNode += c; - } else if(c==='0') { - numberNode += c; - state = NUMBER_DIGIT; - } else if('123456789'.indexOf(c) !== -1) { - numberNode += c; - state = NUMBER_DIGIT; - } else - return emitError("Bad value"); - continue; - - case CLOSE_ARRAY: - if(c===',') { - stack.push(CLOSE_ARRAY); - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - state = VALUE; - } else if (c===']') { - if (textNode !== undefined) { - emitValueOpen(textNode); - emitValueClose(); - textNode = undefined; - } - emitValueClose(); - depth--; - state = stack.pop() || VALUE; - } else if (whitespace(c)) - continue; - else - return emitError('Bad array'); - continue; - - case STRING: - if (textNode === undefined) { - textNode = ""; - } - - // thanks thejh, this is an about 50% performance improvement. - var starti = i-1; - - STRING_BIGLOOP: while (true) { - - // zero means "no unicode active". 1-4 mean "parse some more". end after 4. - while (unicodeI > 0) { - unicodeS += c; - c = chunk.charAt(i++); - if (unicodeI === 4) { - // TODO this might be slow? well, probably not used too often anyway - textNode += String.fromCharCode(parseInt(unicodeS, 16)); - unicodeI = 0; - starti = i-1; - } else { - unicodeI++; - } - // we can just break here: no stuff we skipped that still has to be sliced out or so - if (!c) break STRING_BIGLOOP; - } - if (c === '"' && !slashed) { - state = stack.pop() || VALUE; - textNode += chunk.substring(starti, i-1); - break; - } - if (c === '\\' && !slashed) { - slashed = true; - textNode += chunk.substring(starti, i-1); - c = chunk.charAt(i++); - if (!c) break; - } - if (slashed) { - slashed = false; - if (c === 'n') { textNode += '\n'; } - else if (c === 'r') { textNode += '\r'; } - else if (c === 't') { textNode += '\t'; } - else if (c === 'f') { textNode += '\f'; } - else if (c === 'b') { textNode += '\b'; } - else if (c === 'u') { - // \uxxxx. meh! - unicodeI = 1; - unicodeS = ''; - } else { - textNode += c; - } - c = chunk.charAt(i++); - starti = i-1; - if (!c) break; - else continue; - } - - stringTokenPattern.lastIndex = i; - var reResult = stringTokenPattern.exec(chunk); - if (!reResult) { - i = chunk.length+1; - textNode += chunk.substring(starti, i-1); - break; - } - i = reResult.index+1; - c = chunk.charAt(reResult.index); - if (!c) { - textNode += chunk.substring(starti, i-1); - break; - } - } - continue; - - case TRUE: - if (!c) continue; // strange buffers - if (c==='r') state = TRUE2; - else - return emitError( 'Invalid true started with t'+ c); - continue; - - case TRUE2: - if (!c) continue; - if (c==='u') state = TRUE3; - else - return emitError('Invalid true started with tr'+ c); - continue; - - case TRUE3: - if (!c) continue; - if(c==='e') { - emitValueOpen(true); - emitValueClose(); - state = stack.pop() || VALUE; - } else - return emitError('Invalid true started with tru'+ c); - continue; - - case FALSE: - if (!c) continue; - if (c==='a') state = FALSE2; - else - return emitError('Invalid false started with f'+ c); - continue; - - case FALSE2: - if (!c) continue; - if (c==='l') state = FALSE3; - else - return emitError('Invalid false started with fa'+ c); - continue; - - case FALSE3: - if (!c) continue; - if (c==='s') state = FALSE4; - else - return emitError('Invalid false started with fal'+ c); - continue; - - case FALSE4: - if (!c) continue; - if (c==='e') { - emitValueOpen(false); - emitValueClose(); - state = stack.pop() || VALUE; - } else - return emitError('Invalid false started with fals'+ c); - continue; - - case NULL: - if (!c) continue; - if (c==='u') state = NULL2; - else - return emitError('Invalid null started with n'+ c); - continue; - - case NULL2: - if (!c) continue; - if (c==='l') state = NULL3; - else - return emitError('Invalid null started with nu'+ c); - continue; - - case NULL3: - if (!c) continue; - if(c==='l') { - emitValueOpen(null); - emitValueClose(); - state = stack.pop() || VALUE; - } else - return emitError('Invalid null started with nul'+ c); - continue; - - case NUMBER_DECIMAL_POINT: - if(c==='.') { - numberNode += c; - state = NUMBER_DIGIT; - } else - return emitError('Leading zero not followed by .'); - continue; - - case NUMBER_DIGIT: - if('0123456789'.indexOf(c) !== -1) numberNode += c; - else if (c==='.') { - if(numberNode.indexOf('.')!==-1) - return emitError('Invalid number has two dots'); - numberNode += c; - } else if (c==='e' || c==='E') { - if(numberNode.indexOf('e')!==-1 || - numberNode.indexOf('E')!==-1 ) - return emitError('Invalid number has two exponential'); - numberNode += c; - } else if (c==="+" || c==="-") { - if(!(p==='e' || p==='E')) - return emitError('Invalid symbol in number'); - numberNode += c; - } else { - if (numberNode) { - emitValueOpen(parseFloat(numberNode)); - emitValueClose(); - numberNode = ""; - } - i--; // go back one - state = stack.pop() || VALUE; - } - continue; - - default: - return emitError("Unknown state: " + state); - } - } - if (position >= bufferCheckPosition) - checkBufferLength(); - } -} - - -/** - * A bridge used to assign stateless functions to listen to clarinet. - * - * As well as the parameter from clarinet, each callback will also be passed - * the result of the last callback. - * - * This may also be used to clear all listeners by assigning zero handlers: - * - * ascentManager( clarinet, {} ) - */ -function ascentManager(oboeBus, handlers){ - "use strict"; - - var listenerId = {}, - ascent; - - function stateAfter(handler) { - return function(param){ - ascent = handler( ascent, param); - } - } - - for( var eventName in handlers ) { - - oboeBus(eventName).on(stateAfter(handlers[eventName]), listenerId); - } - - oboeBus(NODE_SWAP).on(function(newNode) { - - var oldHead = head(ascent), - key = keyOf(oldHead), - ancestors = tail(ascent), - parentNode; - - if( ancestors ) { - parentNode = nodeOf(head(ancestors)); - parentNode[key] = newNode; - } - }); - - oboeBus(NODE_DROP).on(function() { - - var oldHead = head(ascent), - key = keyOf(oldHead), - ancestors = tail(ascent), - parentNode; - - if( ancestors ) { - parentNode = nodeOf(head(ancestors)); - - delete parentNode[key]; - } - }); - - oboeBus(ABORTING).on(function(){ - - for( var eventName in handlers ) { - oboeBus(eventName).un(listenerId); - } - }); -} - -// based on gist https://gist.github.com/monsur/706839 - -/** - * XmlHttpRequest's getAllResponseHeaders() method returns a string of response - * headers according to the format described here: - * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method - * This method parses that string into a user-friendly key/value pair object. - */ -function parseResponseHeaders(headerStr) { - var headers = {}; - - headerStr && headerStr.split('\u000d\u000a') - .forEach(function(headerPair){ - - // Can't use split() here because it does the wrong thing - // if the header value has the string ": " in it. - var index = headerPair.indexOf('\u003a\u0020'); - - headers[headerPair.substring(0, index)] - = headerPair.substring(index + 2); - }); - - return headers; -} - -/** - * Detect if a given URL is cross-origin in the scope of the - * current page. - * - * Browser only (since cross-origin has no meaning in Node.js) - * - * @param {Object} pageLocation - as in window.location - * @param {Object} ajaxHost - an object like window.location describing the - * origin of the url that we want to ajax in - */ -function isCrossOrigin(pageLocation, ajaxHost) { - - /* - * NB: defaultPort only knows http and https. - * Returns undefined otherwise. - */ - function defaultPort(protocol) { - return {'http:':80, 'https:':443}[protocol]; - } - - function portOf(location) { - // pageLocation should always have a protocol. ajaxHost if no port or - // protocol is specified, should use the port of the containing page - - return location.port || defaultPort(location.protocol||pageLocation.protocol); - } - - // if ajaxHost doesn't give a domain, port is the same as pageLocation - // it can't give a protocol but not a domain - // it can't give a port but not a domain - - return !!( (ajaxHost.protocol && (ajaxHost.protocol != pageLocation.protocol)) || - (ajaxHost.host && (ajaxHost.host != pageLocation.host)) || - (ajaxHost.host && (portOf(ajaxHost) != portOf(pageLocation))) - ); -} - -/* turn any url into an object like window.location */ -function parseUrlOrigin(url) { - // url could be domain-relative - // url could give a domain - - // cross origin means: - // same domain - // same port - // some protocol - // so, same everything up to the first (single) slash - // if such is given - // - // can ignore everything after that - - var URL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/, - - // if no match, use an empty array so that - // subexpressions 1,2,3 are all undefined - // and will ultimately return all empty - // strings as the parse result: - urlHostMatch = URL_HOST_PATTERN.exec(url) || []; - - return { - protocol: urlHostMatch[1] || '', - host: urlHostMatch[2] || '', - port: urlHostMatch[3] || '' - }; -} - -function httpTransport(){ - return new XMLHttpRequest(); -} - -/** - * A wrapper around the browser XmlHttpRequest object that raises an - * event whenever a new part of the response is available. - * - * In older browsers progressive reading is impossible so all the - * content is given in a single call. For newer ones several events - * should be raised, allowing progressive interpretation of the response. - * - * @param {Function} oboeBus an event bus local to this Oboe instance - * @param {XMLHttpRequest} xhr the xhr to use as the transport. Under normal - * operation, will have been created using httpTransport() above - * but for tests a stub can be provided instead. - * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE' - * @param {String} url the url to make a request to - * @param {String|Null} data some content to be sent with the request. - * Only valid if method is POST or PUT. - * @param {Object} [headers] the http request headers to send - * @param {boolean} withCredentials the XHR withCredentials property will be - * set to this value - */ -function streamingHttp(oboeBus, xhr, method, url, data, headers, withCredentials) { - - "use strict"; - - var emitStreamData = oboeBus(STREAM_DATA).emit, - emitFail = oboeBus(FAIL_EVENT).emit, - numberOfCharsAlreadyGivenToCallback = 0, - stillToSendStartEvent = true; - - // When an ABORTING message is put on the event bus abort - // the ajax request - oboeBus( ABORTING ).on( function(){ - - // if we keep the onreadystatechange while aborting the XHR gives - // a callback like a successful call so first remove this listener - // by assigning null: - xhr.onreadystatechange = null; - - xhr.abort(); - }); - - /** - * Handle input from the underlying xhr: either a state change, - * the progress event or the request being complete. - */ - function handleProgress() { - - var textSoFar = xhr.responseText, - newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback); - - - /* Raise the event for new text. - - On older browsers, the new text is the whole response. - On newer/better ones, the fragment part that we got since - last progress. */ - - if( newText ) { - emitStreamData( newText ); - } - - numberOfCharsAlreadyGivenToCallback = len(textSoFar); - } - - - if('onprogress' in xhr){ // detect browser support for progressive delivery - xhr.onprogress = handleProgress; - } - - xhr.onreadystatechange = function() { - - function sendStartIfNotAlready() { - // Internet Explorer is very unreliable as to when xhr.status etc can - // be read so has to be protected with try/catch and tried again on - // the next readyState if it fails - try{ - stillToSendStartEvent && oboeBus( HTTP_START ).emit( - xhr.status, - parseResponseHeaders(xhr.getAllResponseHeaders()) ); - stillToSendStartEvent = false; - } catch(e){/* do nothing, will try again on next readyState*/} - } - - switch( xhr.readyState ) { - - case 2: // HEADERS_RECEIVED - case 3: // LOADING - return sendStartIfNotAlready(); - - case 4: // DONE - sendStartIfNotAlready(); // if xhr.status hasn't been available yet, it must be NOW, huh IE? - - // is this a 2xx http code? - var successful = String(xhr.status)[0] == 2; - - if( successful ) { - // In Chrome 29 (not 28) no onprogress is emitted when a response - // is complete before the onload. We need to always do handleInput - // in case we get the load but have not had a final progress event. - // This looks like a bug and may change in future but let's take - // the safest approach and assume we might not have received a - // progress event for each part of the response - handleProgress(); - - oboeBus(STREAM_END).emit(); - } else { - - emitFail( errorReport( - xhr.status, - xhr.responseText - )); - } - } - }; - - try{ - - xhr.open(method, url, true); - - for( var headerName in headers ){ - xhr.setRequestHeader(headerName, headers[headerName]); - } - - if( !isCrossOrigin(window.location, parseUrlOrigin(url)) ) { - xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); - } - - xhr.withCredentials = withCredentials; - - xhr.send(data); - - } catch( e ) { - - // To keep a consistent interface with Node, we can't emit an event here. - // Node's streaming http adaptor receives the error as an asynchronous - // event rather than as an exception. If we emitted now, the Oboe user - // has had no chance to add a .fail listener so there is no way - // the event could be useful. For both these reasons defer the - // firing to the next JS frame. - window.setTimeout( - partialComplete(emitFail, errorReport(undefined, undefined, e)) - , 0 - ); - } -} - -var jsonPathSyntax = (function() { - - var - - /** - * Export a regular expression as a simple function by exposing just - * the Regex#exec. This allows regex tests to be used under the same - * interface as differently implemented tests, or for a user of the - * tests to not concern themselves with their implementation as regular - * expressions. - * - * This could also be expressed point-free as: - * Function.prototype.bind.bind(RegExp.prototype.exec), - * - * But that's far too confusing! (and not even smaller once minified - * and gzipped) - */ - regexDescriptor = function regexDescriptor(regex) { - return regex.exec.bind(regex); - } - - /** - * Join several regular expressions and express as a function. - * This allows the token patterns to reuse component regular expressions - * instead of being expressed in full using huge and confusing regular - * expressions. - */ - , jsonPathClause = varArgs(function( componentRegexes ) { - - // The regular expressions all start with ^ because we - // only want to find matches at the start of the - // JSONPath fragment we are inspecting - componentRegexes.unshift(/^/); - - return regexDescriptor( - RegExp( - componentRegexes.map(attr('source')).join('') - ) - ); - }) - - , possiblyCapturing = /(\$?)/ - , namedNode = /([\w-_]+|\*)/ - , namePlaceholder = /()/ - , nodeInArrayNotation = /\["([^"]+)"\]/ - , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ - , fieldList = /{([\w ]*?)}/ - , optionalFieldList = /(?:{([\w ]*?)})?/ - - - // foo or * - , jsonPathNamedNodeInObjectNotation = jsonPathClause( - possiblyCapturing, - namedNode, - optionalFieldList - ) - - // ["foo"] - , jsonPathNamedNodeInArrayNotation = jsonPathClause( - possiblyCapturing, - nodeInArrayNotation, - optionalFieldList - ) - - // [2] or [*] - , jsonPathNumberedNodeInArrayNotation = jsonPathClause( - possiblyCapturing, - numberedNodeInArrayNotation, - optionalFieldList - ) - - // {a b c} - , jsonPathPureDuckTyping = jsonPathClause( - possiblyCapturing, - namePlaceholder, - fieldList - ) - - // .. - , jsonPathDoubleDot = jsonPathClause(/\.\./) - - // . - , jsonPathDot = jsonPathClause(/\./) - - // ! - , jsonPathBang = jsonPathClause( - possiblyCapturing, - /!/ - ) - - // nada! - , emptyString = jsonPathClause(/$/) - - ; - - - /* We export only a single function. When called, this function injects - into another function the descriptors from above. - */ - return function (fn){ - return fn( - lazyUnion( - jsonPathNamedNodeInObjectNotation - , jsonPathNamedNodeInArrayNotation - , jsonPathNumberedNodeInArrayNotation - , jsonPathPureDuckTyping - ) - , jsonPathDoubleDot - , jsonPathDot - , jsonPathBang - , emptyString - ); - }; - -}()); -/** - * Get a new key->node mapping - * - * @param {String|Number} key - * @param {Object|Array|String|Number|null} node a value found in the json - */ -function namedNode(key, node) { - return {key:key, node:node}; -} - -/** get the key of a namedNode */ -var keyOf = attr('key'); - -/** get the node from a namedNode */ -var nodeOf = attr('node'); -/** - * This file provides various listeners which can be used to build up - * a changing ascent based on the callbacks provided by Clarinet. It listens - * to the low-level events from Clarinet and emits higher-level ones. - * - * The building up is stateless so to track a JSON file - * ascentManager.js is required to store the ascent state - * between calls. - */ - - - -/** - * A special value to use in the path list to represent the path 'to' a root - * object (which doesn't really have any path). This prevents the need for - * special-casing detection of the root object and allows it to be treated - * like any other object. We might think of this as being similar to the - * 'unnamed root' domain ".", eg if I go to - * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates - * the unnamed root of the DNS. - * - * This is kept as an object to take advantage that in Javascript's OO objects - * are guaranteed to be distinct, therefore no other object can possibly clash - * with this one. Strings, numbers etc provide no such guarantee. - **/ -var ROOT_PATH = {}; - - -/** - * Create a new set of handlers for clarinet's events, bound to the emit - * function given. - */ -function incrementalContentBuilder( oboeBus ) { - - var emitNodeOpened = oboeBus(NODE_OPENED).emit, - emitNodeClosed = oboeBus(NODE_CLOSED).emit, - emitRootOpened = oboeBus(ROOT_PATH_FOUND).emit, - emitRootClosed = oboeBus(ROOT_NODE_FOUND).emit; - - function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) { - - /* for values in arrays we aren't pre-warned of the coming paths - (Clarinet gives no call to onkey like it does for values in objects) - so if we are in an array we need to create this path ourselves. The - key will be len(parentNode) because array keys are always sequential - numbers. */ - - var parentNode = nodeOf( head( possiblyInconsistentAscent)); - - return isOfType( Array, parentNode) - ? - keyFound( possiblyInconsistentAscent, - len(parentNode), - newDeepestNode - ) - : - // nothing needed, return unchanged - possiblyInconsistentAscent - ; - } - - function nodeOpened( ascent, newDeepestNode ) { - - if( !ascent ) { - // we discovered the root node, - emitRootOpened( newDeepestNode); - - return keyFound( ascent, ROOT_PATH, newDeepestNode); - } - - // we discovered a non-root node - - var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), - ancestorBranches = tail( arrayConsistentAscent), - previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); - - appendBuiltContent( - ancestorBranches, - previouslyUnmappedName, - newDeepestNode - ); - - return cons( - namedNode( previouslyUnmappedName, newDeepestNode ), - ancestorBranches - ); - } - - - /** - * Add a new value to the object we are building up to represent the - * parsed JSON - */ - function appendBuiltContent( ancestorBranches, key, node ){ - - nodeOf( head( ancestorBranches))[key] = node; - } - - - /** - * For when we find a new key in the json. - * - * @param {String|Number|Object} newDeepestName the key. If we are in an - * array will be a number, otherwise a string. May take the special - * value ROOT_PATH if the root node has just been found - * - * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode] - * usually this won't be known so can be undefined. Can't use null - * to represent unknown because null is a valid value in JSON - **/ - function keyFound(ascent, newDeepestName, maybeNewDeepestNode) { - - if( ascent ) { // if not root - - // If we have the key but (unless adding to an array) no known value - // yet. Put that key in the output but against no defined value: - appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode ); - } - - var ascentWithNewPath = cons( - namedNode( newDeepestName, - maybeNewDeepestNode), - ascent - ); - - emitNodeOpened( ascentWithNewPath); - - return ascentWithNewPath; - } - - - /** - * For when the current node ends. - */ - function nodeClosed( ascent ) { - - emitNodeClosed( ascent); - - return tail( ascent) || - // If there are no nodes left in the ascent the root node - // just closed. Emit a special event for this: - emitRootClosed(nodeOf(head(ascent))); - } - - var contentBuilderHandlers = {}; - contentBuilderHandlers[SAX_VALUE_OPEN] = nodeOpened; - contentBuilderHandlers[SAX_VALUE_CLOSE] = nodeClosed; - contentBuilderHandlers[SAX_KEY] = keyFound; - return contentBuilderHandlers; -} - -/** - * The jsonPath evaluator compiler used for Oboe.js. - * - * One function is exposed. This function takes a String JSONPath spec and - * returns a function to test candidate ascents for matches. - * - * String jsonPath -> (List ascent) -> Boolean|Object - * - * This file is coded in a pure functional style. That is, no function has - * side effects, every function evaluates to the same value for the same - * arguments and no variables are reassigned. - */ -// the call to jsonPathSyntax injects the token syntaxes that are needed -// inside the compiler -var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax, - doubleDotSyntax, - dotSyntax, - bangSyntax, - emptySyntax ) { - - var CAPTURING_INDEX = 1; - var NAME_INDEX = 2; - var FIELD_LIST_INDEX = 3; - - var headKey = compose2(keyOf, head), - headNode = compose2(nodeOf, head); - - /** - * Create an evaluator function for a named path node, expressed in the - * JSONPath like: - * foo - * ["bar"] - * [2] - */ - function nameClause(previousExpr, detection ) { - - var name = detection[NAME_INDEX], - - matchesName = ( !name || name == '*' ) - ? always - : function(ascent){return headKey(ascent) == name}; - - - return lazyIntersection(matchesName, previousExpr); - } - - /** - * Create an evaluator function for a a duck-typed node, expressed like: - * - * {spin, taste, colour} - * .particle{spin, taste, colour} - * *{spin, taste, colour} - */ - function duckTypeClause(previousExpr, detection) { - - var fieldListStr = detection[FIELD_LIST_INDEX]; - - if (!fieldListStr) - return previousExpr; // don't wrap at all, return given expr as-is - - var hasAllrequiredFields = partialComplete( - hasAllProperties, - arrayAsList(fieldListStr.split(/\W+/)) - ), - - isMatch = compose2( - hasAllrequiredFields, - headNode - ); - - return lazyIntersection(isMatch, previousExpr); - } - - /** - * Expression for $, returns the evaluator function - */ - function capture( previousExpr, detection ) { - - // extract meaning from the detection - var capturing = !!detection[CAPTURING_INDEX]; - - if (!capturing) - return previousExpr; // don't wrap at all, return given expr as-is - - return lazyIntersection(previousExpr, head); - - } - - /** - * Create an evaluator function that moves onto the next item on the - * lists. This function is the place where the logic to move up a - * level in the ascent exists. - * - * Eg, for JSONPath ".foo" we need skip1(nameClause(always, [,'foo'])) - */ - function skip1(previousExpr) { - - - if( previousExpr == always ) { - /* If there is no previous expression this consume command - is at the start of the jsonPath. - Since JSONPath specifies what we'd like to find but not - necessarily everything leading down to it, when running - out of JSONPath to check against we default to true */ - return always; - } - - /** return true if the ascent we have contains only the JSON root, - * false otherwise - */ - function notAtRoot(ascent){ - return headKey(ascent) != ROOT_PATH; - } - - return lazyIntersection( - /* If we're already at the root but there are more - expressions to satisfy, can't consume any more. No match. - - This check is why none of the other exprs have to be able - to handle empty lists; skip1 is the only evaluator that - moves onto the next token and it refuses to do so once it - reaches the last item in the list. */ - notAtRoot, - - /* We are not at the root of the ascent yet. - Move to the next level of the ascent by handing only - the tail to the previous expression */ - compose2(previousExpr, tail) - ); - - } - - /** - * Create an evaluator function for the .. (double dot) token. Consumes - * zero or more levels of the ascent, the fewest that are required to find - * a match when given to previousExpr. - */ - function skipMany(previousExpr) { - - if( previousExpr == always ) { - /* If there is no previous expression this consume command - is at the start of the jsonPath. - Since JSONPath specifies what we'd like to find but not - necessarily everything leading down to it, when running - out of JSONPath to check against we default to true */ - return always; - } - - var - // In JSONPath .. is equivalent to !.. so if .. reaches the root - // the match has succeeded. Ie, we might write ..foo or !..foo - // and both should match identically. - terminalCaseWhenArrivingAtRoot = rootExpr(), - terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr, - recursiveCase = skip1(function(ascent) { - return cases(ascent); - }), - - cases = lazyUnion( - terminalCaseWhenArrivingAtRoot - , terminalCaseWhenPreviousExpressionIsSatisfied - , recursiveCase - ); - - return cases; - } - - /** - * Generate an evaluator for ! - matches only the root element of the json - * and ignores any previous expressions since nothing may precede !. - */ - function rootExpr() { - - return function(ascent){ - return headKey(ascent) == ROOT_PATH; - }; - } - - /** - * Generate a statement wrapper to sit around the outermost - * clause evaluator. - * - * Handles the case where the capturing is implicit because the JSONPath - * did not contain a '$' by returning the last node. - */ - function statementExpr(lastClause) { - - return function(ascent) { - - // kick off the evaluation by passing through to the last clause - var exprMatch = lastClause(ascent); - - return exprMatch === true ? head(ascent) : exprMatch; - }; - } - - /** - * For when a token has been found in the JSONPath input. - * Compiles the parser for that token and returns in combination with the - * parser already generated. - * - * @param {Function} exprs a list of the clause evaluator generators for - * the token that was found - * @param {Function} parserGeneratedSoFar the parser already found - * @param {Array} detection the match given by the regex engine when - * the feature was found - */ - function expressionsReader( exprs, parserGeneratedSoFar, detection ) { - - // if exprs is zero-length foldR will pass back the - // parserGeneratedSoFar as-is so we don't need to treat - // this as a special case - - return foldR( - function( parserGeneratedSoFar, expr ){ - - return expr(parserGeneratedSoFar, detection); - }, - parserGeneratedSoFar, - exprs - ); - - } - - /** - * If jsonPath matches the given detector function, creates a function which - * evaluates against every clause in the clauseEvaluatorGenerators. The - * created function is propagated to the onSuccess function, along with - * the remaining unparsed JSONPath substring. - * - * The intended use is to create a clauseMatcher by filling in - * the first two arguments, thus providing a function that knows - * some syntax to match and what kind of generator to create if it - * finds it. The parameter list once completed is: - * - * (jsonPath, parserGeneratedSoFar, onSuccess) - * - * onSuccess may be compileJsonPathToFunction, to recursively continue - * parsing after finding a match or returnFoundParser to stop here. - */ - function generateClauseReaderIfTokenFound ( - - tokenDetector, clauseEvaluatorGenerators, - - jsonPath, parserGeneratedSoFar, onSuccess) { - - var detected = tokenDetector(jsonPath); - - if(detected) { - var compiledParser = expressionsReader( - clauseEvaluatorGenerators, - parserGeneratedSoFar, - detected - ), - - remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); - - return onSuccess(remainingUnparsedJsonPath, compiledParser); - } - } - - /** - * Partially completes generateClauseReaderIfTokenFound above. - */ - function clauseMatcher(tokenDetector, exprs) { - - return partialComplete( - generateClauseReaderIfTokenFound, - tokenDetector, - exprs - ); - } - - /** - * clauseForJsonPath is a function which attempts to match against - * several clause matchers in order until one matches. If non match the - * jsonPath expression is invalid and an error is thrown. - * - * The parameter list is the same as a single clauseMatcher: - * - * (jsonPath, parserGeneratedSoFar, onSuccess) - */ - var clauseForJsonPath = lazyUnion( - - clauseMatcher(pathNodeSyntax , list( capture, - duckTypeClause, - nameClause, - skip1 )) - - , clauseMatcher(doubleDotSyntax , list( skipMany)) - - // dot is a separator only (like whitespace in other languages) but - // rather than make it a special case, use an empty list of - // expressions when this token is found - , clauseMatcher(dotSyntax , list() ) - - , clauseMatcher(bangSyntax , list( capture, - rootExpr)) - - , clauseMatcher(emptySyntax , list( statementExpr)) - - , function (jsonPath) { - throw Error('"' + jsonPath + '" could not be tokenised') - } - ); - - - /** - * One of two possible values for the onSuccess argument of - * generateClauseReaderIfTokenFound. - * - * When this function is used, generateClauseReaderIfTokenFound simply - * returns the compiledParser that it made, regardless of if there is - * any remaining jsonPath to be compiled. - */ - function returnFoundParser(_remainingJsonPath, compiledParser){ - return compiledParser - } - - /** - * Recursively compile a JSONPath expression. - * - * This function serves as one of two possible values for the onSuccess - * argument of generateClauseReaderIfTokenFound, meaning continue to - * recursively compile. Otherwise, returnFoundParser is given and - * compilation terminates. - */ - function compileJsonPathToFunction( uncompiledJsonPath, - parserGeneratedSoFar ) { - - /** - * On finding a match, if there is remaining text to be compiled - * we want to either continue parsing using a recursive call to - * compileJsonPathToFunction. Otherwise, we want to stop and return - * the parser that we have found so far. - */ - var onFind = uncompiledJsonPath - ? compileJsonPathToFunction - : returnFoundParser; - - return clauseForJsonPath( - uncompiledJsonPath, - parserGeneratedSoFar, - onFind - ); - } - - /** - * This is the function that we expose to the rest of the library. - */ - return function(jsonPath){ - - try { - // Kick off the recursive parsing of the jsonPath - return compileJsonPathToFunction(jsonPath, always); - - } catch( e ) { - throw Error( 'Could not compile "' + jsonPath + - '" because ' + e.message - ); - } - } - -}); - -/** - * A pub/sub which is responsible for a single event type. A - * multi-event type event bus is created by pubSub by collecting - * several of these. - * - * @param {String} eventType - * the name of the events managed by this singleEventPubSub - * @param {singleEventPubSub} [newListener] - * place to notify of new listeners - * @param {singleEventPubSub} [removeListener] - * place to notify of when listeners are removed - */ -function singleEventPubSub(eventType, newListener, removeListener){ - - /** we are optimised for emitting events over firing them. - * As well as the tuple list which stores event ids and - * listeners there is a list with just the listeners which - * can be iterated more quickly when we are emitting - */ - var listenerTupleList, - listenerList; - - function hasId(id){ - return function(tuple) { - return tuple.id == id; - }; - } - - return { - - /** - * @param {Function} listener - * @param {*} listenerId - * an id that this listener can later by removed by. - * Can be of any type, to be compared to other ids using == - */ - on:function( listener, listenerId ) { - - var tuple = { - listener: listener - , id: listenerId || listener // when no id is given use the - // listener function as the id - }; - - if( newListener ) { - newListener.emit(eventType, listener, tuple.id); - } - - listenerTupleList = cons( tuple, listenerTupleList ); - listenerList = cons( listener, listenerList ); - - return this; // chaining - }, - - emit:function () { - applyEach( listenerList, arguments ); - }, - - un: function( listenerId ) { - - var removed; - - listenerTupleList = without( - listenerTupleList, - hasId(listenerId), - function(tuple){ - removed = tuple; - } - ); - - if( removed ) { - listenerList = without( listenerList, function(listener){ - return listener == removed.listener; - }); - - if( removeListener ) { - removeListener.emit(eventType, removed.listener, removed.id); - } - } - }, - - listeners: function(){ - // differs from Node EventEmitter: returns list, not array - return listenerList; - }, - - hasListener: function(listenerId){ - var test = listenerId? hasId(listenerId) : always; - - return defined(first( test, listenerTupleList)); - } - }; -} - -/** - * pubSub is a curried interface for listening to and emitting - * events. - * - * If we get a bus: - * - * var bus = pubSub(); - * - * We can listen to event 'foo' like: - * - * bus('foo').on(myCallback) - * - * And emit event foo like: - * - * bus('foo').emit() - * - * or, with a parameter: - * - * bus('foo').emit('bar') - * - * All functions can be cached and don't need to be - * bound. Ie: - * - * var fooEmitter = bus('foo').emit - * fooEmitter('bar'); // emit an event - * fooEmitter('baz'); // emit another - * - * There's also an uncurried[1] shortcut for .emit and .on: - * - * bus.on('foo', callback) - * bus.emit('foo', 'bar') - * - * [1]: http://zvon.org/other/haskell/Outputprelude/uncurry_f.html - */ -function pubSub(){ - - var singles = {}, - newListener = newSingle('newListener'), - removeListener = newSingle('removeListener'); - - function newSingle(eventName) { - return singles[eventName] = singleEventPubSub( - eventName, - newListener, - removeListener - ); - } - - /** pubSub instances are functions */ - function pubSubInstance( eventName ){ - - return singles[eventName] || newSingle( eventName ); - } - - // add convenience EventEmitter-style uncurried form of 'emit' and 'on' - ['emit', 'on', 'un'].forEach(function(methodName){ - - pubSubInstance[methodName] = varArgs(function(eventName, parameters){ - apply( parameters, pubSubInstance( eventName )[methodName]); - }); - }); - - return pubSubInstance; -} - -/** - * This file declares some constants to use as names for event types. - */ - -var // the events which are never exported are kept as - // the smallest possible representation, in numbers: - _S = 1, - - // fired whenever a new node starts in the JSON stream: - NODE_OPENED = _S++, - - // fired whenever a node closes in the JSON stream: - NODE_CLOSED = _S++, - - // called if a .node callback returns a value - - NODE_SWAP = _S++, - NODE_DROP = _S++, - - FAIL_EVENT = 'fail', - - ROOT_NODE_FOUND = _S++, - ROOT_PATH_FOUND = _S++, - - HTTP_START = 'start', - STREAM_DATA = 'data', - STREAM_END = 'end', - ABORTING = _S++, - - // SAX events butchered from Clarinet - SAX_KEY = _S++, - SAX_VALUE_OPEN = _S++, - SAX_VALUE_CLOSE = _S++; - -function errorReport(statusCode, body, error) { - try{ - var jsonBody = JSON.parse(body); - }catch(e){} - - return { - statusCode:statusCode, - body:body, - jsonBody:jsonBody, - thrown:error - }; -} - -/** - * The pattern adaptor listens for newListener and removeListener - * events. When patterns are added or removed it compiles the JSONPath - * and wires them up. - * - * When nodes and paths are found it emits the fully-qualified match - * events with parameters ready to ship to the outside world - */ - -function patternAdapter(oboeBus, jsonPathCompiler) { - - var predicateEventMap = { - node:oboeBus(NODE_CLOSED) - , path:oboeBus(NODE_OPENED) - }; - - function emitMatchingNode(emitMatch, node, ascent) { - - /* - We're now calling to the outside world where Lisp-style - lists will not be familiar. Convert to standard arrays. - - Also, reverse the order because it is more common to - list paths "root to leaf" than "leaf to root" */ - var descent = reverseList(ascent); - - emitMatch( - node, - - // To make a path, strip off the last item which is the special - // ROOT_PATH token for the 'path' to the root node - listAsArray(tail(map(keyOf,descent))), // path - listAsArray(map(nodeOf, descent)) // ancestors - ); - } - - /* - * Set up the catching of events such as NODE_CLOSED and NODE_OPENED and, if - * matching the specified pattern, propagate to pattern-match events such as - * oboeBus('node:!') - * - * - * - * @param {Function} predicateEvent - * either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED). - * @param {Function} compiledJsonPath - */ - function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){ - - var emitMatch = oboeBus(fullEventName).emit; - - predicateEvent.on( function (ascent) { - - var maybeMatchingMapping = compiledJsonPath(ascent); - - /* Possible values for maybeMatchingMapping are now: - - false: - we did not match - - an object/array/string/number/null: - we matched and have the node that matched. - Because nulls are valid json values this can be null. - - undefined: - we matched but don't have the matching node yet. - ie, we know there is an upcoming node that matches but we - can't say anything else about it. - */ - if (maybeMatchingMapping !== false) { - - emitMatchingNode( - emitMatch, - nodeOf(maybeMatchingMapping), - ascent - ); - } - }, fullEventName); - - oboeBus('removeListener').on( function(removedEventName){ - - // if the fully qualified match event listener is later removed, clean up - // by removing the underlying listener if it was the last using that pattern: - - if( removedEventName == fullEventName ) { - - if( !oboeBus(removedEventName).listeners( )) { - predicateEvent.un( fullEventName ); - } - } - }); - } - - oboeBus('newListener').on( function(fullEventName){ - - var match = /(node|path):(.*)/.exec(fullEventName); - - if( match ) { - var predicateEvent = predicateEventMap[match[1]]; - - if( !predicateEvent.hasListener( fullEventName) ) { - - addUnderlyingListener( - fullEventName, - predicateEvent, - jsonPathCompiler( match[2] ) - ); - } - } - }) - -} - -/** - * The instance API is the thing that is returned when oboe() is called. - * it allows: - * - * - listeners for various events to be added and removed - * - the http response header/headers to be read - */ -function instanceApi(oboeBus, contentSource){ - - var oboeApi, - fullyQualifiedNamePattern = /^(node|path):./, - rootNodeFinishedEvent = oboeBus(ROOT_NODE_FOUND), - emitNodeDrop = oboeBus(NODE_DROP).emit, - emitNodeSwap = oboeBus(NODE_SWAP).emit, - - /** - * Add any kind of listener that the instance api exposes - */ - addListener = varArgs(function( eventId, parameters ){ - - if( oboeApi[eventId] ) { - - // for events added as .on(event, callback), if there is a - // .event() equivalent with special behaviour , pass through - // to that: - apply(parameters, oboeApi[eventId]); - } else { - - // we have a standard Node.js EventEmitter 2-argument call. - // The first parameter is the listener. - var event = oboeBus(eventId), - listener = parameters[0]; - - if( fullyQualifiedNamePattern.test(eventId) ) { - - // allow fully-qualified node/path listeners - // to be added - addForgettableCallback(event, listener); - } else { - - // the event has no special handling, pass through - // directly onto the event bus: - event.on( listener); - } - } - - return oboeApi; // chaining - }), - - /** - * Remove any kind of listener that the instance api exposes - */ - removeListener = function( eventId, p2, p3 ){ - - if( eventId == 'done' ) { - - rootNodeFinishedEvent.un(p2); - - } else if( eventId == 'node' || eventId == 'path' ) { - - // allow removal of node and path - oboeBus.un(eventId + ':' + p2, p3); - } else { - - // we have a standard Node.js EventEmitter 2-argument call. - // The second parameter is the listener. This may be a call - // to remove a fully-qualified node/path listener but requires - // no special handling - var listener = p2; - - oboeBus(eventId).un(listener); - } - - return oboeApi; // chaining - }; - - /** - * Add a callback, wrapped in a try/catch so as to not break the - * execution of Oboe if an exception is thrown (fail events are - * fired instead) - * - * The callback is used as the listener id so that it can later be - * removed using .un(callback) - */ - function addProtectedCallback(eventName, callback) { - oboeBus(eventName).on(protectedCallback(callback), callback); - return oboeApi; // chaining - } - - /** - * Add a callback where, if .forget() is called during the callback's - * execution, the callback will be de-registered - */ - function addForgettableCallback(event, callback, listenerId) { - - // listenerId is optional and if not given, the original - // callback will be used - listenerId = listenerId || callback; - - var safeCallback = protectedCallback(callback); - - event.on( function() { - - var discard = false; - - oboeApi.forget = function(){ - discard = true; - }; - - apply( arguments, safeCallback ); - - delete oboeApi.forget; - - if( discard ) { - event.un(listenerId); - } - }, listenerId); - - return oboeApi; // chaining - } - - /** - * wrap a callback so that if it throws, Oboe.js doesn't crash but instead - * throw the error in another event loop - */ - function protectedCallback( callback ) { - return function() { - try{ - return callback.apply(oboeApi, arguments); - }catch(e) { - setTimeout(function() { - throw new Error(e.message); - }); - } - } - } - - /** - * Return the fully qualified event for when a pattern matches - * either a node or a path - * - * @param type {String} either 'node' or 'path' - */ - function fullyQualifiedPatternMatchEvent(type, pattern) { - return oboeBus(type + ':' + pattern); - } - - function wrapCallbackToSwapNodeIfSomethingReturned( callback ) { - return function() { - var returnValueFromCallback = callback.apply(this, arguments); - - if( defined(returnValueFromCallback) ) { - - if( returnValueFromCallback == oboe.drop ) { - emitNodeDrop(); - } else { - emitNodeSwap(returnValueFromCallback); - } - } - } - } - - function addSingleNodeOrPathListener(eventId, pattern, callback) { - - var effectiveCallback; - - if( eventId == 'node' ) { - effectiveCallback = wrapCallbackToSwapNodeIfSomethingReturned(callback); - } else { - effectiveCallback = callback; - } - - addForgettableCallback( - fullyQualifiedPatternMatchEvent(eventId, pattern), - effectiveCallback, - callback - ); - } - - /** - * Add several listeners at a time, from a map - */ - function addMultipleNodeOrPathListeners(eventId, listenerMap) { - - for( var pattern in listenerMap ) { - addSingleNodeOrPathListener(eventId, pattern, listenerMap[pattern]); - } - } - - /** - * implementation behind .onPath() and .onNode() - */ - function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){ - - if( isString(jsonPathOrListenerMap) ) { - addSingleNodeOrPathListener(eventId, jsonPathOrListenerMap, callback); - - } else { - addMultipleNodeOrPathListeners(eventId, jsonPathOrListenerMap); - } - - return oboeApi; // chaining - } - - - // some interface methods are only filled in after we receive - // values and are noops before that: - oboeBus(ROOT_PATH_FOUND).on( function(rootNode) { - oboeApi.root = functor(rootNode); - }); - - /** - * When content starts make the headers readable through the - * instance API - */ - oboeBus(HTTP_START).on( function(_statusCode, headers) { - - oboeApi.header = function(name) { - return name ? headers[name] - : headers - ; - } - }); - - /** - * Construct and return the public API of the Oboe instance to be - * returned to the calling application - */ - return oboeApi = { - on : addListener, - addListener : addListener, - removeListener : removeListener, - emit : oboeBus.emit, - - node : partialComplete(addNodeOrPathListenerApi, 'node'), - path : partialComplete(addNodeOrPathListenerApi, 'path'), - - done : partialComplete(addForgettableCallback, rootNodeFinishedEvent), - start : partialComplete(addProtectedCallback, HTTP_START ), - - // fail doesn't use protectedCallback because - // could lead to non-terminating loops - fail : oboeBus(FAIL_EVENT).on, - - // public api calling abort fires the ABORTING event - abort : oboeBus(ABORTING).emit, - - // initially return nothing for header and root - header : noop, - root : noop, - - source : contentSource - }; -} - -/** - * This file sits just behind the API which is used to attain a new - * Oboe instance. It creates the new components that are required - * and introduces them to each other. - */ - -function wire (httpMethodName, contentSource, body, headers, withCredentials){ - - var oboeBus = pubSub(); - - // Wire the input stream in if we are given a content source. - // This will usually be the case. If not, the instance created - // will have to be passed content from an external source. - - if( contentSource ) { - - streamingHttp( oboeBus, - httpTransport(), - httpMethodName, - contentSource, - body, - headers, - withCredentials - ); - } - - clarinet(oboeBus); - - ascentManager(oboeBus, incrementalContentBuilder(oboeBus)); - - patternAdapter(oboeBus, jsonPathCompiler); - - return instanceApi(oboeBus, contentSource); -} - -function applyDefaults( passthrough, url, httpMethodName, body, headers, withCredentials, cached ){ - - headers = headers ? - // Shallow-clone the headers array. This allows it to be - // modified without side effects to the caller. We don't - // want to change objects that the user passes in. - JSON.parse(JSON.stringify(headers)) - : {}; - - if( body ) { - if( !isString(body) ) { - - // If the body is not a string, stringify it. This allows objects to - // be given which will be sent as JSON. - body = JSON.stringify(body); - - // Default Content-Type to JSON unless given otherwise. - headers['Content-Type'] = headers['Content-Type'] || 'application/json'; - } - headers['Content-Length'] = headers['Content-Length'] || body.length; - } else { - body = null; - } - - // support cache busting like jQuery.ajax({cache:false}) - function modifiedUrl(baseUrl, cached) { - - if( cached === false ) { - - if( baseUrl.indexOf('?') == -1 ) { - baseUrl += '?'; - } else { - baseUrl += '&'; - } - - baseUrl += '_=' + new Date().getTime(); - } - return baseUrl; - } - - return passthrough( httpMethodName || 'GET', modifiedUrl(url, cached), body, headers, withCredentials || false ); -} - -// export public API -function oboe(arg1) { - - // We use duck-typing to detect if the parameter given is a stream, with the - // below list of parameters. - // Unpipe and unshift would normally be present on a stream but this breaks - // compatibility with Request streams. - // See https://github.com/jimhigson/oboe.js/issues/65 - - var nodeStreamMethodNames = list('resume', 'pause', 'pipe'), - isStream = partialComplete( - hasAllProperties - , nodeStreamMethodNames - ); - - if( arg1 ) { - if (isStream(arg1) || isString(arg1)) { - - // simple version for GETs. Signature is: - // oboe( url ) - // or, under node: - // oboe( readableStream ) - return applyDefaults( - wire, - arg1 // url - ); - - } else { - - // method signature is: - // oboe({method:m, url:u, body:b, headers:{...}}) - - return applyDefaults( - wire, - arg1.url, - arg1.method, - arg1.body, - arg1.headers, - arg1.withCredentials, - arg1.cached - ); - - } - } else { - // wire up a no-AJAX, no-stream Oboe. Will have to have content - // fed in externally and using .emit. - return wire(); - } -} - -/* oboe.drop is a special value. If a node callback returns this value the - parsed node is deleted from the JSON - */ -oboe.drop = function() { - return oboe.drop; -}; - - - if ( typeof define === "function" && define.amd ) { - define( "oboe", [], function () { return oboe; } ); - } else if (typeof exports === 'object') { - module.exports = oboe; - } else { - window.oboe = oboe; - } -})((function(){ - // Access to the window object throws an exception in HTML5 web workers so - // point it to "self" if it runs in a web worker - try { - return window; - } catch (e) { - return self; - } - }()), Object, Array, Error, JSON); - -},{}],1393:[function(require,module,exports){ +},{}],1227:[function(require,module,exports){ const events = {} const observable = (worker) => { @@ -176828,7 +141494,7 @@ observable.dispatchEvent = function () { module.exports = observable -},{}],1394:[function(require,module,exports){ +},{}],1228:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) @@ -176872,7 +141538,7 @@ function onceStrict (fn) { return f } -},{"wrappy":1844}],1395:[function(require,module,exports){ +},{"wrappy":1525}],1229:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; exports.hostname = function () { @@ -176923,23 +141589,7 @@ exports.homedir = function () { return '/' }; -},{}],1396:[function(require,module,exports){ -'use strict'; - -const pDefer = () => { - const deferred = {}; - - deferred.promise = new Promise((resolve, reject) => { - deferred.resolve = resolve; - deferred.reject = reject; - }); - - return deferred; -}; - -module.exports = pDefer; - -},{}],1397:[function(require,module,exports){ +},{}],1230:[function(require,module,exports){ const Fifo = require('fast-fifo') const defer = require('p-defer') @@ -176977,7 +141627,9 @@ module.exports = class PFifo { } } -},{"fast-fifo":377,"p-defer":1396}],1398:[function(require,module,exports){ +},{"fast-fifo":276,"p-defer":1231}],1231:[function(require,module,exports){ +arguments[4][645][0].apply(exports,arguments) +},{"dup":645}],1232:[function(require,module,exports){ 'use strict'; module.exports = (promise, onFinally) => { onFinally = onFinally || (() => {}); @@ -176994,7 +141646,7 @@ module.exports = (promise, onFinally) => { ); }; -},{}],1399:[function(require,module,exports){ +},{}],1233:[function(require,module,exports){ 'use strict'; const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { @@ -177068,7 +141720,7 @@ module.exports = pMap; // TODO: Remove this for the next major release module.exports.default = pMap; -},{}],1400:[function(require,module,exports){ +},{}],1234:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const EventEmitter = require("eventemitter3"); @@ -177088,7 +141740,9 @@ class PQueue extends EventEmitter { this._resolveEmpty = empty; this._resolveIdle = empty; // eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options + // TODO: Remove this `as`. + ); if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap}\` (${typeof options.intervalCap})`); } @@ -177331,7 +141985,7 @@ class PQueue extends EventEmitter { } exports.default = PQueue; -},{"./priority-queue":1402,"eventemitter3":1403,"p-timeout":1404}],1401:[function(require,module,exports){ +},{"./priority-queue":1236,"eventemitter3":271,"p-timeout":1237}],1235:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Port of lower_bound from http://en.cppreference.com/w/cpp/algorithm/lower_bound @@ -177354,7 +142008,7 @@ function lowerBound(array, value, comparator) { } exports.default = lowerBound; -},{}],1402:[function(require,module,exports){ +},{}],1236:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const lower_bound_1 = require("./lower-bound"); @@ -177385,9 +142039,7 @@ class PriorityQueue { } exports.default = PriorityQueue; -},{"./lower-bound":1401}],1403:[function(require,module,exports){ -arguments[4][369][0].apply(exports,arguments) -},{"dup":369}],1404:[function(require,module,exports){ +},{"./lower-bound":1235}],1237:[function(require,module,exports){ 'use strict'; const pFinally = require('p-finally'); @@ -177446,7 +142098,7 @@ module.exports.default = pTimeout; module.exports.TimeoutError = TimeoutError; -},{"p-finally":1398}],1405:[function(require,module,exports){ +},{"p-finally":1232}],1238:[function(require,module,exports){ 'use strict'; const pMap = require('p-map'); @@ -177457,5731 +142109,7 @@ module.exports = pTimes; // TODO: Remove this for the next major release module.exports.default = pTimes; -},{"p-map":1399}],1406:[function(require,module,exports){ -'use strict'; - - -var TYPED_OK = (typeof Uint8Array !== 'undefined') && - (typeof Uint16Array !== 'undefined') && - (typeof Int32Array !== 'undefined'); - -function _has(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} - -exports.assign = function (obj /*from1, from2, from3, ...*/) { - var sources = Array.prototype.slice.call(arguments, 1); - while (sources.length) { - var source = sources.shift(); - if (!source) { continue; } - - if (typeof source !== 'object') { - throw new TypeError(source + 'must be non-object'); - } - - for (var p in source) { - if (_has(source, p)) { - obj[p] = source[p]; - } - } - } - - return obj; -}; - - -// reduce buffer size, avoiding mem copy -exports.shrinkBuf = function (buf, size) { - if (buf.length === size) { return buf; } - if (buf.subarray) { return buf.subarray(0, size); } - buf.length = size; - return buf; -}; - - -var fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (var i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - var i, l, len, pos, chunk, result; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -var fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (var i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// -exports.setTyped = function (on) { - if (on) { - exports.Buf8 = Uint8Array; - exports.Buf16 = Uint16Array; - exports.Buf32 = Int32Array; - exports.assign(exports, fnTyped); - } else { - exports.Buf8 = Array; - exports.Buf16 = Array; - exports.Buf32 = Array; - exports.assign(exports, fnUntyped); - } -}; - -exports.setTyped(TYPED_OK); - -},{}],1407:[function(require,module,exports){ -'use strict'; - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It isn't worth it to make additional optimizations as in original. -// Small size is preferable. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function adler32(adler, buf, len, pos) { - var s1 = (adler & 0xffff) |0, - s2 = ((adler >>> 16) & 0xffff) |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = (s1 + buf[pos++]) |0; - s2 = (s2 + s1) |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return (s1 | (s2 << 16)) |0; -} - - -module.exports = adler32; - -},{}],1408:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -module.exports = { - - /* Allowed flush values; see deflate() and inflate() below for details */ - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_TREES: 6, - - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - //Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - //Z_VERSION_ERROR: -6, - - /* compression levels */ - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - - - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - - /* Possible values of the data_type field (though see inflate()) */ - Z_BINARY: 0, - Z_TEXT: 1, - //Z_ASCII: 1, // = Z_TEXT (deprecated) - Z_UNKNOWN: 2, - - /* The deflate compression method */ - Z_DEFLATED: 8 - //Z_NULL: null // Use -1 or null inline, depending on var type -}; - -},{}],1409:[function(require,module,exports){ -'use strict'; - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; - - for (var n = 0; n < 256; n++) { - c = n; - for (var k = 0; k < 8; k++) { - c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -var crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - var t = crcTable, - end = pos + len; - - crc ^= -1; - - for (var i = pos; i < end; i++) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - - -module.exports = crc32; - -},{}],1410:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = require('../utils/common'); -var trees = require('./trees'); -var adler32 = require('./adler32'); -var crc32 = require('./crc32'); -var msg = require('./messages'); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -var Z_NO_FLUSH = 0; -var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -//var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -//var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -//var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - - -/* compression levels */ -//var Z_NO_COMPRESSION = 0; -//var Z_BEST_SPEED = 1; -//var Z_BEST_COMPRESSION = 9; -var Z_DEFAULT_COMPRESSION = -1; - - -var Z_FILTERED = 1; -var Z_HUFFMAN_ONLY = 2; -var Z_RLE = 3; -var Z_FIXED = 4; -var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -//var Z_BINARY = 0; -//var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - - -/* The deflate compression method */ -var Z_DEFLATED = 8; - -/*============================================================================*/ - - -var MAX_MEM_LEVEL = 9; -/* Maximum value for memLevel in deflateInit2 */ -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_MEM_LEVEL = 8; - - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ -var LITERALS = 256; -/* number of literal bytes 0..255 */ -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ -var D_CODES = 30; -/* number of distance codes */ -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); - -var PRESET_DICT = 0x20; - -var INIT_STATE = 42; -var EXTRA_STATE = 69; -var NAME_STATE = 73; -var COMMENT_STATE = 91; -var HCRC_STATE = 103; -var BUSY_STATE = 113; -var FINISH_STATE = 666; - -var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -var BS_BLOCK_DONE = 2; /* block flush performed */ -var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - var s = strm.state; - - //_tr_flush_bits(s); - var len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { -// put_byte(s, (Byte)(b >> 8)); -// put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - var len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - utils.arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - var chain_length = s.max_chain_length; /* max hash chain length */ - var scan = s.strstart; /* current string */ - var match; /* matched string */ - var len; /* length of current match */ - var best_len = s.prev_length; /* best match length so far */ - var nice_match = s.nice_match; /* stop if match long enough */ - var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - var _win = s.window; // shortcut - - var wmask = s.w_mask; - var prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - var strend = s.strstart + MAX_MATCH; - var scan_end1 = _win[scan + best_len - 1]; - var scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (strend - scan); - scan = strend - MAX_MATCH; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - var _w_size = s.w_size; - var p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - utils.arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; -//#if MIN_MATCH != 3 -// Call update_hash() MIN_MATCH-3 more times -//#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ -// if (s.high_water < s.window_size) { -// var curr = s.strstart + s.lookahead; -// var init = 0; -// -// if (s.high_water < curr) { -// /* Previous high water mark below current data -- zero WIN_INIT -// * bytes or up to end of window, whichever is less. -// */ -// init = s.window_size - curr; -// if (init > WIN_INIT) -// init = WIN_INIT; -// zmemzero(s->window + curr, (unsigned)init); -// s->high_water = curr + init; -// } -// else if (s->high_water < (ulg)curr + WIN_INIT) { -// /* High water mark at or above current data, but below current data -// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -// * to end of window, whichever is less. -// */ -// init = (ulg)curr + WIN_INIT - s->high_water; -// if (init > s->window_size - s->high_water) -// init = s->window_size - s->high_water; -// zmemzero(s->window + s->high_water, (unsigned)init); -// s->high_water += init; -// } -// } -// -// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -// "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - var max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); -// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || -// s.block_start >= s.w_size)) { -// throw new Error("slide too late"); -// } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); -// if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - var max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - var hash_head; /* head of the hash chain */ - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else - { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - -//#if MIN_MATCH != 3 -// Call UPDATE_HASH() MIN_MATCH-3 more times -//#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - var hash_head; /* head of hash chain */ - var bflush; /* set if current block must be flushed */ - - var max_insert; - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - var bflush; /* set if current block must be flushed */ - var prev; /* byte at distance one to match */ - var scan, strend; /* scan goes up to strend for length of run */ - - var _win = s.window; - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH) { - fill_window(s); - if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -function Config(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; -} - -var configuration_table; - -configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - s.ins_h = 0; -} - - -function DeflateState() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); - this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); - this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); - zero(this.dyn_ltree); - zero(this.dyn_dtree); - zero(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new utils.Buf16(MAX_BITS + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ - zero(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; - zero(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ -} - - -function deflateResetKeep(strm) { - var s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - trees._tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - var ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - var wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - var s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); - - s.window = new utils.Buf8(s.w_size * 2); - s.head = new utils.Buf16(s.hash_size); - s.prev = new utils.Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new utils.Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - -function deflateInit(strm, level) { - return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); -} - - -function deflate(strm, flush) { - var old_flush, s; - var beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - var level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - -//#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } -//#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - trees._tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - trees._tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else - { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - var status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var s; - var str, n; - var wrap; - var avail; - var next; - var input; - var tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new utils.Buf8(s.w_size); - utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - - -exports.deflateInit = deflateInit; -exports.deflateInit2 = deflateInit2; -exports.deflateReset = deflateReset; -exports.deflateResetKeep = deflateResetKeep; -exports.deflateSetHeader = deflateSetHeader; -exports.deflate = deflate; -exports.deflateEnd = deflateEnd; -exports.deflateSetDictionary = deflateSetDictionary; -exports.deflateInfo = 'pako deflate (from Nodeca project)'; - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - -},{"../utils/common":1406,"./adler32":1407,"./crc32":1409,"./messages":1414,"./trees":1415}],1411:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -// See state defs from inflate.js -var BAD = 30; /* got a data error -- remain here until reset */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -module.exports = function inflate_fast(strm, start) { - var state; - var _in; /* local strm.input */ - var last; /* have enough input while in < last */ - var _out; /* local strm.output */ - var beg; /* inflate()'s initial strm.output */ - var end; /* while out < end, enough space available */ -//#ifdef INFLATE_STRICT - var dmax; /* maximum distance from zlib header */ -//#endif - var wsize; /* window size or zero if not using window */ - var whave; /* valid bytes in the window */ - var wnext; /* window write index */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - var s_window; /* allocated sliding window, if wsize != 0 */ - var hold; /* local strm.hold */ - var bits; /* local strm.bits */ - var lcode; /* local strm.lencode */ - var dcode; /* local strm.distcode */ - var lmask; /* mask for first level of length codes */ - var dmask; /* mask for first level of distance codes */ - var here; /* retrieved table entry */ - var op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - var len; /* match length, unused bytes */ - var dist; /* match distance */ - var from; /* where to copy match from */ - var from_source; - - - var input, output; // JS specific, because we have no pointers - - /* copy state to local variables */ - state = strm.state; - //here = state.here; - _in = strm.next_in; - input = strm.input; - last = _in + (strm.avail_in - 5); - _out = strm.next_out; - output = strm.output; - beg = _out - (start - strm.avail_out); - end = _out + (strm.avail_out - 257); -//#ifdef INFLATE_STRICT - dmax = state.dmax; -//#endif - wsize = state.wsize; - whave = state.whave; - wnext = state.wnext; - s_window = state.window; - hold = state.hold; - bits = state.bits; - lcode = state.lencode; - dcode = state.distcode; - lmask = (1 << state.lenbits) - 1; - dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } - else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & ((1 << op) - 1); - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & ((1 << op) - 1); -//#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } -//#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } - -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// if (len <= op - whave) { -// do { -// output[_out++] = 0; -// } while (--len); -// continue top; -// } -// len -= op - whave; -// do { -// output[_out++] = 0; -// } while (--op > whave); -// if (op === 0) { -// from = _out - dist; -// do { -// output[_out++] = output[from++]; -// } while (--len); -// continue top; -// } -//#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } - else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } - else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dodist; - } - else { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } - else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dolen; - } - else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } - else { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); - strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); - state.hold = hold; - state.bits = bits; - return; -}; - -},{}],1412:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = require('../utils/common'); -var adler32 = require('./adler32'); -var crc32 = require('./crc32'); -var inflate_fast = require('./inffast'); -var inflate_table = require('./inftrees'); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -//var Z_NO_FLUSH = 0; -//var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -//var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - -/* The deflate compression method */ -var Z_DEFLATED = 8; - - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -var HEAD = 1; /* i: waiting for magic header */ -var FLAGS = 2; /* i: waiting for method and flags (gzip) */ -var TIME = 3; /* i: waiting for modification time (gzip) */ -var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -var EXLEN = 5; /* i: waiting for extra length (gzip) */ -var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -var NAME = 7; /* i: waiting for end of file name (gzip) */ -var COMMENT = 8; /* i: waiting for end of comment (gzip) */ -var HCRC = 9; /* i: waiting for header crc (gzip) */ -var DICTID = 10; /* i: waiting for dictionary check value */ -var DICT = 11; /* waiting for inflateSetDictionary() call */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ -var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -var STORED = 14; /* i: waiting for stored size (length and complement) */ -var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -var COPY = 16; /* i/o: waiting for input or output to copy stored block */ -var TABLE = 17; /* i: waiting for dynamic block table lengths */ -var LENLENS = 18; /* i: waiting for code length code lengths */ -var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -var LEN_ = 20; /* i: same as LEN below, but only first time in */ -var LEN = 21; /* i: waiting for length/lit/eob code */ -var LENEXT = 22; /* i: waiting for length extra bits */ -var DIST = 23; /* i: waiting for distance code */ -var DISTEXT = 24; /* i: waiting for distance extra bits */ -var MATCH = 25; /* o: waiting for output space to copy string */ -var LIT = 26; /* o: waiting for output space to write literal */ -var CHECK = 27; /* i: waiting for 32-bit check value */ -var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -var DONE = 29; /* finished check, done -- remain here until reset */ -var BAD = 30; /* got a data error -- remain here until reset */ -var MEM = 31; /* got an inflate() memory error -- remain here until reset */ -var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_WBITS = MAX_WBITS; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -function InflateState() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ - this.work = new utils.Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ -} - -function inflateResetKeep(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); - state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - var wrap; - var state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - var ret; - var state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - -function inflateInit(strm) { - return inflateInit2(strm, DEF_WBITS); -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -var virgin = true; - -var lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - var sym; - - lenfix = new utils.Buf32(512); - distfix = new utils.Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - var dist; - var state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new utils.Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - utils.arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - utils.arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - var state; - var input, output; // input/output buffers - var next; /* next input INDEX */ - var put; /* next output INDEX */ - var have, left; /* available input and output */ - var hold; /* bit buffer */ - var bits; /* bits in bit buffer */ - var _in, _out; /* save starting available input and output */ - var copy; /* number of stored or match bytes to copy */ - var from; /* where to copy match bytes from */ - var from_source; - var here = 0; /* current decoding table entry */ - var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - var len; /* length to copy for repeats, bits to drop */ - var ret; /* return code */ - var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ - var opts; - - var n; // temporary var for NEED_BITS - - var order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more convenient processing later - state.head.extra = new Array(state.head.extra_len); - } - utils.arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - /* falls through */ - case TYPE: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - utils.arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' instead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD: - ret = Z_DATA_ERROR; - break inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { - state.mode = MEM; - return Z_MEM_ERROR; - } - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - var state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - var state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var state; - var dictid; - var ret; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - ret = updatewindow(strm, dictionary, dictLength, dictLength); - if (ret) { - state.mode = MEM; - return Z_MEM_ERROR; - } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -exports.inflateReset = inflateReset; -exports.inflateReset2 = inflateReset2; -exports.inflateResetKeep = inflateResetKeep; -exports.inflateInit = inflateInit; -exports.inflateInit2 = inflateInit2; -exports.inflate = inflate; -exports.inflateEnd = inflateEnd; -exports.inflateGetHeader = inflateGetHeader; -exports.inflateSetDictionary = inflateSetDictionary; -exports.inflateInfo = 'pako inflate (from Nodeca project)'; - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - -},{"../utils/common":1406,"./adler32":1407,"./crc32":1409,"./inffast":1411,"./inftrees":1413}],1413:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -var utils = require('../utils/common'); - -var MAXBITS = 15; -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -var lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -var lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -var dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -var dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) -{ - var bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - var len = 0; /* a code's length in bits */ - var sym = 0; /* index of code symbols */ - var min = 0, max = 0; /* minimum and maximum code lengths */ - var root = 0; /* number of index bits for root table */ - var curr = 0; /* number of index bits for current table */ - var drop = 0; /* code bits to drop for sub-table */ - var left = 0; /* number of prefix codes available */ - var used = 0; /* code entries in table used */ - var huff = 0; /* Huffman code */ - var incr; /* for incrementing code, index */ - var fill; /* index for replicating entries */ - var low; /* low bits for current root entry */ - var mask; /* mask for low root bits */ - var next; /* next available space in table */ - var base = null; /* base value table to use */ - var base_index = 0; -// var shoextra; /* extra bits table to use */ - var end; /* use base and extra for symbol > end */ - var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - var extra = null; - var extra_index = 0; - - var here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { break; } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { break; } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } - else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } - else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << (len - drop); - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << (len - 1); - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { break; } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { break; } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -}; - -},{"../utils/common":1406}],1414:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -module.exports = { - 2: 'need dictionary', /* Z_NEED_DICT 2 */ - 1: 'stream end', /* Z_STREAM_END 1 */ - 0: '', /* Z_OK 0 */ - '-1': 'file error', /* Z_ERRNO (-1) */ - '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ - '-3': 'data error', /* Z_DATA_ERROR (-3) */ - '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ - '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ - '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ -}; - -},{}],1415:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -/* eslint-disable space-unary-ops */ - -var utils = require('../utils/common'); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -//var Z_FILTERED = 1; -//var Z_HUFFMAN_ONLY = 2; -//var Z_RLE = 3; -var Z_FIXED = 4; -//var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -var Z_BINARY = 0; -var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - -/*============================================================================*/ - - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - -// From zutil.h - -var STORED_BLOCK = 0; -var STATIC_TREES = 1; -var DYN_TREES = 2; -/* The three kinds of block type */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -var LITERALS = 256; -/* number of literal bytes 0..255 */ - -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -var D_CODES = 30; -/* number of distance codes */ - -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -var MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -var END_BLOCK = 256; -/* end of block literal code */ - -var REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -var REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -var REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -var extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -var extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -var extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -var bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 -var static_ltree = new Array((L_CODES + 2) * 2); -zero(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -var static_dtree = new Array(D_CODES * 2); -zero(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -var _dist_code = new Array(DIST_CODE_LEN); -zero(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -var base_length = new Array(LENGTH_CODES); -zero(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -var base_dist = new Array(D_CODES); -zero(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -var static_l_desc; -var static_d_desc; -var static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = (w) & 0xff; - s.pending_buf[s.pending++] = (w >>> 8) & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > (Buf_size - length)) { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> (Buf_size - s.bi_valid); - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - var res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var max_code = desc.max_code; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var extra = desc.stat_desc.extra_bits; - var base = desc.stat_desc.extra_base; - var max_length = desc.stat_desc.max_length; - var h; /* heap index */ - var n, m; /* iterate over the tree elements */ - var bits; /* bit length */ - var xbits; /* extra bits */ - var f; /* frequency */ - var overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { continue; } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { return; } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { bits--; } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { continue; } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - var code = 0; /* running code value */ - var bits; /* bit index */ - var n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits - 1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < (1 << extra_lbits[code]); n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1 << extra_dbits[code]); n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - var n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) -{ - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } -// while (len--) { -// put_byte(s, *buf++); -// } - utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - var _n2 = n * 2; - var _m2 = m * 2; - return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - var v = s.heap[k]; - var j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { break; } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - var dist; /* distance of matched string */ - var lc; /* match length or unmatched char (if dist == 0) */ - var lx = 0; /* running index in l_buf */ - var code; /* the code to send */ - var extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var elems = desc.stat_desc.elems; - var n, m; /* iterate over heap elements */ - var max_code = -1; /* largest code with non zero frequency */ - var node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - var max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - var rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - var black_mask = 0xf3ffc07f; - var n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -var static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) -{ - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - var max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s.opt_len + 3 + 7) >>> 3; - static_lenb = (s.static_len + 3 + 7) >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - -// (!) This block is disabled in zlib defaults, -// don't enable it for binary compatibility - -//#ifdef TRUNCATE_BLOCK -// /* Try to guess if it is profitable to stop the current block here */ -// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { -// /* Compute an upper bound for the compressed length */ -// out_length = s.last_lit*8; -// in_length = s.strstart - s.block_start; -// -// for (dcode = 0; dcode < D_CODES; dcode++) { -// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); -// } -// out_length >>>= 3; -// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", -// // s->last_lit, in_length, out_length, -// // 100L - out_length*100L/in_length)); -// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { -// return true; -// } -// } -//#endif - - return (s.last_lit === s.lit_bufsize - 1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -exports._tr_init = _tr_init; -exports._tr_stored_block = _tr_stored_block; -exports._tr_flush_block = _tr_flush_block; -exports._tr_tally = _tr_tally; -exports._tr_align = _tr_align; - -},{"../utils/common":1406}],1416:[function(require,module,exports){ -'use strict'; - -// (C) 1995-2013 Jean-loup Gailly and Mark Adler -// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would be -// appreciated but is not required. -// 2. Altered source versions must be plainly marked as such, and must not be -// misrepresented as being the original software. -// 3. This notice may not be removed or altered from any source distribution. - -function ZStream() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; -} - -module.exports = ZStream; - -},{}],1417:[function(require,module,exports){ +},{"p-map":1233}],1239:[function(require,module,exports){ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", @@ -183195,7 +142123,7 @@ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.43": "aes-256-ofb", "2.16.840.1.101.3.4.1.44": "aes-256-cfb" } -},{}],1418:[function(require,module,exports){ +},{}],1240:[function(require,module,exports){ // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js // Fedor, you are amazing. 'use strict' @@ -183319,7 +142247,7 @@ exports.signature = asn1.define('signature', function () { ) }) -},{"./certificate":1419,"asn1.js":56}],1419:[function(require,module,exports){ +},{"./certificate":1241,"asn1.js":11}],1241:[function(require,module,exports){ // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen @@ -183410,7 +142338,7 @@ var X509Certificate = asn.define('X509Certificate', function () { module.exports = X509Certificate -},{"asn1.js":56}],1420:[function(require,module,exports){ +},{"asn1.js":11}],1242:[function(require,module,exports){ // adapted from https://github.com/apatil/pemstrip var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m @@ -183443,7 +142371,7 @@ module.exports = function (okey, password) { } } -},{"browserify-aes":185,"evp_bytestokey":371,"safe-buffer":1593}],1421:[function(require,module,exports){ +},{"browserify-aes":149,"evp_bytestokey":273,"safe-buffer":1371}],1243:[function(require,module,exports){ var asn1 = require('./asn1') var aesid = require('./aesid.json') var fixProc = require('./fixProc') @@ -183552,40 +142480,7 @@ function decrypt (data, password) { return Buffer.concat(out) } -},{"./aesid.json":1417,"./asn1":1418,"./fixProc":1420,"browserify-aes":185,"pbkdf2":1426,"safe-buffer":1593}],1422:[function(require,module,exports){ -var trim = require('string.prototype.trim') - , forEach = require('for-each') - , isArray = function(arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; - } - -module.exports = function (headers) { - if (!headers) - return {} - - var result = {} - - forEach( - trim(headers).split('\n') - , function (row) { - var index = row.indexOf(':') - , key = trim(row.slice(0, index)).toLowerCase() - , value = trim(row.slice(index + 1)) - - if (typeof(result[key]) === 'undefined') { - result[key] = value - } else if (isArray(result[key])) { - result[key].push(value) - } else { - result[key] = [ result[key], value ] - } - } - ) - - return result -} - -},{"for-each":380,"string.prototype.trim":1738}],1423:[function(require,module,exports){ +},{"./aesid.json":1239,"./asn1":1240,"./fixProc":1242,"browserify-aes":149,"pbkdf2":1247,"safe-buffer":1371}],1244:[function(require,module,exports){ /** * Compiles a querystring * Returns string representation of the object @@ -183624,7 +142519,7 @@ exports.decode = function(qs){ return qry; }; -},{}],1424:[function(require,module,exports){ +},{}],1245:[function(require,module,exports){ /** * Parses an URI * @@ -183665,7 +142560,7 @@ module.exports = function parseuri(str) { return uri; }; -},{}],1425:[function(require,module,exports){ +},{}],1246:[function(require,module,exports){ (function (process){ // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, // backported and transplited with Babel, with backwards-compat fixes @@ -183971,11 +142866,11 @@ var substr = 'ab'.substr(-1) === 'b' ; }).call(this,require('_process')) -},{"_process":1438}],1426:[function(require,module,exports){ +},{"_process":1258}],1247:[function(require,module,exports){ exports.pbkdf2 = require('./lib/async') exports.pbkdf2Sync = require('./lib/sync') -},{"./lib/async":1427,"./lib/sync":1430}],1427:[function(require,module,exports){ +},{"./lib/async":1248,"./lib/sync":1251}],1248:[function(require,module,exports){ (function (process,global){ var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') @@ -184079,7 +142974,7 @@ module.exports = function (password, salt, iterations, keylen, digest, callback) } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./default-encoding":1428,"./precondition":1429,"./sync":1430,"_process":1438,"safe-buffer":1593}],1428:[function(require,module,exports){ +},{"./default-encoding":1249,"./precondition":1250,"./sync":1251,"_process":1258,"safe-buffer":1371}],1249:[function(require,module,exports){ (function (process){ var defaultEncoding /* istanbul ignore next */ @@ -184093,7 +142988,7 @@ if (process.browser) { module.exports = defaultEncoding }).call(this,require('_process')) -},{"_process":1438}],1429:[function(require,module,exports){ +},{"_process":1258}],1250:[function(require,module,exports){ (function (Buffer){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs @@ -184125,7 +143020,7 @@ module.exports = function (password, salt, iterations, keylen) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766}],1430:[function(require,module,exports){ +},{"../../is-buffer/index.js":608}],1251:[function(require,module,exports){ var md5 = require('create-hash/md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') @@ -184231,7 +143126,7 @@ function pbkdf2 (password, salt, iterations, keylen, digest) { module.exports = pbkdf2 -},{"./default-encoding":1428,"./precondition":1429,"create-hash/md5":233,"ripemd160":1592,"safe-buffer":1593,"sha.js":1616}],1431:[function(require,module,exports){ +},{"./default-encoding":1249,"./precondition":1250,"create-hash/md5":194,"ripemd160":1370,"safe-buffer":1371,"sha.js":1386}],1252:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -184350,7 +143245,7 @@ class PeerBook { module.exports = PeerBook }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"bs58":213,"peer-id":1432,"peer-info":1433}],1432:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"bs58":177,"peer-id":1253,"peer-info":1254}],1253:[function(require,module,exports){ (function (Buffer){ /* * Id is an object representation of a peer Id. a peer Id is a multihash @@ -184671,7 +143566,7 @@ function toB64Opt (val) { } }).call(this,require("buffer").Buffer) -},{"assert":78,"async/waterfall":152,"buffer":217,"class-is":224,"libp2p-crypto/src/keys":910,"multihashes":1331}],1433:[function(require,module,exports){ +},{"assert":26,"async/waterfall":102,"buffer":181,"class-is":187,"libp2p-crypto/src/keys":750,"multihashes":1157}],1254:[function(require,module,exports){ 'use strict' const PeerId = require('peer-id') @@ -184739,7 +143634,7 @@ PeerInfo.isPeerInfo = (peerInfo) => { module.exports = PeerInfo -},{"./multiaddr-set":1434,"./utils":1435,"assert":78,"peer-id":1432}],1434:[function(require,module,exports){ +},{"./multiaddr-set":1255,"./utils":1256,"assert":26,"peer-id":1253}],1255:[function(require,module,exports){ 'use strict' const { ensureMultiaddr } = require('./utils') @@ -184848,7 +143743,7 @@ class MultiaddrSet { module.exports = MultiaddrSet -},{"./utils":1435,"unique-by":1766}],1435:[function(require,module,exports){ +},{"./utils":1256,"unique-by":1506}],1256:[function(require,module,exports){ 'use strict' const multiaddr = require('multiaddr') @@ -184865,52 +143760,11 @@ module.exports = { ensureMultiaddr: ensureMultiaddr } -},{"multiaddr":1314}],1436:[function(require,module,exports){ -(function (process){ -// Generated by CoffeeScript 1.12.2 -(function() { - var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; - - if ((typeof performance !== "undefined" && performance !== null) && performance.now) { - module.exports = function() { - return performance.now(); - }; - } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { - module.exports = function() { - return (getNanoSeconds() - nodeLoadTime) / 1e6; - }; - hrtime = process.hrtime; - getNanoSeconds = function() { - var hr; - hr = hrtime(); - return hr[0] * 1e9 + hr[1]; - }; - moduleLoadTime = getNanoSeconds(); - upTime = process.uptime() * 1e9; - nodeLoadTime = moduleLoadTime - upTime; - } else if (Date.now) { - module.exports = function() { - return Date.now() - loadTime; - }; - loadTime = Date.now(); - } else { - module.exports = function() { - return new Date().getTime() - loadTime; - }; - loadTime = new Date().getTime(); - } - -}).call(this); - - - -}).call(this,require('_process')) -},{"_process":1438}],1437:[function(require,module,exports){ +},{"multiaddr":1140}],1257:[function(require,module,exports){ (function (process){ 'use strict'; -if (typeof process === 'undefined' || - !process.version || +if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; @@ -184954,7 +143808,7 @@ function nextTick(fn, arg1, arg2, arg3) { }).call(this,require('_process')) -},{"_process":1438}],1438:[function(require,module,exports){ +},{"_process":1258}],1258:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -185140,7 +143994,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],1439:[function(require,module,exports){ +},{}],1259:[function(require,module,exports){ (function (process,setImmediate){ /** @module promise-nodeify * @copyright Copyright 2016-2018 Kevin Locke @@ -185283,7 +144137,7 @@ if (typeof exports === 'object') { } }).call(this,require('_process'),require("timers").setImmediate) -},{"_process":1438,"timers":1749}],1440:[function(require,module,exports){ +},{"_process":1258,"timers":1500}],1260:[function(require,module,exports){ // Copyright (c) 2015-2017 David M. Lee, II 'use strict'; @@ -185334,7 +144188,7 @@ TimeoutError = module.exports.TimeoutError = function() { TimeoutError.prototype = Object.create(Error.prototype); TimeoutError.prototype.name = "TimeoutError"; -},{}],1441:[function(require,module,exports){ +},{}],1261:[function(require,module,exports){ 'use strict'; var isFn = require('is-fn'); var setImmediate = require('set-immediate-shim'); @@ -185353,7 +144207,7 @@ module.exports = function (promise) { }; }; -},{"is-fn":771,"set-immediate-shim":1614}],1442:[function(require,module,exports){ +},{"is-fn":612,"set-immediate-shim":1384}],1262:[function(require,module,exports){ (function (process){ var isPromise = require('is-promise') @@ -185414,7 +144268,7 @@ function Promise(fn) { if (isResolved && !running) next() }); } - + (function () { function fulfill(val) { if (isResolved) return @@ -185454,7 +144308,7 @@ Promise.use = function (extension) { extensions.push(extension); }; }).call(this,require('_process')) -},{"_process":1438,"is-promise":777}],1443:[function(require,module,exports){ +},{"_process":1258,"is-promise":616}],1263:[function(require,module,exports){ /** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES * * EXAMPLE: @@ -185522,7 +144376,7 @@ if (typeof exports === "undefined") { this["promisify"] = module.exports; } -},{}],1444:[function(require,module,exports){ +},{}],1264:[function(require,module,exports){ var parse = require('./parse') var stringify = require('./stringify') @@ -185530,7 +144384,7 @@ module.exports = parse module.exports.parse = parse module.exports.stringify = stringify -},{"./parse":1445,"./stringify":1446}],1445:[function(require,module,exports){ +},{"./parse":1265,"./stringify":1266}],1265:[function(require,module,exports){ var tokenize = require('./tokenize') var MAX_RANGE = 0x1FFFFFFF @@ -186240,7 +145094,7 @@ var parse = function (buf) { module.exports = parse -},{"./tokenize":1447}],1446:[function(require,module,exports){ +},{"./tokenize":1267}],1266:[function(require,module,exports){ var onfield = function (f, result) { var prefix = f.repeated ? 'repeated' : f.required ? 'required' : 'optional' if (f.type === 'map') prefix = 'map<' + f.map.from + ',' + f.map.to + '>' @@ -186434,7 +145288,7 @@ module.exports = function (schema) { return result.map(indent('')).join('\n') } -},{}],1447:[function(require,module,exports){ +},{}],1267:[function(require,module,exports){ module.exports = function (sch) { var noComments = function (line) { var i = line.indexOf('//') @@ -186473,7 +145327,7 @@ module.exports = function (sch) { .filter(noMultilineComments()) } -},{}],1448:[function(require,module,exports){ +},{}],1268:[function(require,module,exports){ /* eslint max-depth: 1 */ 'use strict' @@ -186707,7 +145561,7 @@ var defaultValue = function (f, def) { module.exports = compileDecode -},{"./utils":1453,"varint":1785}],1449:[function(require,module,exports){ +},{"./utils":1273,"varint":1521}],1269:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -186841,7 +145695,7 @@ function compileEncode (m, resolve, enc, oneofs, encodingLength) { module.exports = compileEncode }).call(this,require("buffer").Buffer) -},{"./utils":1453,"buffer":217,"varint":1785}],1450:[function(require,module,exports){ +},{"./utils":1273,"buffer":181,"varint":1521}],1270:[function(require,module,exports){ 'use strict' var defined = require('./utils').defined @@ -186945,7 +145799,7 @@ function compileEncodingLength (m, enc, oneofs) { module.exports = compileEncodingLength -},{"./utils":1453,"varint":1785}],1451:[function(require,module,exports){ +},{"./utils":1273,"varint":1521}],1271:[function(require,module,exports){ 'use strict' var varint = require('varint') @@ -187240,7 +146094,7 @@ exports.float = (function () { return encoder(5, encode, decode, encodingLength) })() -},{"safe-buffer":1593,"signed-varint":1632,"varint":1785}],1452:[function(require,module,exports){ +},{"safe-buffer":1371,"signed-varint":1402,"varint":1521}],1272:[function(require,module,exports){ 'use strict' var encodings = require('./encodings') @@ -187407,14 +146261,14 @@ module.exports = function (schema, extraEncodings) { })) } -},{"./decode":1448,"./encode":1449,"./encoding-length":1450,"./encodings":1451,"varint":1785}],1453:[function(require,module,exports){ +},{"./decode":1268,"./encode":1269,"./encoding-length":1270,"./encodings":1271,"varint":1521}],1273:[function(require,module,exports){ 'use strict' exports.defined = function (val) { return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val)) } -},{}],1454:[function(require,module,exports){ +},{}],1274:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -187457,7 +146311,7 @@ module.exports = function (proto, opts) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./compile":1452,"protocol-buffers-schema":1444}],1455:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"./compile":1272,"protocol-buffers-schema":1264}],1275:[function(require,module,exports){ /*! * prr * (c) 2013 Rod Vagg @@ -187521,9069 +146375,7 @@ module.exports = function (proto, opts) { return prr }) -},{}],1456:[function(require,module,exports){ -module.exports=[ -"ac", -"com.ac", -"edu.ac", -"gov.ac", -"net.ac", -"mil.ac", -"org.ac", -"ad", -"nom.ad", -"ae", -"co.ae", -"net.ae", -"org.ae", -"sch.ae", -"ac.ae", -"gov.ae", -"mil.ae", -"aero", -"accident-investigation.aero", -"accident-prevention.aero", -"aerobatic.aero", -"aeroclub.aero", -"aerodrome.aero", -"agents.aero", -"aircraft.aero", -"airline.aero", -"airport.aero", -"air-surveillance.aero", -"airtraffic.aero", -"air-traffic-control.aero", -"ambulance.aero", -"amusement.aero", -"association.aero", -"author.aero", -"ballooning.aero", -"broker.aero", -"caa.aero", -"cargo.aero", -"catering.aero", -"certification.aero", -"championship.aero", -"charter.aero", -"civilaviation.aero", -"club.aero", -"conference.aero", -"consultant.aero", -"consulting.aero", -"control.aero", -"council.aero", -"crew.aero", -"design.aero", -"dgca.aero", -"educator.aero", -"emergency.aero", -"engine.aero", -"engineer.aero", -"entertainment.aero", -"equipment.aero", -"exchange.aero", -"express.aero", -"federation.aero", -"flight.aero", -"freight.aero", -"fuel.aero", -"gliding.aero", -"government.aero", -"groundhandling.aero", -"group.aero", -"hanggliding.aero", -"homebuilt.aero", -"insurance.aero", -"journal.aero", -"journalist.aero", -"leasing.aero", -"logistics.aero", -"magazine.aero", -"maintenance.aero", -"media.aero", -"microlight.aero", -"modelling.aero", -"navigation.aero", -"parachuting.aero", -"paragliding.aero", -"passenger-association.aero", -"pilot.aero", -"press.aero", -"production.aero", -"recreation.aero", -"repbody.aero", -"res.aero", -"research.aero", -"rotorcraft.aero", -"safety.aero", -"scientist.aero", -"services.aero", -"show.aero", -"skydiving.aero", -"software.aero", -"student.aero", -"trader.aero", -"trading.aero", -"trainer.aero", -"union.aero", -"workinggroup.aero", -"works.aero", -"af", -"gov.af", -"com.af", -"org.af", -"net.af", -"edu.af", -"ag", -"com.ag", -"org.ag", -"net.ag", -"co.ag", -"nom.ag", -"ai", -"off.ai", -"com.ai", -"net.ai", -"org.ai", -"al", -"com.al", -"edu.al", -"gov.al", -"mil.al", -"net.al", -"org.al", -"am", -"co.am", -"com.am", -"commune.am", -"net.am", -"org.am", -"ao", -"ed.ao", -"gv.ao", -"og.ao", -"co.ao", -"pb.ao", -"it.ao", -"aq", -"ar", -"com.ar", -"edu.ar", -"gob.ar", -"gov.ar", -"int.ar", -"mil.ar", -"musica.ar", -"net.ar", -"org.ar", -"tur.ar", -"arpa", -"e164.arpa", -"in-addr.arpa", -"ip6.arpa", -"iris.arpa", -"uri.arpa", -"urn.arpa", -"as", -"gov.as", -"asia", -"at", -"ac.at", -"co.at", -"gv.at", -"or.at", -"au", -"com.au", -"net.au", -"org.au", -"edu.au", -"gov.au", -"asn.au", -"id.au", -"info.au", -"conf.au", -"oz.au", -"act.au", -"nsw.au", -"nt.au", -"qld.au", -"sa.au", -"tas.au", -"vic.au", -"wa.au", -"act.edu.au", -"catholic.edu.au", -"eq.edu.au", -"nsw.edu.au", -"nt.edu.au", -"qld.edu.au", -"sa.edu.au", -"tas.edu.au", -"vic.edu.au", -"wa.edu.au", -"qld.gov.au", -"sa.gov.au", -"tas.gov.au", -"vic.gov.au", -"wa.gov.au", -"education.tas.edu.au", -"schools.nsw.edu.au", -"aw", -"com.aw", -"ax", -"az", -"com.az", -"net.az", -"int.az", -"gov.az", -"org.az", -"edu.az", -"info.az", -"pp.az", -"mil.az", -"name.az", -"pro.az", -"biz.az", -"ba", -"com.ba", -"edu.ba", -"gov.ba", -"mil.ba", -"net.ba", -"org.ba", -"bb", -"biz.bb", -"co.bb", -"com.bb", -"edu.bb", -"gov.bb", -"info.bb", -"net.bb", -"org.bb", -"store.bb", -"tv.bb", -"*.bd", -"be", -"ac.be", -"bf", -"gov.bf", -"bg", -"a.bg", -"b.bg", -"c.bg", -"d.bg", -"e.bg", -"f.bg", -"g.bg", -"h.bg", -"i.bg", -"j.bg", -"k.bg", -"l.bg", -"m.bg", -"n.bg", -"o.bg", -"p.bg", -"q.bg", -"r.bg", -"s.bg", -"t.bg", -"u.bg", -"v.bg", -"w.bg", -"x.bg", -"y.bg", -"z.bg", -"0.bg", -"1.bg", -"2.bg", -"3.bg", -"4.bg", -"5.bg", -"6.bg", -"7.bg", -"8.bg", -"9.bg", -"bh", -"com.bh", -"edu.bh", -"net.bh", -"org.bh", -"gov.bh", -"bi", -"co.bi", -"com.bi", -"edu.bi", -"or.bi", -"org.bi", -"biz", -"bj", -"asso.bj", -"barreau.bj", -"gouv.bj", -"bm", -"com.bm", -"edu.bm", -"gov.bm", -"net.bm", -"org.bm", -"bn", -"com.bn", -"edu.bn", -"gov.bn", -"net.bn", -"org.bn", -"bo", -"com.bo", -"edu.bo", -"gob.bo", -"int.bo", -"org.bo", -"net.bo", -"mil.bo", -"tv.bo", -"web.bo", -"academia.bo", -"agro.bo", -"arte.bo", -"blog.bo", -"bolivia.bo", -"ciencia.bo", -"cooperativa.bo", -"democracia.bo", -"deporte.bo", -"ecologia.bo", -"economia.bo", -"empresa.bo", -"indigena.bo", -"industria.bo", -"info.bo", -"medicina.bo", -"movimiento.bo", -"musica.bo", -"natural.bo", -"nombre.bo", -"noticias.bo", -"patria.bo", -"politica.bo", -"profesional.bo", -"plurinacional.bo", -"pueblo.bo", -"revista.bo", -"salud.bo", -"tecnologia.bo", -"tksat.bo", -"transporte.bo", -"wiki.bo", -"br", -"9guacu.br", -"abc.br", -"adm.br", -"adv.br", -"agr.br", -"aju.br", -"am.br", -"anani.br", -"aparecida.br", -"arq.br", -"art.br", -"ato.br", -"b.br", -"barueri.br", -"belem.br", -"bhz.br", -"bio.br", -"blog.br", -"bmd.br", -"boavista.br", -"bsb.br", -"campinagrande.br", -"campinas.br", -"caxias.br", -"cim.br", -"cng.br", -"cnt.br", -"com.br", -"contagem.br", -"coop.br", -"cri.br", -"cuiaba.br", -"curitiba.br", -"def.br", -"ecn.br", -"eco.br", -"edu.br", -"emp.br", -"eng.br", -"esp.br", -"etc.br", -"eti.br", -"far.br", -"feira.br", -"flog.br", -"floripa.br", -"fm.br", -"fnd.br", -"fortal.br", -"fot.br", -"foz.br", -"fst.br", -"g12.br", -"ggf.br", -"goiania.br", -"gov.br", -"ac.gov.br", -"al.gov.br", -"am.gov.br", -"ap.gov.br", -"ba.gov.br", -"ce.gov.br", -"df.gov.br", -"es.gov.br", -"go.gov.br", -"ma.gov.br", -"mg.gov.br", -"ms.gov.br", -"mt.gov.br", -"pa.gov.br", -"pb.gov.br", -"pe.gov.br", -"pi.gov.br", -"pr.gov.br", -"rj.gov.br", -"rn.gov.br", -"ro.gov.br", -"rr.gov.br", -"rs.gov.br", -"sc.gov.br", -"se.gov.br", -"sp.gov.br", -"to.gov.br", -"gru.br", -"imb.br", -"ind.br", -"inf.br", -"jab.br", -"jampa.br", -"jdf.br", -"joinville.br", -"jor.br", -"jus.br", -"leg.br", -"lel.br", -"londrina.br", -"macapa.br", -"maceio.br", -"manaus.br", -"maringa.br", -"mat.br", -"med.br", -"mil.br", -"morena.br", -"mp.br", -"mus.br", -"natal.br", -"net.br", -"niteroi.br", -"*.nom.br", -"not.br", -"ntr.br", -"odo.br", -"ong.br", -"org.br", -"osasco.br", -"palmas.br", -"poa.br", -"ppg.br", -"pro.br", -"psc.br", -"psi.br", -"pvh.br", -"qsl.br", -"radio.br", -"rec.br", -"recife.br", -"ribeirao.br", -"rio.br", -"riobranco.br", -"riopreto.br", -"salvador.br", -"sampa.br", -"santamaria.br", -"santoandre.br", -"saobernardo.br", -"saogonca.br", -"sjc.br", -"slg.br", -"slz.br", -"sorocaba.br", -"srv.br", -"taxi.br", -"tc.br", -"teo.br", -"the.br", -"tmp.br", -"trd.br", -"tur.br", -"tv.br", -"udi.br", -"vet.br", -"vix.br", -"vlog.br", -"wiki.br", -"zlg.br", -"bs", -"com.bs", -"net.bs", -"org.bs", -"edu.bs", -"gov.bs", -"bt", -"com.bt", -"edu.bt", -"gov.bt", -"net.bt", -"org.bt", -"bv", -"bw", -"co.bw", -"org.bw", -"by", -"gov.by", -"mil.by", -"com.by", -"of.by", -"bz", -"com.bz", -"net.bz", -"org.bz", -"edu.bz", -"gov.bz", -"ca", -"ab.ca", -"bc.ca", -"mb.ca", -"nb.ca", -"nf.ca", -"nl.ca", -"ns.ca", -"nt.ca", -"nu.ca", -"on.ca", -"pe.ca", -"qc.ca", -"sk.ca", -"yk.ca", -"gc.ca", -"cat", -"cc", -"cd", -"gov.cd", -"cf", -"cg", -"ch", -"ci", -"org.ci", -"or.ci", -"com.ci", -"co.ci", -"edu.ci", -"ed.ci", -"ac.ci", -"net.ci", -"go.ci", -"asso.ci", -"aéroport.ci", -"int.ci", -"presse.ci", -"md.ci", -"gouv.ci", -"*.ck", -"!www.ck", -"cl", -"gov.cl", -"gob.cl", -"co.cl", -"mil.cl", -"cm", -"co.cm", -"com.cm", -"gov.cm", -"net.cm", -"cn", -"ac.cn", -"com.cn", -"edu.cn", -"gov.cn", -"net.cn", -"org.cn", -"mil.cn", -"公司.cn", -"网络.cn", -"網絡.cn", -"ah.cn", -"bj.cn", -"cq.cn", -"fj.cn", -"gd.cn", -"gs.cn", -"gz.cn", -"gx.cn", -"ha.cn", -"hb.cn", -"he.cn", -"hi.cn", -"hl.cn", -"hn.cn", -"jl.cn", -"js.cn", -"jx.cn", -"ln.cn", -"nm.cn", -"nx.cn", -"qh.cn", -"sc.cn", -"sd.cn", -"sh.cn", -"sn.cn", -"sx.cn", -"tj.cn", -"xj.cn", -"xz.cn", -"yn.cn", -"zj.cn", -"hk.cn", -"mo.cn", -"tw.cn", -"co", -"arts.co", -"com.co", -"edu.co", -"firm.co", -"gov.co", -"info.co", -"int.co", -"mil.co", -"net.co", -"nom.co", -"org.co", -"rec.co", -"web.co", -"com", -"coop", -"cr", -"ac.cr", -"co.cr", -"ed.cr", -"fi.cr", -"go.cr", -"or.cr", -"sa.cr", -"cu", -"com.cu", -"edu.cu", -"org.cu", -"net.cu", -"gov.cu", -"inf.cu", -"cv", -"cw", -"com.cw", -"edu.cw", -"net.cw", -"org.cw", -"cx", -"gov.cx", -"cy", -"ac.cy", -"biz.cy", -"com.cy", -"ekloges.cy", -"gov.cy", -"ltd.cy", -"name.cy", -"net.cy", -"org.cy", -"parliament.cy", -"press.cy", -"pro.cy", -"tm.cy", -"cz", -"de", -"dj", -"dk", -"dm", -"com.dm", -"net.dm", -"org.dm", -"edu.dm", -"gov.dm", -"do", -"art.do", -"com.do", -"edu.do", -"gob.do", -"gov.do", -"mil.do", -"net.do", -"org.do", -"sld.do", -"web.do", -"dz", -"com.dz", -"org.dz", -"net.dz", -"gov.dz", -"edu.dz", -"asso.dz", -"pol.dz", -"art.dz", -"ec", -"com.ec", -"info.ec", -"net.ec", -"fin.ec", -"k12.ec", -"med.ec", -"pro.ec", -"org.ec", -"edu.ec", -"gov.ec", -"gob.ec", -"mil.ec", -"edu", -"ee", -"edu.ee", -"gov.ee", -"riik.ee", -"lib.ee", -"med.ee", -"com.ee", -"pri.ee", -"aip.ee", -"org.ee", -"fie.ee", -"eg", -"com.eg", -"edu.eg", -"eun.eg", -"gov.eg", -"mil.eg", -"name.eg", -"net.eg", -"org.eg", -"sci.eg", -"*.er", -"es", -"com.es", -"nom.es", -"org.es", -"gob.es", -"edu.es", -"et", -"com.et", -"gov.et", -"org.et", -"edu.et", -"biz.et", -"name.et", -"info.et", -"net.et", -"eu", -"fi", -"aland.fi", -"*.fj", -"*.fk", -"fm", -"fo", -"fr", -"asso.fr", -"com.fr", -"gouv.fr", -"nom.fr", -"prd.fr", -"tm.fr", -"aeroport.fr", -"avocat.fr", -"avoues.fr", -"cci.fr", -"chambagri.fr", -"chirurgiens-dentistes.fr", -"experts-comptables.fr", -"geometre-expert.fr", -"greta.fr", -"huissier-justice.fr", -"medecin.fr", -"notaires.fr", -"pharmacien.fr", -"port.fr", -"veterinaire.fr", -"ga", -"gb", -"gd", -"ge", -"com.ge", -"edu.ge", -"gov.ge", -"org.ge", -"mil.ge", -"net.ge", -"pvt.ge", -"gf", -"gg", -"co.gg", -"net.gg", -"org.gg", -"gh", -"com.gh", -"edu.gh", -"gov.gh", -"org.gh", -"mil.gh", -"gi", -"com.gi", -"ltd.gi", -"gov.gi", -"mod.gi", -"edu.gi", -"org.gi", -"gl", -"co.gl", -"com.gl", -"edu.gl", -"net.gl", -"org.gl", -"gm", -"gn", -"ac.gn", -"com.gn", -"edu.gn", -"gov.gn", -"org.gn", -"net.gn", -"gov", -"gp", -"com.gp", -"net.gp", -"mobi.gp", -"edu.gp", -"org.gp", -"asso.gp", -"gq", -"gr", -"com.gr", -"edu.gr", -"net.gr", -"org.gr", -"gov.gr", -"gs", -"gt", -"com.gt", -"edu.gt", -"gob.gt", -"ind.gt", -"mil.gt", -"net.gt", -"org.gt", -"gu", -"com.gu", -"edu.gu", -"gov.gu", -"guam.gu", -"info.gu", -"net.gu", -"org.gu", -"web.gu", -"gw", -"gy", -"co.gy", -"com.gy", -"edu.gy", -"gov.gy", -"net.gy", -"org.gy", -"hk", -"com.hk", -"edu.hk", -"gov.hk", -"idv.hk", -"net.hk", -"org.hk", -"公司.hk", -"教育.hk", -"敎育.hk", -"政府.hk", -"個人.hk", -"个人.hk", -"箇人.hk", -"網络.hk", -"网络.hk", -"组織.hk", -"網絡.hk", -"网絡.hk", -"组织.hk", -"組織.hk", -"組织.hk", -"hm", -"hn", -"com.hn", -"edu.hn", -"org.hn", -"net.hn", -"mil.hn", -"gob.hn", -"hr", -"iz.hr", -"from.hr", -"name.hr", -"com.hr", -"ht", -"com.ht", -"shop.ht", -"firm.ht", -"info.ht", -"adult.ht", -"net.ht", -"pro.ht", -"org.ht", -"med.ht", -"art.ht", -"coop.ht", -"pol.ht", -"asso.ht", -"edu.ht", -"rel.ht", -"gouv.ht", -"perso.ht", -"hu", -"co.hu", -"info.hu", -"org.hu", -"priv.hu", -"sport.hu", -"tm.hu", -"2000.hu", -"agrar.hu", -"bolt.hu", -"casino.hu", -"city.hu", -"erotica.hu", -"erotika.hu", -"film.hu", -"forum.hu", -"games.hu", -"hotel.hu", -"ingatlan.hu", -"jogasz.hu", -"konyvelo.hu", -"lakas.hu", -"media.hu", -"news.hu", -"reklam.hu", -"sex.hu", -"shop.hu", -"suli.hu", -"szex.hu", -"tozsde.hu", -"utazas.hu", -"video.hu", -"id", -"ac.id", -"biz.id", -"co.id", -"desa.id", -"go.id", -"mil.id", -"my.id", -"net.id", -"or.id", -"ponpes.id", -"sch.id", -"web.id", -"ie", -"gov.ie", -"il", -"ac.il", -"co.il", -"gov.il", -"idf.il", -"k12.il", -"muni.il", -"net.il", -"org.il", -"im", -"ac.im", -"co.im", -"com.im", -"ltd.co.im", -"net.im", -"org.im", -"plc.co.im", -"tt.im", -"tv.im", -"in", -"co.in", -"firm.in", -"net.in", -"org.in", -"gen.in", -"ind.in", -"nic.in", -"ac.in", -"edu.in", -"res.in", -"gov.in", -"mil.in", -"info", -"int", -"eu.int", -"io", -"com.io", -"iq", -"gov.iq", -"edu.iq", -"mil.iq", -"com.iq", -"org.iq", -"net.iq", -"ir", -"ac.ir", -"co.ir", -"gov.ir", -"id.ir", -"net.ir", -"org.ir", -"sch.ir", -"ایران.ir", -"ايران.ir", -"is", -"net.is", -"com.is", -"edu.is", -"gov.is", -"org.is", -"int.is", -"it", -"gov.it", -"edu.it", -"abr.it", -"abruzzo.it", -"aosta-valley.it", -"aostavalley.it", -"bas.it", -"basilicata.it", -"cal.it", -"calabria.it", -"cam.it", -"campania.it", -"emilia-romagna.it", -"emiliaromagna.it", -"emr.it", -"friuli-v-giulia.it", -"friuli-ve-giulia.it", -"friuli-vegiulia.it", -"friuli-venezia-giulia.it", -"friuli-veneziagiulia.it", -"friuli-vgiulia.it", -"friuliv-giulia.it", -"friulive-giulia.it", -"friulivegiulia.it", -"friulivenezia-giulia.it", -"friuliveneziagiulia.it", -"friulivgiulia.it", -"fvg.it", -"laz.it", -"lazio.it", -"lig.it", -"liguria.it", -"lom.it", -"lombardia.it", -"lombardy.it", -"lucania.it", -"mar.it", -"marche.it", -"mol.it", -"molise.it", -"piedmont.it", -"piemonte.it", -"pmn.it", -"pug.it", -"puglia.it", -"sar.it", -"sardegna.it", -"sardinia.it", -"sic.it", -"sicilia.it", -"sicily.it", -"taa.it", -"tos.it", -"toscana.it", -"trentin-sud-tirol.it", -"trentin-süd-tirol.it", -"trentin-sudtirol.it", -"trentin-südtirol.it", -"trentin-sued-tirol.it", -"trentin-suedtirol.it", -"trentino-a-adige.it", -"trentino-aadige.it", -"trentino-alto-adige.it", -"trentino-altoadige.it", -"trentino-s-tirol.it", -"trentino-stirol.it", -"trentino-sud-tirol.it", -"trentino-süd-tirol.it", -"trentino-sudtirol.it", -"trentino-südtirol.it", -"trentino-sued-tirol.it", -"trentino-suedtirol.it", -"trentino.it", -"trentinoa-adige.it", -"trentinoaadige.it", -"trentinoalto-adige.it", -"trentinoaltoadige.it", -"trentinos-tirol.it", -"trentinostirol.it", -"trentinosud-tirol.it", -"trentinosüd-tirol.it", -"trentinosudtirol.it", -"trentinosüdtirol.it", -"trentinosued-tirol.it", -"trentinosuedtirol.it", -"trentinsud-tirol.it", -"trentinsüd-tirol.it", -"trentinsudtirol.it", -"trentinsüdtirol.it", -"trentinsued-tirol.it", -"trentinsuedtirol.it", -"tuscany.it", -"umb.it", -"umbria.it", -"val-d-aosta.it", -"val-daosta.it", -"vald-aosta.it", -"valdaosta.it", -"valle-aosta.it", -"valle-d-aosta.it", -"valle-daosta.it", -"valleaosta.it", -"valled-aosta.it", -"valledaosta.it", -"vallee-aoste.it", -"vallée-aoste.it", -"vallee-d-aoste.it", -"vallée-d-aoste.it", -"valleeaoste.it", -"valléeaoste.it", -"valleedaoste.it", -"valléedaoste.it", -"vao.it", -"vda.it", -"ven.it", -"veneto.it", -"ag.it", -"agrigento.it", -"al.it", -"alessandria.it", -"alto-adige.it", -"altoadige.it", -"an.it", -"ancona.it", -"andria-barletta-trani.it", -"andria-trani-barletta.it", -"andriabarlettatrani.it", -"andriatranibarletta.it", -"ao.it", -"aosta.it", -"aoste.it", -"ap.it", -"aq.it", -"aquila.it", -"ar.it", -"arezzo.it", -"ascoli-piceno.it", -"ascolipiceno.it", -"asti.it", -"at.it", -"av.it", -"avellino.it", -"ba.it", -"balsan-sudtirol.it", -"balsan-südtirol.it", -"balsan-suedtirol.it", -"balsan.it", -"bari.it", -"barletta-trani-andria.it", -"barlettatraniandria.it", -"belluno.it", -"benevento.it", -"bergamo.it", -"bg.it", -"bi.it", -"biella.it", -"bl.it", -"bn.it", -"bo.it", -"bologna.it", -"bolzano-altoadige.it", -"bolzano.it", -"bozen-sudtirol.it", -"bozen-südtirol.it", -"bozen-suedtirol.it", -"bozen.it", -"br.it", -"brescia.it", -"brindisi.it", -"bs.it", -"bt.it", -"bulsan-sudtirol.it", -"bulsan-südtirol.it", -"bulsan-suedtirol.it", -"bulsan.it", -"bz.it", -"ca.it", -"cagliari.it", -"caltanissetta.it", -"campidano-medio.it", -"campidanomedio.it", -"campobasso.it", -"carbonia-iglesias.it", -"carboniaiglesias.it", -"carrara-massa.it", -"carraramassa.it", -"caserta.it", -"catania.it", -"catanzaro.it", -"cb.it", -"ce.it", -"cesena-forli.it", -"cesena-forlì.it", -"cesenaforli.it", -"cesenaforlì.it", -"ch.it", -"chieti.it", -"ci.it", -"cl.it", -"cn.it", -"co.it", -"como.it", -"cosenza.it", -"cr.it", -"cremona.it", -"crotone.it", -"cs.it", -"ct.it", -"cuneo.it", -"cz.it", -"dell-ogliastra.it", -"dellogliastra.it", -"en.it", -"enna.it", -"fc.it", -"fe.it", -"fermo.it", -"ferrara.it", -"fg.it", -"fi.it", -"firenze.it", -"florence.it", -"fm.it", -"foggia.it", -"forli-cesena.it", -"forlì-cesena.it", -"forlicesena.it", -"forlìcesena.it", -"fr.it", -"frosinone.it", -"ge.it", -"genoa.it", -"genova.it", -"go.it", -"gorizia.it", -"gr.it", -"grosseto.it", -"iglesias-carbonia.it", -"iglesiascarbonia.it", -"im.it", -"imperia.it", -"is.it", -"isernia.it", -"kr.it", -"la-spezia.it", -"laquila.it", -"laspezia.it", -"latina.it", -"lc.it", -"le.it", -"lecce.it", -"lecco.it", -"li.it", -"livorno.it", -"lo.it", -"lodi.it", -"lt.it", -"lu.it", -"lucca.it", -"macerata.it", -"mantova.it", -"massa-carrara.it", -"massacarrara.it", -"matera.it", -"mb.it", -"mc.it", -"me.it", -"medio-campidano.it", -"mediocampidano.it", -"messina.it", -"mi.it", -"milan.it", -"milano.it", -"mn.it", -"mo.it", -"modena.it", -"monza-brianza.it", -"monza-e-della-brianza.it", -"monza.it", -"monzabrianza.it", -"monzaebrianza.it", -"monzaedellabrianza.it", -"ms.it", -"mt.it", -"na.it", -"naples.it", -"napoli.it", -"no.it", -"novara.it", -"nu.it", -"nuoro.it", -"og.it", -"ogliastra.it", -"olbia-tempio.it", -"olbiatempio.it", -"or.it", -"oristano.it", -"ot.it", -"pa.it", -"padova.it", -"padua.it", -"palermo.it", -"parma.it", -"pavia.it", -"pc.it", -"pd.it", -"pe.it", -"perugia.it", -"pesaro-urbino.it", -"pesarourbino.it", -"pescara.it", -"pg.it", -"pi.it", -"piacenza.it", -"pisa.it", -"pistoia.it", -"pn.it", -"po.it", -"pordenone.it", -"potenza.it", -"pr.it", -"prato.it", -"pt.it", -"pu.it", -"pv.it", -"pz.it", -"ra.it", -"ragusa.it", -"ravenna.it", -"rc.it", -"re.it", -"reggio-calabria.it", -"reggio-emilia.it", -"reggiocalabria.it", -"reggioemilia.it", -"rg.it", -"ri.it", -"rieti.it", -"rimini.it", -"rm.it", -"rn.it", -"ro.it", -"roma.it", -"rome.it", -"rovigo.it", -"sa.it", -"salerno.it", -"sassari.it", -"savona.it", -"si.it", -"siena.it", -"siracusa.it", -"so.it", -"sondrio.it", -"sp.it", -"sr.it", -"ss.it", -"suedtirol.it", -"südtirol.it", -"sv.it", -"ta.it", -"taranto.it", -"te.it", -"tempio-olbia.it", -"tempioolbia.it", -"teramo.it", -"terni.it", -"tn.it", -"to.it", -"torino.it", -"tp.it", -"tr.it", -"trani-andria-barletta.it", -"trani-barletta-andria.it", -"traniandriabarletta.it", -"tranibarlettaandria.it", -"trapani.it", -"trento.it", -"treviso.it", -"trieste.it", -"ts.it", -"turin.it", -"tv.it", -"ud.it", -"udine.it", -"urbino-pesaro.it", -"urbinopesaro.it", -"va.it", -"varese.it", -"vb.it", -"vc.it", -"ve.it", -"venezia.it", -"venice.it", -"verbania.it", -"vercelli.it", -"verona.it", -"vi.it", -"vibo-valentia.it", -"vibovalentia.it", -"vicenza.it", -"viterbo.it", -"vr.it", -"vs.it", -"vt.it", -"vv.it", -"je", -"co.je", -"net.je", -"org.je", -"*.jm", -"jo", -"com.jo", -"org.jo", -"net.jo", -"edu.jo", -"sch.jo", -"gov.jo", -"mil.jo", -"name.jo", -"jobs", -"jp", -"ac.jp", -"ad.jp", -"co.jp", -"ed.jp", -"go.jp", -"gr.jp", -"lg.jp", -"ne.jp", -"or.jp", -"aichi.jp", -"akita.jp", -"aomori.jp", -"chiba.jp", -"ehime.jp", -"fukui.jp", -"fukuoka.jp", -"fukushima.jp", -"gifu.jp", -"gunma.jp", -"hiroshima.jp", -"hokkaido.jp", -"hyogo.jp", -"ibaraki.jp", -"ishikawa.jp", -"iwate.jp", -"kagawa.jp", -"kagoshima.jp", -"kanagawa.jp", -"kochi.jp", -"kumamoto.jp", -"kyoto.jp", -"mie.jp", -"miyagi.jp", -"miyazaki.jp", -"nagano.jp", -"nagasaki.jp", -"nara.jp", -"niigata.jp", -"oita.jp", -"okayama.jp", -"okinawa.jp", -"osaka.jp", -"saga.jp", -"saitama.jp", -"shiga.jp", -"shimane.jp", -"shizuoka.jp", -"tochigi.jp", -"tokushima.jp", -"tokyo.jp", -"tottori.jp", -"toyama.jp", -"wakayama.jp", -"yamagata.jp", -"yamaguchi.jp", -"yamanashi.jp", -"栃木.jp", -"愛知.jp", -"愛媛.jp", -"兵庫.jp", -"熊本.jp", -"茨城.jp", -"北海道.jp", -"千葉.jp", -"和歌山.jp", -"長崎.jp", -"長野.jp", -"新潟.jp", -"青森.jp", -"静岡.jp", -"東京.jp", -"石川.jp", -"埼玉.jp", -"三重.jp", -"京都.jp", -"佐賀.jp", -"大分.jp", -"大阪.jp", -"奈良.jp", -"宮城.jp", -"宮崎.jp", -"富山.jp", -"山口.jp", -"山形.jp", -"山梨.jp", -"岩手.jp", -"岐阜.jp", -"岡山.jp", -"島根.jp", -"広島.jp", -"徳島.jp", -"沖縄.jp", -"滋賀.jp", -"神奈川.jp", -"福井.jp", -"福岡.jp", -"福島.jp", -"秋田.jp", -"群馬.jp", -"香川.jp", -"高知.jp", -"鳥取.jp", -"鹿児島.jp", -"*.kawasaki.jp", -"*.kitakyushu.jp", -"*.kobe.jp", -"*.nagoya.jp", -"*.sapporo.jp", -"*.sendai.jp", -"*.yokohama.jp", -"!city.kawasaki.jp", -"!city.kitakyushu.jp", -"!city.kobe.jp", -"!city.nagoya.jp", -"!city.sapporo.jp", -"!city.sendai.jp", -"!city.yokohama.jp", -"aisai.aichi.jp", -"ama.aichi.jp", -"anjo.aichi.jp", -"asuke.aichi.jp", -"chiryu.aichi.jp", -"chita.aichi.jp", -"fuso.aichi.jp", -"gamagori.aichi.jp", -"handa.aichi.jp", -"hazu.aichi.jp", -"hekinan.aichi.jp", -"higashiura.aichi.jp", -"ichinomiya.aichi.jp", -"inazawa.aichi.jp", -"inuyama.aichi.jp", -"isshiki.aichi.jp", -"iwakura.aichi.jp", -"kanie.aichi.jp", -"kariya.aichi.jp", -"kasugai.aichi.jp", -"kira.aichi.jp", -"kiyosu.aichi.jp", -"komaki.aichi.jp", -"konan.aichi.jp", -"kota.aichi.jp", -"mihama.aichi.jp", -"miyoshi.aichi.jp", -"nishio.aichi.jp", -"nisshin.aichi.jp", -"obu.aichi.jp", -"oguchi.aichi.jp", -"oharu.aichi.jp", -"okazaki.aichi.jp", -"owariasahi.aichi.jp", -"seto.aichi.jp", -"shikatsu.aichi.jp", -"shinshiro.aichi.jp", -"shitara.aichi.jp", -"tahara.aichi.jp", -"takahama.aichi.jp", -"tobishima.aichi.jp", -"toei.aichi.jp", -"togo.aichi.jp", -"tokai.aichi.jp", -"tokoname.aichi.jp", -"toyoake.aichi.jp", -"toyohashi.aichi.jp", -"toyokawa.aichi.jp", -"toyone.aichi.jp", -"toyota.aichi.jp", -"tsushima.aichi.jp", -"yatomi.aichi.jp", -"akita.akita.jp", -"daisen.akita.jp", -"fujisato.akita.jp", -"gojome.akita.jp", -"hachirogata.akita.jp", -"happou.akita.jp", -"higashinaruse.akita.jp", -"honjo.akita.jp", -"honjyo.akita.jp", -"ikawa.akita.jp", -"kamikoani.akita.jp", -"kamioka.akita.jp", -"katagami.akita.jp", -"kazuno.akita.jp", -"kitaakita.akita.jp", -"kosaka.akita.jp", -"kyowa.akita.jp", -"misato.akita.jp", -"mitane.akita.jp", -"moriyoshi.akita.jp", -"nikaho.akita.jp", -"noshiro.akita.jp", -"odate.akita.jp", -"oga.akita.jp", -"ogata.akita.jp", -"semboku.akita.jp", -"yokote.akita.jp", -"yurihonjo.akita.jp", -"aomori.aomori.jp", -"gonohe.aomori.jp", -"hachinohe.aomori.jp", -"hashikami.aomori.jp", -"hiranai.aomori.jp", -"hirosaki.aomori.jp", -"itayanagi.aomori.jp", -"kuroishi.aomori.jp", -"misawa.aomori.jp", -"mutsu.aomori.jp", -"nakadomari.aomori.jp", -"noheji.aomori.jp", -"oirase.aomori.jp", -"owani.aomori.jp", -"rokunohe.aomori.jp", -"sannohe.aomori.jp", -"shichinohe.aomori.jp", -"shingo.aomori.jp", -"takko.aomori.jp", -"towada.aomori.jp", -"tsugaru.aomori.jp", -"tsuruta.aomori.jp", -"abiko.chiba.jp", -"asahi.chiba.jp", -"chonan.chiba.jp", -"chosei.chiba.jp", -"choshi.chiba.jp", -"chuo.chiba.jp", -"funabashi.chiba.jp", -"futtsu.chiba.jp", -"hanamigawa.chiba.jp", -"ichihara.chiba.jp", -"ichikawa.chiba.jp", -"ichinomiya.chiba.jp", -"inzai.chiba.jp", -"isumi.chiba.jp", -"kamagaya.chiba.jp", -"kamogawa.chiba.jp", -"kashiwa.chiba.jp", -"katori.chiba.jp", -"katsuura.chiba.jp", -"kimitsu.chiba.jp", -"kisarazu.chiba.jp", -"kozaki.chiba.jp", -"kujukuri.chiba.jp", -"kyonan.chiba.jp", -"matsudo.chiba.jp", -"midori.chiba.jp", -"mihama.chiba.jp", -"minamiboso.chiba.jp", -"mobara.chiba.jp", -"mutsuzawa.chiba.jp", -"nagara.chiba.jp", -"nagareyama.chiba.jp", -"narashino.chiba.jp", -"narita.chiba.jp", -"noda.chiba.jp", -"oamishirasato.chiba.jp", -"omigawa.chiba.jp", -"onjuku.chiba.jp", -"otaki.chiba.jp", -"sakae.chiba.jp", -"sakura.chiba.jp", -"shimofusa.chiba.jp", -"shirako.chiba.jp", -"shiroi.chiba.jp", -"shisui.chiba.jp", -"sodegaura.chiba.jp", -"sosa.chiba.jp", -"tako.chiba.jp", -"tateyama.chiba.jp", -"togane.chiba.jp", -"tohnosho.chiba.jp", -"tomisato.chiba.jp", -"urayasu.chiba.jp", -"yachimata.chiba.jp", -"yachiyo.chiba.jp", -"yokaichiba.chiba.jp", -"yokoshibahikari.chiba.jp", -"yotsukaido.chiba.jp", -"ainan.ehime.jp", -"honai.ehime.jp", -"ikata.ehime.jp", -"imabari.ehime.jp", -"iyo.ehime.jp", -"kamijima.ehime.jp", -"kihoku.ehime.jp", -"kumakogen.ehime.jp", -"masaki.ehime.jp", -"matsuno.ehime.jp", -"matsuyama.ehime.jp", -"namikata.ehime.jp", -"niihama.ehime.jp", -"ozu.ehime.jp", -"saijo.ehime.jp", -"seiyo.ehime.jp", -"shikokuchuo.ehime.jp", -"tobe.ehime.jp", -"toon.ehime.jp", -"uchiko.ehime.jp", -"uwajima.ehime.jp", -"yawatahama.ehime.jp", -"echizen.fukui.jp", -"eiheiji.fukui.jp", -"fukui.fukui.jp", -"ikeda.fukui.jp", -"katsuyama.fukui.jp", -"mihama.fukui.jp", -"minamiechizen.fukui.jp", -"obama.fukui.jp", -"ohi.fukui.jp", -"ono.fukui.jp", -"sabae.fukui.jp", -"sakai.fukui.jp", -"takahama.fukui.jp", -"tsuruga.fukui.jp", -"wakasa.fukui.jp", -"ashiya.fukuoka.jp", -"buzen.fukuoka.jp", -"chikugo.fukuoka.jp", -"chikuho.fukuoka.jp", -"chikujo.fukuoka.jp", -"chikushino.fukuoka.jp", -"chikuzen.fukuoka.jp", -"chuo.fukuoka.jp", -"dazaifu.fukuoka.jp", -"fukuchi.fukuoka.jp", -"hakata.fukuoka.jp", -"higashi.fukuoka.jp", -"hirokawa.fukuoka.jp", -"hisayama.fukuoka.jp", -"iizuka.fukuoka.jp", -"inatsuki.fukuoka.jp", -"kaho.fukuoka.jp", -"kasuga.fukuoka.jp", -"kasuya.fukuoka.jp", -"kawara.fukuoka.jp", -"keisen.fukuoka.jp", -"koga.fukuoka.jp", -"kurate.fukuoka.jp", -"kurogi.fukuoka.jp", -"kurume.fukuoka.jp", -"minami.fukuoka.jp", -"miyako.fukuoka.jp", -"miyama.fukuoka.jp", -"miyawaka.fukuoka.jp", -"mizumaki.fukuoka.jp", -"munakata.fukuoka.jp", -"nakagawa.fukuoka.jp", -"nakama.fukuoka.jp", -"nishi.fukuoka.jp", -"nogata.fukuoka.jp", -"ogori.fukuoka.jp", -"okagaki.fukuoka.jp", -"okawa.fukuoka.jp", -"oki.fukuoka.jp", -"omuta.fukuoka.jp", -"onga.fukuoka.jp", -"onojo.fukuoka.jp", -"oto.fukuoka.jp", -"saigawa.fukuoka.jp", -"sasaguri.fukuoka.jp", -"shingu.fukuoka.jp", -"shinyoshitomi.fukuoka.jp", -"shonai.fukuoka.jp", -"soeda.fukuoka.jp", -"sue.fukuoka.jp", -"tachiarai.fukuoka.jp", -"tagawa.fukuoka.jp", -"takata.fukuoka.jp", -"toho.fukuoka.jp", -"toyotsu.fukuoka.jp", -"tsuiki.fukuoka.jp", -"ukiha.fukuoka.jp", -"umi.fukuoka.jp", -"usui.fukuoka.jp", -"yamada.fukuoka.jp", -"yame.fukuoka.jp", -"yanagawa.fukuoka.jp", -"yukuhashi.fukuoka.jp", -"aizubange.fukushima.jp", -"aizumisato.fukushima.jp", -"aizuwakamatsu.fukushima.jp", -"asakawa.fukushima.jp", -"bandai.fukushima.jp", -"date.fukushima.jp", -"fukushima.fukushima.jp", -"furudono.fukushima.jp", -"futaba.fukushima.jp", -"hanawa.fukushima.jp", -"higashi.fukushima.jp", -"hirata.fukushima.jp", -"hirono.fukushima.jp", -"iitate.fukushima.jp", -"inawashiro.fukushima.jp", -"ishikawa.fukushima.jp", -"iwaki.fukushima.jp", -"izumizaki.fukushima.jp", -"kagamiishi.fukushima.jp", -"kaneyama.fukushima.jp", -"kawamata.fukushima.jp", -"kitakata.fukushima.jp", -"kitashiobara.fukushima.jp", -"koori.fukushima.jp", -"koriyama.fukushima.jp", -"kunimi.fukushima.jp", -"miharu.fukushima.jp", -"mishima.fukushima.jp", -"namie.fukushima.jp", -"nango.fukushima.jp", -"nishiaizu.fukushima.jp", -"nishigo.fukushima.jp", -"okuma.fukushima.jp", -"omotego.fukushima.jp", -"ono.fukushima.jp", -"otama.fukushima.jp", -"samegawa.fukushima.jp", -"shimogo.fukushima.jp", -"shirakawa.fukushima.jp", -"showa.fukushima.jp", -"soma.fukushima.jp", -"sukagawa.fukushima.jp", -"taishin.fukushima.jp", -"tamakawa.fukushima.jp", -"tanagura.fukushima.jp", -"tenei.fukushima.jp", -"yabuki.fukushima.jp", -"yamato.fukushima.jp", -"yamatsuri.fukushima.jp", -"yanaizu.fukushima.jp", -"yugawa.fukushima.jp", -"anpachi.gifu.jp", -"ena.gifu.jp", -"gifu.gifu.jp", -"ginan.gifu.jp", -"godo.gifu.jp", -"gujo.gifu.jp", -"hashima.gifu.jp", -"hichiso.gifu.jp", -"hida.gifu.jp", -"higashishirakawa.gifu.jp", -"ibigawa.gifu.jp", -"ikeda.gifu.jp", -"kakamigahara.gifu.jp", -"kani.gifu.jp", -"kasahara.gifu.jp", -"kasamatsu.gifu.jp", -"kawaue.gifu.jp", -"kitagata.gifu.jp", -"mino.gifu.jp", -"minokamo.gifu.jp", -"mitake.gifu.jp", -"mizunami.gifu.jp", -"motosu.gifu.jp", -"nakatsugawa.gifu.jp", -"ogaki.gifu.jp", -"sakahogi.gifu.jp", -"seki.gifu.jp", -"sekigahara.gifu.jp", -"shirakawa.gifu.jp", -"tajimi.gifu.jp", -"takayama.gifu.jp", -"tarui.gifu.jp", -"toki.gifu.jp", -"tomika.gifu.jp", -"wanouchi.gifu.jp", -"yamagata.gifu.jp", -"yaotsu.gifu.jp", -"yoro.gifu.jp", -"annaka.gunma.jp", -"chiyoda.gunma.jp", -"fujioka.gunma.jp", -"higashiagatsuma.gunma.jp", -"isesaki.gunma.jp", -"itakura.gunma.jp", -"kanna.gunma.jp", -"kanra.gunma.jp", -"katashina.gunma.jp", -"kawaba.gunma.jp", -"kiryu.gunma.jp", -"kusatsu.gunma.jp", -"maebashi.gunma.jp", -"meiwa.gunma.jp", -"midori.gunma.jp", -"minakami.gunma.jp", -"naganohara.gunma.jp", -"nakanojo.gunma.jp", -"nanmoku.gunma.jp", -"numata.gunma.jp", -"oizumi.gunma.jp", -"ora.gunma.jp", -"ota.gunma.jp", -"shibukawa.gunma.jp", -"shimonita.gunma.jp", -"shinto.gunma.jp", -"showa.gunma.jp", -"takasaki.gunma.jp", -"takayama.gunma.jp", -"tamamura.gunma.jp", -"tatebayashi.gunma.jp", -"tomioka.gunma.jp", -"tsukiyono.gunma.jp", -"tsumagoi.gunma.jp", -"ueno.gunma.jp", -"yoshioka.gunma.jp", -"asaminami.hiroshima.jp", -"daiwa.hiroshima.jp", -"etajima.hiroshima.jp", -"fuchu.hiroshima.jp", -"fukuyama.hiroshima.jp", -"hatsukaichi.hiroshima.jp", -"higashihiroshima.hiroshima.jp", -"hongo.hiroshima.jp", -"jinsekikogen.hiroshima.jp", -"kaita.hiroshima.jp", -"kui.hiroshima.jp", -"kumano.hiroshima.jp", -"kure.hiroshima.jp", -"mihara.hiroshima.jp", -"miyoshi.hiroshima.jp", -"naka.hiroshima.jp", -"onomichi.hiroshima.jp", -"osakikamijima.hiroshima.jp", -"otake.hiroshima.jp", -"saka.hiroshima.jp", -"sera.hiroshima.jp", -"seranishi.hiroshima.jp", -"shinichi.hiroshima.jp", -"shobara.hiroshima.jp", -"takehara.hiroshima.jp", -"abashiri.hokkaido.jp", -"abira.hokkaido.jp", -"aibetsu.hokkaido.jp", -"akabira.hokkaido.jp", -"akkeshi.hokkaido.jp", -"asahikawa.hokkaido.jp", -"ashibetsu.hokkaido.jp", -"ashoro.hokkaido.jp", -"assabu.hokkaido.jp", -"atsuma.hokkaido.jp", -"bibai.hokkaido.jp", -"biei.hokkaido.jp", -"bifuka.hokkaido.jp", -"bihoro.hokkaido.jp", -"biratori.hokkaido.jp", -"chippubetsu.hokkaido.jp", -"chitose.hokkaido.jp", -"date.hokkaido.jp", -"ebetsu.hokkaido.jp", -"embetsu.hokkaido.jp", -"eniwa.hokkaido.jp", -"erimo.hokkaido.jp", -"esan.hokkaido.jp", -"esashi.hokkaido.jp", -"fukagawa.hokkaido.jp", -"fukushima.hokkaido.jp", -"furano.hokkaido.jp", -"furubira.hokkaido.jp", -"haboro.hokkaido.jp", -"hakodate.hokkaido.jp", -"hamatonbetsu.hokkaido.jp", -"hidaka.hokkaido.jp", -"higashikagura.hokkaido.jp", -"higashikawa.hokkaido.jp", -"hiroo.hokkaido.jp", -"hokuryu.hokkaido.jp", -"hokuto.hokkaido.jp", -"honbetsu.hokkaido.jp", -"horokanai.hokkaido.jp", -"horonobe.hokkaido.jp", -"ikeda.hokkaido.jp", -"imakane.hokkaido.jp", -"ishikari.hokkaido.jp", -"iwamizawa.hokkaido.jp", -"iwanai.hokkaido.jp", -"kamifurano.hokkaido.jp", -"kamikawa.hokkaido.jp", -"kamishihoro.hokkaido.jp", -"kamisunagawa.hokkaido.jp", -"kamoenai.hokkaido.jp", -"kayabe.hokkaido.jp", -"kembuchi.hokkaido.jp", -"kikonai.hokkaido.jp", -"kimobetsu.hokkaido.jp", -"kitahiroshima.hokkaido.jp", -"kitami.hokkaido.jp", -"kiyosato.hokkaido.jp", -"koshimizu.hokkaido.jp", -"kunneppu.hokkaido.jp", -"kuriyama.hokkaido.jp", -"kuromatsunai.hokkaido.jp", -"kushiro.hokkaido.jp", -"kutchan.hokkaido.jp", -"kyowa.hokkaido.jp", -"mashike.hokkaido.jp", -"matsumae.hokkaido.jp", -"mikasa.hokkaido.jp", -"minamifurano.hokkaido.jp", -"mombetsu.hokkaido.jp", -"moseushi.hokkaido.jp", -"mukawa.hokkaido.jp", -"muroran.hokkaido.jp", -"naie.hokkaido.jp", -"nakagawa.hokkaido.jp", -"nakasatsunai.hokkaido.jp", -"nakatombetsu.hokkaido.jp", -"nanae.hokkaido.jp", -"nanporo.hokkaido.jp", -"nayoro.hokkaido.jp", -"nemuro.hokkaido.jp", -"niikappu.hokkaido.jp", -"niki.hokkaido.jp", -"nishiokoppe.hokkaido.jp", -"noboribetsu.hokkaido.jp", -"numata.hokkaido.jp", -"obihiro.hokkaido.jp", -"obira.hokkaido.jp", -"oketo.hokkaido.jp", -"okoppe.hokkaido.jp", -"otaru.hokkaido.jp", -"otobe.hokkaido.jp", -"otofuke.hokkaido.jp", -"otoineppu.hokkaido.jp", -"oumu.hokkaido.jp", -"ozora.hokkaido.jp", -"pippu.hokkaido.jp", -"rankoshi.hokkaido.jp", -"rebun.hokkaido.jp", -"rikubetsu.hokkaido.jp", -"rishiri.hokkaido.jp", -"rishirifuji.hokkaido.jp", -"saroma.hokkaido.jp", -"sarufutsu.hokkaido.jp", -"shakotan.hokkaido.jp", -"shari.hokkaido.jp", -"shibecha.hokkaido.jp", -"shibetsu.hokkaido.jp", -"shikabe.hokkaido.jp", -"shikaoi.hokkaido.jp", -"shimamaki.hokkaido.jp", -"shimizu.hokkaido.jp", -"shimokawa.hokkaido.jp", -"shinshinotsu.hokkaido.jp", -"shintoku.hokkaido.jp", -"shiranuka.hokkaido.jp", -"shiraoi.hokkaido.jp", -"shiriuchi.hokkaido.jp", -"sobetsu.hokkaido.jp", -"sunagawa.hokkaido.jp", -"taiki.hokkaido.jp", -"takasu.hokkaido.jp", -"takikawa.hokkaido.jp", -"takinoue.hokkaido.jp", -"teshikaga.hokkaido.jp", -"tobetsu.hokkaido.jp", -"tohma.hokkaido.jp", -"tomakomai.hokkaido.jp", -"tomari.hokkaido.jp", -"toya.hokkaido.jp", -"toyako.hokkaido.jp", -"toyotomi.hokkaido.jp", -"toyoura.hokkaido.jp", -"tsubetsu.hokkaido.jp", -"tsukigata.hokkaido.jp", -"urakawa.hokkaido.jp", -"urausu.hokkaido.jp", -"uryu.hokkaido.jp", -"utashinai.hokkaido.jp", -"wakkanai.hokkaido.jp", -"wassamu.hokkaido.jp", -"yakumo.hokkaido.jp", -"yoichi.hokkaido.jp", -"aioi.hyogo.jp", -"akashi.hyogo.jp", -"ako.hyogo.jp", -"amagasaki.hyogo.jp", -"aogaki.hyogo.jp", -"asago.hyogo.jp", -"ashiya.hyogo.jp", -"awaji.hyogo.jp", -"fukusaki.hyogo.jp", -"goshiki.hyogo.jp", -"harima.hyogo.jp", -"himeji.hyogo.jp", -"ichikawa.hyogo.jp", -"inagawa.hyogo.jp", -"itami.hyogo.jp", -"kakogawa.hyogo.jp", -"kamigori.hyogo.jp", -"kamikawa.hyogo.jp", -"kasai.hyogo.jp", -"kasuga.hyogo.jp", -"kawanishi.hyogo.jp", -"miki.hyogo.jp", -"minamiawaji.hyogo.jp", -"nishinomiya.hyogo.jp", -"nishiwaki.hyogo.jp", -"ono.hyogo.jp", -"sanda.hyogo.jp", -"sannan.hyogo.jp", -"sasayama.hyogo.jp", -"sayo.hyogo.jp", -"shingu.hyogo.jp", -"shinonsen.hyogo.jp", -"shiso.hyogo.jp", -"sumoto.hyogo.jp", -"taishi.hyogo.jp", -"taka.hyogo.jp", -"takarazuka.hyogo.jp", -"takasago.hyogo.jp", -"takino.hyogo.jp", -"tamba.hyogo.jp", -"tatsuno.hyogo.jp", -"toyooka.hyogo.jp", -"yabu.hyogo.jp", -"yashiro.hyogo.jp", -"yoka.hyogo.jp", -"yokawa.hyogo.jp", -"ami.ibaraki.jp", -"asahi.ibaraki.jp", -"bando.ibaraki.jp", -"chikusei.ibaraki.jp", -"daigo.ibaraki.jp", -"fujishiro.ibaraki.jp", -"hitachi.ibaraki.jp", -"hitachinaka.ibaraki.jp", -"hitachiomiya.ibaraki.jp", -"hitachiota.ibaraki.jp", -"ibaraki.ibaraki.jp", -"ina.ibaraki.jp", -"inashiki.ibaraki.jp", -"itako.ibaraki.jp", -"iwama.ibaraki.jp", -"joso.ibaraki.jp", -"kamisu.ibaraki.jp", -"kasama.ibaraki.jp", -"kashima.ibaraki.jp", -"kasumigaura.ibaraki.jp", -"koga.ibaraki.jp", -"miho.ibaraki.jp", -"mito.ibaraki.jp", -"moriya.ibaraki.jp", -"naka.ibaraki.jp", -"namegata.ibaraki.jp", -"oarai.ibaraki.jp", -"ogawa.ibaraki.jp", -"omitama.ibaraki.jp", -"ryugasaki.ibaraki.jp", -"sakai.ibaraki.jp", -"sakuragawa.ibaraki.jp", -"shimodate.ibaraki.jp", -"shimotsuma.ibaraki.jp", -"shirosato.ibaraki.jp", -"sowa.ibaraki.jp", -"suifu.ibaraki.jp", -"takahagi.ibaraki.jp", -"tamatsukuri.ibaraki.jp", -"tokai.ibaraki.jp", -"tomobe.ibaraki.jp", -"tone.ibaraki.jp", -"toride.ibaraki.jp", -"tsuchiura.ibaraki.jp", -"tsukuba.ibaraki.jp", -"uchihara.ibaraki.jp", -"ushiku.ibaraki.jp", -"yachiyo.ibaraki.jp", -"yamagata.ibaraki.jp", -"yawara.ibaraki.jp", -"yuki.ibaraki.jp", -"anamizu.ishikawa.jp", -"hakui.ishikawa.jp", -"hakusan.ishikawa.jp", -"kaga.ishikawa.jp", -"kahoku.ishikawa.jp", -"kanazawa.ishikawa.jp", -"kawakita.ishikawa.jp", -"komatsu.ishikawa.jp", -"nakanoto.ishikawa.jp", -"nanao.ishikawa.jp", -"nomi.ishikawa.jp", -"nonoichi.ishikawa.jp", -"noto.ishikawa.jp", -"shika.ishikawa.jp", -"suzu.ishikawa.jp", -"tsubata.ishikawa.jp", -"tsurugi.ishikawa.jp", -"uchinada.ishikawa.jp", -"wajima.ishikawa.jp", -"fudai.iwate.jp", -"fujisawa.iwate.jp", -"hanamaki.iwate.jp", -"hiraizumi.iwate.jp", -"hirono.iwate.jp", -"ichinohe.iwate.jp", -"ichinoseki.iwate.jp", -"iwaizumi.iwate.jp", -"iwate.iwate.jp", -"joboji.iwate.jp", -"kamaishi.iwate.jp", -"kanegasaki.iwate.jp", -"karumai.iwate.jp", -"kawai.iwate.jp", -"kitakami.iwate.jp", -"kuji.iwate.jp", -"kunohe.iwate.jp", -"kuzumaki.iwate.jp", -"miyako.iwate.jp", -"mizusawa.iwate.jp", -"morioka.iwate.jp", -"ninohe.iwate.jp", -"noda.iwate.jp", -"ofunato.iwate.jp", -"oshu.iwate.jp", -"otsuchi.iwate.jp", -"rikuzentakata.iwate.jp", -"shiwa.iwate.jp", -"shizukuishi.iwate.jp", -"sumita.iwate.jp", -"tanohata.iwate.jp", -"tono.iwate.jp", -"yahaba.iwate.jp", -"yamada.iwate.jp", -"ayagawa.kagawa.jp", -"higashikagawa.kagawa.jp", -"kanonji.kagawa.jp", -"kotohira.kagawa.jp", -"manno.kagawa.jp", -"marugame.kagawa.jp", -"mitoyo.kagawa.jp", -"naoshima.kagawa.jp", -"sanuki.kagawa.jp", -"tadotsu.kagawa.jp", -"takamatsu.kagawa.jp", -"tonosho.kagawa.jp", -"uchinomi.kagawa.jp", -"utazu.kagawa.jp", -"zentsuji.kagawa.jp", -"akune.kagoshima.jp", -"amami.kagoshima.jp", -"hioki.kagoshima.jp", -"isa.kagoshima.jp", -"isen.kagoshima.jp", -"izumi.kagoshima.jp", -"kagoshima.kagoshima.jp", -"kanoya.kagoshima.jp", -"kawanabe.kagoshima.jp", -"kinko.kagoshima.jp", -"kouyama.kagoshima.jp", -"makurazaki.kagoshima.jp", -"matsumoto.kagoshima.jp", -"minamitane.kagoshima.jp", -"nakatane.kagoshima.jp", -"nishinoomote.kagoshima.jp", -"satsumasendai.kagoshima.jp", -"soo.kagoshima.jp", -"tarumizu.kagoshima.jp", -"yusui.kagoshima.jp", -"aikawa.kanagawa.jp", -"atsugi.kanagawa.jp", -"ayase.kanagawa.jp", -"chigasaki.kanagawa.jp", -"ebina.kanagawa.jp", -"fujisawa.kanagawa.jp", -"hadano.kanagawa.jp", -"hakone.kanagawa.jp", -"hiratsuka.kanagawa.jp", -"isehara.kanagawa.jp", -"kaisei.kanagawa.jp", -"kamakura.kanagawa.jp", -"kiyokawa.kanagawa.jp", -"matsuda.kanagawa.jp", -"minamiashigara.kanagawa.jp", -"miura.kanagawa.jp", -"nakai.kanagawa.jp", -"ninomiya.kanagawa.jp", -"odawara.kanagawa.jp", -"oi.kanagawa.jp", -"oiso.kanagawa.jp", -"sagamihara.kanagawa.jp", -"samukawa.kanagawa.jp", -"tsukui.kanagawa.jp", -"yamakita.kanagawa.jp", -"yamato.kanagawa.jp", -"yokosuka.kanagawa.jp", -"yugawara.kanagawa.jp", -"zama.kanagawa.jp", -"zushi.kanagawa.jp", -"aki.kochi.jp", -"geisei.kochi.jp", -"hidaka.kochi.jp", -"higashitsuno.kochi.jp", -"ino.kochi.jp", -"kagami.kochi.jp", -"kami.kochi.jp", -"kitagawa.kochi.jp", -"kochi.kochi.jp", -"mihara.kochi.jp", -"motoyama.kochi.jp", -"muroto.kochi.jp", -"nahari.kochi.jp", -"nakamura.kochi.jp", -"nankoku.kochi.jp", -"nishitosa.kochi.jp", -"niyodogawa.kochi.jp", -"ochi.kochi.jp", -"okawa.kochi.jp", -"otoyo.kochi.jp", -"otsuki.kochi.jp", -"sakawa.kochi.jp", -"sukumo.kochi.jp", -"susaki.kochi.jp", -"tosa.kochi.jp", -"tosashimizu.kochi.jp", -"toyo.kochi.jp", -"tsuno.kochi.jp", -"umaji.kochi.jp", -"yasuda.kochi.jp", -"yusuhara.kochi.jp", -"amakusa.kumamoto.jp", -"arao.kumamoto.jp", -"aso.kumamoto.jp", -"choyo.kumamoto.jp", -"gyokuto.kumamoto.jp", -"kamiamakusa.kumamoto.jp", -"kikuchi.kumamoto.jp", -"kumamoto.kumamoto.jp", -"mashiki.kumamoto.jp", -"mifune.kumamoto.jp", -"minamata.kumamoto.jp", -"minamioguni.kumamoto.jp", -"nagasu.kumamoto.jp", -"nishihara.kumamoto.jp", -"oguni.kumamoto.jp", -"ozu.kumamoto.jp", -"sumoto.kumamoto.jp", -"takamori.kumamoto.jp", -"uki.kumamoto.jp", -"uto.kumamoto.jp", -"yamaga.kumamoto.jp", -"yamato.kumamoto.jp", -"yatsushiro.kumamoto.jp", -"ayabe.kyoto.jp", -"fukuchiyama.kyoto.jp", -"higashiyama.kyoto.jp", -"ide.kyoto.jp", -"ine.kyoto.jp", -"joyo.kyoto.jp", -"kameoka.kyoto.jp", -"kamo.kyoto.jp", -"kita.kyoto.jp", -"kizu.kyoto.jp", -"kumiyama.kyoto.jp", -"kyotamba.kyoto.jp", -"kyotanabe.kyoto.jp", -"kyotango.kyoto.jp", -"maizuru.kyoto.jp", -"minami.kyoto.jp", -"minamiyamashiro.kyoto.jp", -"miyazu.kyoto.jp", -"muko.kyoto.jp", -"nagaokakyo.kyoto.jp", -"nakagyo.kyoto.jp", -"nantan.kyoto.jp", -"oyamazaki.kyoto.jp", -"sakyo.kyoto.jp", -"seika.kyoto.jp", -"tanabe.kyoto.jp", -"uji.kyoto.jp", -"ujitawara.kyoto.jp", -"wazuka.kyoto.jp", -"yamashina.kyoto.jp", -"yawata.kyoto.jp", -"asahi.mie.jp", -"inabe.mie.jp", -"ise.mie.jp", -"kameyama.mie.jp", -"kawagoe.mie.jp", -"kiho.mie.jp", -"kisosaki.mie.jp", -"kiwa.mie.jp", -"komono.mie.jp", -"kumano.mie.jp", -"kuwana.mie.jp", -"matsusaka.mie.jp", -"meiwa.mie.jp", -"mihama.mie.jp", -"minamiise.mie.jp", -"misugi.mie.jp", -"miyama.mie.jp", -"nabari.mie.jp", -"shima.mie.jp", -"suzuka.mie.jp", -"tado.mie.jp", -"taiki.mie.jp", -"taki.mie.jp", -"tamaki.mie.jp", -"toba.mie.jp", -"tsu.mie.jp", -"udono.mie.jp", -"ureshino.mie.jp", -"watarai.mie.jp", -"yokkaichi.mie.jp", -"furukawa.miyagi.jp", -"higashimatsushima.miyagi.jp", -"ishinomaki.miyagi.jp", -"iwanuma.miyagi.jp", -"kakuda.miyagi.jp", -"kami.miyagi.jp", -"kawasaki.miyagi.jp", -"marumori.miyagi.jp", -"matsushima.miyagi.jp", -"minamisanriku.miyagi.jp", -"misato.miyagi.jp", -"murata.miyagi.jp", -"natori.miyagi.jp", -"ogawara.miyagi.jp", -"ohira.miyagi.jp", -"onagawa.miyagi.jp", -"osaki.miyagi.jp", -"rifu.miyagi.jp", -"semine.miyagi.jp", -"shibata.miyagi.jp", -"shichikashuku.miyagi.jp", -"shikama.miyagi.jp", -"shiogama.miyagi.jp", -"shiroishi.miyagi.jp", -"tagajo.miyagi.jp", -"taiwa.miyagi.jp", -"tome.miyagi.jp", -"tomiya.miyagi.jp", -"wakuya.miyagi.jp", -"watari.miyagi.jp", -"yamamoto.miyagi.jp", -"zao.miyagi.jp", -"aya.miyazaki.jp", -"ebino.miyazaki.jp", -"gokase.miyazaki.jp", -"hyuga.miyazaki.jp", -"kadogawa.miyazaki.jp", -"kawaminami.miyazaki.jp", -"kijo.miyazaki.jp", -"kitagawa.miyazaki.jp", -"kitakata.miyazaki.jp", -"kitaura.miyazaki.jp", -"kobayashi.miyazaki.jp", -"kunitomi.miyazaki.jp", -"kushima.miyazaki.jp", -"mimata.miyazaki.jp", -"miyakonojo.miyazaki.jp", -"miyazaki.miyazaki.jp", -"morotsuka.miyazaki.jp", -"nichinan.miyazaki.jp", -"nishimera.miyazaki.jp", -"nobeoka.miyazaki.jp", -"saito.miyazaki.jp", -"shiiba.miyazaki.jp", -"shintomi.miyazaki.jp", -"takaharu.miyazaki.jp", -"takanabe.miyazaki.jp", -"takazaki.miyazaki.jp", -"tsuno.miyazaki.jp", -"achi.nagano.jp", -"agematsu.nagano.jp", -"anan.nagano.jp", -"aoki.nagano.jp", -"asahi.nagano.jp", -"azumino.nagano.jp", -"chikuhoku.nagano.jp", -"chikuma.nagano.jp", -"chino.nagano.jp", -"fujimi.nagano.jp", -"hakuba.nagano.jp", -"hara.nagano.jp", -"hiraya.nagano.jp", -"iida.nagano.jp", -"iijima.nagano.jp", -"iiyama.nagano.jp", -"iizuna.nagano.jp", -"ikeda.nagano.jp", -"ikusaka.nagano.jp", -"ina.nagano.jp", -"karuizawa.nagano.jp", -"kawakami.nagano.jp", -"kiso.nagano.jp", -"kisofukushima.nagano.jp", -"kitaaiki.nagano.jp", -"komagane.nagano.jp", -"komoro.nagano.jp", -"matsukawa.nagano.jp", -"matsumoto.nagano.jp", -"miasa.nagano.jp", -"minamiaiki.nagano.jp", -"minamimaki.nagano.jp", -"minamiminowa.nagano.jp", -"minowa.nagano.jp", -"miyada.nagano.jp", -"miyota.nagano.jp", -"mochizuki.nagano.jp", -"nagano.nagano.jp", -"nagawa.nagano.jp", -"nagiso.nagano.jp", -"nakagawa.nagano.jp", -"nakano.nagano.jp", -"nozawaonsen.nagano.jp", -"obuse.nagano.jp", -"ogawa.nagano.jp", -"okaya.nagano.jp", -"omachi.nagano.jp", -"omi.nagano.jp", -"ookuwa.nagano.jp", -"ooshika.nagano.jp", -"otaki.nagano.jp", -"otari.nagano.jp", -"sakae.nagano.jp", -"sakaki.nagano.jp", -"saku.nagano.jp", -"sakuho.nagano.jp", -"shimosuwa.nagano.jp", -"shinanomachi.nagano.jp", -"shiojiri.nagano.jp", -"suwa.nagano.jp", -"suzaka.nagano.jp", -"takagi.nagano.jp", -"takamori.nagano.jp", -"takayama.nagano.jp", -"tateshina.nagano.jp", -"tatsuno.nagano.jp", -"togakushi.nagano.jp", -"togura.nagano.jp", -"tomi.nagano.jp", -"ueda.nagano.jp", -"wada.nagano.jp", -"yamagata.nagano.jp", -"yamanouchi.nagano.jp", -"yasaka.nagano.jp", -"yasuoka.nagano.jp", -"chijiwa.nagasaki.jp", -"futsu.nagasaki.jp", -"goto.nagasaki.jp", -"hasami.nagasaki.jp", -"hirado.nagasaki.jp", -"iki.nagasaki.jp", -"isahaya.nagasaki.jp", -"kawatana.nagasaki.jp", -"kuchinotsu.nagasaki.jp", -"matsuura.nagasaki.jp", -"nagasaki.nagasaki.jp", -"obama.nagasaki.jp", -"omura.nagasaki.jp", -"oseto.nagasaki.jp", -"saikai.nagasaki.jp", -"sasebo.nagasaki.jp", -"seihi.nagasaki.jp", -"shimabara.nagasaki.jp", -"shinkamigoto.nagasaki.jp", -"togitsu.nagasaki.jp", -"tsushima.nagasaki.jp", -"unzen.nagasaki.jp", -"ando.nara.jp", -"gose.nara.jp", -"heguri.nara.jp", -"higashiyoshino.nara.jp", -"ikaruga.nara.jp", -"ikoma.nara.jp", -"kamikitayama.nara.jp", -"kanmaki.nara.jp", -"kashiba.nara.jp", -"kashihara.nara.jp", -"katsuragi.nara.jp", -"kawai.nara.jp", -"kawakami.nara.jp", -"kawanishi.nara.jp", -"koryo.nara.jp", -"kurotaki.nara.jp", -"mitsue.nara.jp", -"miyake.nara.jp", -"nara.nara.jp", -"nosegawa.nara.jp", -"oji.nara.jp", -"ouda.nara.jp", -"oyodo.nara.jp", -"sakurai.nara.jp", -"sango.nara.jp", -"shimoichi.nara.jp", -"shimokitayama.nara.jp", -"shinjo.nara.jp", -"soni.nara.jp", -"takatori.nara.jp", -"tawaramoto.nara.jp", -"tenkawa.nara.jp", -"tenri.nara.jp", -"uda.nara.jp", -"yamatokoriyama.nara.jp", -"yamatotakada.nara.jp", -"yamazoe.nara.jp", -"yoshino.nara.jp", -"aga.niigata.jp", -"agano.niigata.jp", -"gosen.niigata.jp", -"itoigawa.niigata.jp", -"izumozaki.niigata.jp", -"joetsu.niigata.jp", -"kamo.niigata.jp", -"kariwa.niigata.jp", -"kashiwazaki.niigata.jp", -"minamiuonuma.niigata.jp", -"mitsuke.niigata.jp", -"muika.niigata.jp", -"murakami.niigata.jp", -"myoko.niigata.jp", -"nagaoka.niigata.jp", -"niigata.niigata.jp", -"ojiya.niigata.jp", -"omi.niigata.jp", -"sado.niigata.jp", -"sanjo.niigata.jp", -"seiro.niigata.jp", -"seirou.niigata.jp", -"sekikawa.niigata.jp", -"shibata.niigata.jp", -"tagami.niigata.jp", -"tainai.niigata.jp", -"tochio.niigata.jp", -"tokamachi.niigata.jp", -"tsubame.niigata.jp", -"tsunan.niigata.jp", -"uonuma.niigata.jp", -"yahiko.niigata.jp", -"yoita.niigata.jp", -"yuzawa.niigata.jp", -"beppu.oita.jp", -"bungoono.oita.jp", -"bungotakada.oita.jp", -"hasama.oita.jp", -"hiji.oita.jp", -"himeshima.oita.jp", -"hita.oita.jp", -"kamitsue.oita.jp", -"kokonoe.oita.jp", -"kuju.oita.jp", -"kunisaki.oita.jp", -"kusu.oita.jp", -"oita.oita.jp", -"saiki.oita.jp", -"taketa.oita.jp", -"tsukumi.oita.jp", -"usa.oita.jp", -"usuki.oita.jp", -"yufu.oita.jp", -"akaiwa.okayama.jp", -"asakuchi.okayama.jp", -"bizen.okayama.jp", -"hayashima.okayama.jp", -"ibara.okayama.jp", -"kagamino.okayama.jp", -"kasaoka.okayama.jp", -"kibichuo.okayama.jp", -"kumenan.okayama.jp", -"kurashiki.okayama.jp", -"maniwa.okayama.jp", -"misaki.okayama.jp", -"nagi.okayama.jp", -"niimi.okayama.jp", -"nishiawakura.okayama.jp", -"okayama.okayama.jp", -"satosho.okayama.jp", -"setouchi.okayama.jp", -"shinjo.okayama.jp", -"shoo.okayama.jp", -"soja.okayama.jp", -"takahashi.okayama.jp", -"tamano.okayama.jp", -"tsuyama.okayama.jp", -"wake.okayama.jp", -"yakage.okayama.jp", -"aguni.okinawa.jp", -"ginowan.okinawa.jp", -"ginoza.okinawa.jp", -"gushikami.okinawa.jp", -"haebaru.okinawa.jp", -"higashi.okinawa.jp", -"hirara.okinawa.jp", -"iheya.okinawa.jp", -"ishigaki.okinawa.jp", -"ishikawa.okinawa.jp", -"itoman.okinawa.jp", -"izena.okinawa.jp", -"kadena.okinawa.jp", -"kin.okinawa.jp", -"kitadaito.okinawa.jp", -"kitanakagusuku.okinawa.jp", -"kumejima.okinawa.jp", -"kunigami.okinawa.jp", -"minamidaito.okinawa.jp", -"motobu.okinawa.jp", -"nago.okinawa.jp", -"naha.okinawa.jp", -"nakagusuku.okinawa.jp", -"nakijin.okinawa.jp", -"nanjo.okinawa.jp", -"nishihara.okinawa.jp", -"ogimi.okinawa.jp", -"okinawa.okinawa.jp", -"onna.okinawa.jp", -"shimoji.okinawa.jp", -"taketomi.okinawa.jp", -"tarama.okinawa.jp", -"tokashiki.okinawa.jp", -"tomigusuku.okinawa.jp", -"tonaki.okinawa.jp", -"urasoe.okinawa.jp", -"uruma.okinawa.jp", -"yaese.okinawa.jp", -"yomitan.okinawa.jp", -"yonabaru.okinawa.jp", -"yonaguni.okinawa.jp", -"zamami.okinawa.jp", -"abeno.osaka.jp", -"chihayaakasaka.osaka.jp", -"chuo.osaka.jp", -"daito.osaka.jp", -"fujiidera.osaka.jp", -"habikino.osaka.jp", -"hannan.osaka.jp", -"higashiosaka.osaka.jp", -"higashisumiyoshi.osaka.jp", -"higashiyodogawa.osaka.jp", -"hirakata.osaka.jp", -"ibaraki.osaka.jp", -"ikeda.osaka.jp", -"izumi.osaka.jp", -"izumiotsu.osaka.jp", -"izumisano.osaka.jp", -"kadoma.osaka.jp", -"kaizuka.osaka.jp", -"kanan.osaka.jp", -"kashiwara.osaka.jp", -"katano.osaka.jp", -"kawachinagano.osaka.jp", -"kishiwada.osaka.jp", -"kita.osaka.jp", -"kumatori.osaka.jp", -"matsubara.osaka.jp", -"minato.osaka.jp", -"minoh.osaka.jp", -"misaki.osaka.jp", -"moriguchi.osaka.jp", -"neyagawa.osaka.jp", -"nishi.osaka.jp", -"nose.osaka.jp", -"osakasayama.osaka.jp", -"sakai.osaka.jp", -"sayama.osaka.jp", -"sennan.osaka.jp", -"settsu.osaka.jp", -"shijonawate.osaka.jp", -"shimamoto.osaka.jp", -"suita.osaka.jp", -"tadaoka.osaka.jp", -"taishi.osaka.jp", -"tajiri.osaka.jp", -"takaishi.osaka.jp", -"takatsuki.osaka.jp", -"tondabayashi.osaka.jp", -"toyonaka.osaka.jp", -"toyono.osaka.jp", -"yao.osaka.jp", -"ariake.saga.jp", -"arita.saga.jp", -"fukudomi.saga.jp", -"genkai.saga.jp", -"hamatama.saga.jp", -"hizen.saga.jp", -"imari.saga.jp", -"kamimine.saga.jp", -"kanzaki.saga.jp", -"karatsu.saga.jp", -"kashima.saga.jp", -"kitagata.saga.jp", -"kitahata.saga.jp", -"kiyama.saga.jp", -"kouhoku.saga.jp", -"kyuragi.saga.jp", -"nishiarita.saga.jp", -"ogi.saga.jp", -"omachi.saga.jp", -"ouchi.saga.jp", -"saga.saga.jp", -"shiroishi.saga.jp", -"taku.saga.jp", -"tara.saga.jp", -"tosu.saga.jp", -"yoshinogari.saga.jp", -"arakawa.saitama.jp", -"asaka.saitama.jp", -"chichibu.saitama.jp", -"fujimi.saitama.jp", -"fujimino.saitama.jp", -"fukaya.saitama.jp", -"hanno.saitama.jp", -"hanyu.saitama.jp", -"hasuda.saitama.jp", -"hatogaya.saitama.jp", -"hatoyama.saitama.jp", -"hidaka.saitama.jp", -"higashichichibu.saitama.jp", -"higashimatsuyama.saitama.jp", -"honjo.saitama.jp", -"ina.saitama.jp", -"iruma.saitama.jp", -"iwatsuki.saitama.jp", -"kamiizumi.saitama.jp", -"kamikawa.saitama.jp", -"kamisato.saitama.jp", -"kasukabe.saitama.jp", -"kawagoe.saitama.jp", -"kawaguchi.saitama.jp", -"kawajima.saitama.jp", -"kazo.saitama.jp", -"kitamoto.saitama.jp", -"koshigaya.saitama.jp", -"kounosu.saitama.jp", -"kuki.saitama.jp", -"kumagaya.saitama.jp", -"matsubushi.saitama.jp", -"minano.saitama.jp", -"misato.saitama.jp", -"miyashiro.saitama.jp", -"miyoshi.saitama.jp", -"moroyama.saitama.jp", -"nagatoro.saitama.jp", -"namegawa.saitama.jp", -"niiza.saitama.jp", -"ogano.saitama.jp", -"ogawa.saitama.jp", -"ogose.saitama.jp", -"okegawa.saitama.jp", -"omiya.saitama.jp", -"otaki.saitama.jp", -"ranzan.saitama.jp", -"ryokami.saitama.jp", -"saitama.saitama.jp", -"sakado.saitama.jp", -"satte.saitama.jp", -"sayama.saitama.jp", -"shiki.saitama.jp", -"shiraoka.saitama.jp", -"soka.saitama.jp", -"sugito.saitama.jp", -"toda.saitama.jp", -"tokigawa.saitama.jp", -"tokorozawa.saitama.jp", -"tsurugashima.saitama.jp", -"urawa.saitama.jp", -"warabi.saitama.jp", -"yashio.saitama.jp", -"yokoze.saitama.jp", -"yono.saitama.jp", -"yorii.saitama.jp", -"yoshida.saitama.jp", -"yoshikawa.saitama.jp", -"yoshimi.saitama.jp", -"aisho.shiga.jp", -"gamo.shiga.jp", -"higashiomi.shiga.jp", -"hikone.shiga.jp", -"koka.shiga.jp", -"konan.shiga.jp", -"kosei.shiga.jp", -"koto.shiga.jp", -"kusatsu.shiga.jp", -"maibara.shiga.jp", -"moriyama.shiga.jp", -"nagahama.shiga.jp", -"nishiazai.shiga.jp", -"notogawa.shiga.jp", -"omihachiman.shiga.jp", -"otsu.shiga.jp", -"ritto.shiga.jp", -"ryuoh.shiga.jp", -"takashima.shiga.jp", -"takatsuki.shiga.jp", -"torahime.shiga.jp", -"toyosato.shiga.jp", -"yasu.shiga.jp", -"akagi.shimane.jp", -"ama.shimane.jp", -"gotsu.shimane.jp", -"hamada.shimane.jp", -"higashiizumo.shimane.jp", -"hikawa.shimane.jp", -"hikimi.shimane.jp", -"izumo.shimane.jp", -"kakinoki.shimane.jp", -"masuda.shimane.jp", -"matsue.shimane.jp", -"misato.shimane.jp", -"nishinoshima.shimane.jp", -"ohda.shimane.jp", -"okinoshima.shimane.jp", -"okuizumo.shimane.jp", -"shimane.shimane.jp", -"tamayu.shimane.jp", -"tsuwano.shimane.jp", -"unnan.shimane.jp", -"yakumo.shimane.jp", -"yasugi.shimane.jp", -"yatsuka.shimane.jp", -"arai.shizuoka.jp", -"atami.shizuoka.jp", -"fuji.shizuoka.jp", -"fujieda.shizuoka.jp", -"fujikawa.shizuoka.jp", -"fujinomiya.shizuoka.jp", -"fukuroi.shizuoka.jp", -"gotemba.shizuoka.jp", -"haibara.shizuoka.jp", -"hamamatsu.shizuoka.jp", -"higashiizu.shizuoka.jp", -"ito.shizuoka.jp", -"iwata.shizuoka.jp", -"izu.shizuoka.jp", -"izunokuni.shizuoka.jp", -"kakegawa.shizuoka.jp", -"kannami.shizuoka.jp", -"kawanehon.shizuoka.jp", -"kawazu.shizuoka.jp", -"kikugawa.shizuoka.jp", -"kosai.shizuoka.jp", -"makinohara.shizuoka.jp", -"matsuzaki.shizuoka.jp", -"minamiizu.shizuoka.jp", -"mishima.shizuoka.jp", -"morimachi.shizuoka.jp", -"nishiizu.shizuoka.jp", -"numazu.shizuoka.jp", -"omaezaki.shizuoka.jp", -"shimada.shizuoka.jp", -"shimizu.shizuoka.jp", -"shimoda.shizuoka.jp", -"shizuoka.shizuoka.jp", -"susono.shizuoka.jp", -"yaizu.shizuoka.jp", -"yoshida.shizuoka.jp", -"ashikaga.tochigi.jp", -"bato.tochigi.jp", -"haga.tochigi.jp", -"ichikai.tochigi.jp", -"iwafune.tochigi.jp", -"kaminokawa.tochigi.jp", -"kanuma.tochigi.jp", -"karasuyama.tochigi.jp", -"kuroiso.tochigi.jp", -"mashiko.tochigi.jp", -"mibu.tochigi.jp", -"moka.tochigi.jp", -"motegi.tochigi.jp", -"nasu.tochigi.jp", -"nasushiobara.tochigi.jp", -"nikko.tochigi.jp", -"nishikata.tochigi.jp", -"nogi.tochigi.jp", -"ohira.tochigi.jp", -"ohtawara.tochigi.jp", -"oyama.tochigi.jp", -"sakura.tochigi.jp", -"sano.tochigi.jp", -"shimotsuke.tochigi.jp", -"shioya.tochigi.jp", -"takanezawa.tochigi.jp", -"tochigi.tochigi.jp", -"tsuga.tochigi.jp", -"ujiie.tochigi.jp", -"utsunomiya.tochigi.jp", -"yaita.tochigi.jp", -"aizumi.tokushima.jp", -"anan.tokushima.jp", -"ichiba.tokushima.jp", -"itano.tokushima.jp", -"kainan.tokushima.jp", -"komatsushima.tokushima.jp", -"matsushige.tokushima.jp", -"mima.tokushima.jp", -"minami.tokushima.jp", -"miyoshi.tokushima.jp", -"mugi.tokushima.jp", -"nakagawa.tokushima.jp", -"naruto.tokushima.jp", -"sanagochi.tokushima.jp", -"shishikui.tokushima.jp", -"tokushima.tokushima.jp", -"wajiki.tokushima.jp", -"adachi.tokyo.jp", -"akiruno.tokyo.jp", -"akishima.tokyo.jp", -"aogashima.tokyo.jp", -"arakawa.tokyo.jp", -"bunkyo.tokyo.jp", -"chiyoda.tokyo.jp", -"chofu.tokyo.jp", -"chuo.tokyo.jp", -"edogawa.tokyo.jp", -"fuchu.tokyo.jp", -"fussa.tokyo.jp", -"hachijo.tokyo.jp", -"hachioji.tokyo.jp", -"hamura.tokyo.jp", -"higashikurume.tokyo.jp", -"higashimurayama.tokyo.jp", -"higashiyamato.tokyo.jp", -"hino.tokyo.jp", -"hinode.tokyo.jp", -"hinohara.tokyo.jp", -"inagi.tokyo.jp", -"itabashi.tokyo.jp", -"katsushika.tokyo.jp", -"kita.tokyo.jp", -"kiyose.tokyo.jp", -"kodaira.tokyo.jp", -"koganei.tokyo.jp", -"kokubunji.tokyo.jp", -"komae.tokyo.jp", -"koto.tokyo.jp", -"kouzushima.tokyo.jp", -"kunitachi.tokyo.jp", -"machida.tokyo.jp", -"meguro.tokyo.jp", -"minato.tokyo.jp", -"mitaka.tokyo.jp", -"mizuho.tokyo.jp", -"musashimurayama.tokyo.jp", -"musashino.tokyo.jp", -"nakano.tokyo.jp", -"nerima.tokyo.jp", -"ogasawara.tokyo.jp", -"okutama.tokyo.jp", -"ome.tokyo.jp", -"oshima.tokyo.jp", -"ota.tokyo.jp", -"setagaya.tokyo.jp", -"shibuya.tokyo.jp", -"shinagawa.tokyo.jp", -"shinjuku.tokyo.jp", -"suginami.tokyo.jp", -"sumida.tokyo.jp", -"tachikawa.tokyo.jp", -"taito.tokyo.jp", -"tama.tokyo.jp", -"toshima.tokyo.jp", -"chizu.tottori.jp", -"hino.tottori.jp", -"kawahara.tottori.jp", -"koge.tottori.jp", -"kotoura.tottori.jp", -"misasa.tottori.jp", -"nanbu.tottori.jp", -"nichinan.tottori.jp", -"sakaiminato.tottori.jp", -"tottori.tottori.jp", -"wakasa.tottori.jp", -"yazu.tottori.jp", -"yonago.tottori.jp", -"asahi.toyama.jp", -"fuchu.toyama.jp", -"fukumitsu.toyama.jp", -"funahashi.toyama.jp", -"himi.toyama.jp", -"imizu.toyama.jp", -"inami.toyama.jp", -"johana.toyama.jp", -"kamiichi.toyama.jp", -"kurobe.toyama.jp", -"nakaniikawa.toyama.jp", -"namerikawa.toyama.jp", -"nanto.toyama.jp", -"nyuzen.toyama.jp", -"oyabe.toyama.jp", -"taira.toyama.jp", -"takaoka.toyama.jp", -"tateyama.toyama.jp", -"toga.toyama.jp", -"tonami.toyama.jp", -"toyama.toyama.jp", -"unazuki.toyama.jp", -"uozu.toyama.jp", -"yamada.toyama.jp", -"arida.wakayama.jp", -"aridagawa.wakayama.jp", -"gobo.wakayama.jp", -"hashimoto.wakayama.jp", -"hidaka.wakayama.jp", -"hirogawa.wakayama.jp", -"inami.wakayama.jp", -"iwade.wakayama.jp", -"kainan.wakayama.jp", -"kamitonda.wakayama.jp", -"katsuragi.wakayama.jp", -"kimino.wakayama.jp", -"kinokawa.wakayama.jp", -"kitayama.wakayama.jp", -"koya.wakayama.jp", -"koza.wakayama.jp", -"kozagawa.wakayama.jp", -"kudoyama.wakayama.jp", -"kushimoto.wakayama.jp", -"mihama.wakayama.jp", -"misato.wakayama.jp", -"nachikatsuura.wakayama.jp", -"shingu.wakayama.jp", -"shirahama.wakayama.jp", -"taiji.wakayama.jp", -"tanabe.wakayama.jp", -"wakayama.wakayama.jp", -"yuasa.wakayama.jp", -"yura.wakayama.jp", -"asahi.yamagata.jp", -"funagata.yamagata.jp", -"higashine.yamagata.jp", -"iide.yamagata.jp", -"kahoku.yamagata.jp", -"kaminoyama.yamagata.jp", -"kaneyama.yamagata.jp", -"kawanishi.yamagata.jp", -"mamurogawa.yamagata.jp", -"mikawa.yamagata.jp", -"murayama.yamagata.jp", -"nagai.yamagata.jp", -"nakayama.yamagata.jp", -"nanyo.yamagata.jp", -"nishikawa.yamagata.jp", -"obanazawa.yamagata.jp", -"oe.yamagata.jp", -"oguni.yamagata.jp", -"ohkura.yamagata.jp", -"oishida.yamagata.jp", -"sagae.yamagata.jp", -"sakata.yamagata.jp", -"sakegawa.yamagata.jp", -"shinjo.yamagata.jp", -"shirataka.yamagata.jp", -"shonai.yamagata.jp", -"takahata.yamagata.jp", -"tendo.yamagata.jp", -"tozawa.yamagata.jp", -"tsuruoka.yamagata.jp", -"yamagata.yamagata.jp", -"yamanobe.yamagata.jp", -"yonezawa.yamagata.jp", -"yuza.yamagata.jp", -"abu.yamaguchi.jp", -"hagi.yamaguchi.jp", -"hikari.yamaguchi.jp", -"hofu.yamaguchi.jp", -"iwakuni.yamaguchi.jp", -"kudamatsu.yamaguchi.jp", -"mitou.yamaguchi.jp", -"nagato.yamaguchi.jp", -"oshima.yamaguchi.jp", -"shimonoseki.yamaguchi.jp", -"shunan.yamaguchi.jp", -"tabuse.yamaguchi.jp", -"tokuyama.yamaguchi.jp", -"toyota.yamaguchi.jp", -"ube.yamaguchi.jp", -"yuu.yamaguchi.jp", -"chuo.yamanashi.jp", -"doshi.yamanashi.jp", -"fuefuki.yamanashi.jp", -"fujikawa.yamanashi.jp", -"fujikawaguchiko.yamanashi.jp", -"fujiyoshida.yamanashi.jp", -"hayakawa.yamanashi.jp", -"hokuto.yamanashi.jp", -"ichikawamisato.yamanashi.jp", -"kai.yamanashi.jp", -"kofu.yamanashi.jp", -"koshu.yamanashi.jp", -"kosuge.yamanashi.jp", -"minami-alps.yamanashi.jp", -"minobu.yamanashi.jp", -"nakamichi.yamanashi.jp", -"nanbu.yamanashi.jp", -"narusawa.yamanashi.jp", -"nirasaki.yamanashi.jp", -"nishikatsura.yamanashi.jp", -"oshino.yamanashi.jp", -"otsuki.yamanashi.jp", -"showa.yamanashi.jp", -"tabayama.yamanashi.jp", -"tsuru.yamanashi.jp", -"uenohara.yamanashi.jp", -"yamanakako.yamanashi.jp", -"yamanashi.yamanashi.jp", -"ke", -"ac.ke", -"co.ke", -"go.ke", -"info.ke", -"me.ke", -"mobi.ke", -"ne.ke", -"or.ke", -"sc.ke", -"kg", -"org.kg", -"net.kg", -"com.kg", -"edu.kg", -"gov.kg", -"mil.kg", -"*.kh", -"ki", -"edu.ki", -"biz.ki", -"net.ki", -"org.ki", -"gov.ki", -"info.ki", -"com.ki", -"km", -"org.km", -"nom.km", -"gov.km", -"prd.km", -"tm.km", -"edu.km", -"mil.km", -"ass.km", -"com.km", -"coop.km", -"asso.km", -"presse.km", -"medecin.km", -"notaires.km", -"pharmaciens.km", -"veterinaire.km", -"gouv.km", -"kn", -"net.kn", -"org.kn", -"edu.kn", -"gov.kn", -"kp", -"com.kp", -"edu.kp", -"gov.kp", -"org.kp", -"rep.kp", -"tra.kp", -"kr", -"ac.kr", -"co.kr", -"es.kr", -"go.kr", -"hs.kr", -"kg.kr", -"mil.kr", -"ms.kr", -"ne.kr", -"or.kr", -"pe.kr", -"re.kr", -"sc.kr", -"busan.kr", -"chungbuk.kr", -"chungnam.kr", -"daegu.kr", -"daejeon.kr", -"gangwon.kr", -"gwangju.kr", -"gyeongbuk.kr", -"gyeonggi.kr", -"gyeongnam.kr", -"incheon.kr", -"jeju.kr", -"jeonbuk.kr", -"jeonnam.kr", -"seoul.kr", -"ulsan.kr", -"kw", -"com.kw", -"edu.kw", -"emb.kw", -"gov.kw", -"ind.kw", -"net.kw", -"org.kw", -"ky", -"edu.ky", -"gov.ky", -"com.ky", -"org.ky", -"net.ky", -"kz", -"org.kz", -"edu.kz", -"net.kz", -"gov.kz", -"mil.kz", -"com.kz", -"la", -"int.la", -"net.la", -"info.la", -"edu.la", -"gov.la", -"per.la", -"com.la", -"org.la", -"lb", -"com.lb", -"edu.lb", -"gov.lb", -"net.lb", -"org.lb", -"lc", -"com.lc", -"net.lc", -"co.lc", -"org.lc", -"edu.lc", -"gov.lc", -"li", -"lk", -"gov.lk", -"sch.lk", -"net.lk", -"int.lk", -"com.lk", -"org.lk", -"edu.lk", -"ngo.lk", -"soc.lk", -"web.lk", -"ltd.lk", -"assn.lk", -"grp.lk", -"hotel.lk", -"ac.lk", -"lr", -"com.lr", -"edu.lr", -"gov.lr", -"org.lr", -"net.lr", -"ls", -"ac.ls", -"biz.ls", -"co.ls", -"edu.ls", -"gov.ls", -"info.ls", -"net.ls", -"org.ls", -"sc.ls", -"lt", -"gov.lt", -"lu", -"lv", -"com.lv", -"edu.lv", -"gov.lv", -"org.lv", -"mil.lv", -"id.lv", -"net.lv", -"asn.lv", -"conf.lv", -"ly", -"com.ly", -"net.ly", -"gov.ly", -"plc.ly", -"edu.ly", -"sch.ly", -"med.ly", -"org.ly", -"id.ly", -"ma", -"co.ma", -"net.ma", -"gov.ma", -"org.ma", -"ac.ma", -"press.ma", -"mc", -"tm.mc", -"asso.mc", -"md", -"me", -"co.me", -"net.me", -"org.me", -"edu.me", -"ac.me", -"gov.me", -"its.me", -"priv.me", -"mg", -"org.mg", -"nom.mg", -"gov.mg", -"prd.mg", -"tm.mg", -"edu.mg", -"mil.mg", -"com.mg", -"co.mg", -"mh", -"mil", -"mk", -"com.mk", -"org.mk", -"net.mk", -"edu.mk", -"gov.mk", -"inf.mk", -"name.mk", -"ml", -"com.ml", -"edu.ml", -"gouv.ml", -"gov.ml", -"net.ml", -"org.ml", -"presse.ml", -"*.mm", -"mn", -"gov.mn", -"edu.mn", -"org.mn", -"mo", -"com.mo", -"net.mo", -"org.mo", -"edu.mo", -"gov.mo", -"mobi", -"mp", -"mq", -"mr", -"gov.mr", -"ms", -"com.ms", -"edu.ms", -"gov.ms", -"net.ms", -"org.ms", -"mt", -"com.mt", -"edu.mt", -"net.mt", -"org.mt", -"mu", -"com.mu", -"net.mu", -"org.mu", -"gov.mu", -"ac.mu", -"co.mu", -"or.mu", -"museum", -"academy.museum", -"agriculture.museum", -"air.museum", -"airguard.museum", -"alabama.museum", -"alaska.museum", -"amber.museum", -"ambulance.museum", -"american.museum", -"americana.museum", -"americanantiques.museum", -"americanart.museum", -"amsterdam.museum", -"and.museum", -"annefrank.museum", -"anthro.museum", -"anthropology.museum", -"antiques.museum", -"aquarium.museum", -"arboretum.museum", -"archaeological.museum", -"archaeology.museum", -"architecture.museum", -"art.museum", -"artanddesign.museum", -"artcenter.museum", -"artdeco.museum", -"arteducation.museum", -"artgallery.museum", -"arts.museum", -"artsandcrafts.museum", -"asmatart.museum", -"assassination.museum", -"assisi.museum", -"association.museum", -"astronomy.museum", -"atlanta.museum", -"austin.museum", -"australia.museum", -"automotive.museum", -"aviation.museum", -"axis.museum", -"badajoz.museum", -"baghdad.museum", -"bahn.museum", -"bale.museum", -"baltimore.museum", -"barcelona.museum", -"baseball.museum", -"basel.museum", -"baths.museum", -"bauern.museum", -"beauxarts.museum", -"beeldengeluid.museum", -"bellevue.museum", -"bergbau.museum", -"berkeley.museum", -"berlin.museum", -"bern.museum", -"bible.museum", -"bilbao.museum", -"bill.museum", -"birdart.museum", -"birthplace.museum", -"bonn.museum", -"boston.museum", -"botanical.museum", -"botanicalgarden.museum", -"botanicgarden.museum", -"botany.museum", -"brandywinevalley.museum", -"brasil.museum", -"bristol.museum", -"british.museum", -"britishcolumbia.museum", -"broadcast.museum", -"brunel.museum", -"brussel.museum", -"brussels.museum", -"bruxelles.museum", -"building.museum", -"burghof.museum", -"bus.museum", -"bushey.museum", -"cadaques.museum", -"california.museum", -"cambridge.museum", -"can.museum", -"canada.museum", -"capebreton.museum", -"carrier.museum", -"cartoonart.museum", -"casadelamoneda.museum", -"castle.museum", -"castres.museum", -"celtic.museum", -"center.museum", -"chattanooga.museum", -"cheltenham.museum", -"chesapeakebay.museum", -"chicago.museum", -"children.museum", -"childrens.museum", -"childrensgarden.museum", -"chiropractic.museum", -"chocolate.museum", -"christiansburg.museum", -"cincinnati.museum", -"cinema.museum", -"circus.museum", -"civilisation.museum", -"civilization.museum", -"civilwar.museum", -"clinton.museum", -"clock.museum", -"coal.museum", -"coastaldefence.museum", -"cody.museum", -"coldwar.museum", -"collection.museum", -"colonialwilliamsburg.museum", -"coloradoplateau.museum", -"columbia.museum", -"columbus.museum", -"communication.museum", -"communications.museum", -"community.museum", -"computer.museum", -"computerhistory.museum", -"comunicações.museum", -"contemporary.museum", -"contemporaryart.museum", -"convent.museum", -"copenhagen.museum", -"corporation.museum", -"correios-e-telecomunicações.museum", -"corvette.museum", -"costume.museum", -"countryestate.museum", -"county.museum", -"crafts.museum", -"cranbrook.museum", -"creation.museum", -"cultural.museum", -"culturalcenter.museum", -"culture.museum", -"cyber.museum", -"cymru.museum", -"dali.museum", -"dallas.museum", -"database.museum", -"ddr.museum", -"decorativearts.museum", -"delaware.museum", -"delmenhorst.museum", -"denmark.museum", -"depot.museum", -"design.museum", -"detroit.museum", -"dinosaur.museum", -"discovery.museum", -"dolls.museum", -"donostia.museum", -"durham.museum", -"eastafrica.museum", -"eastcoast.museum", -"education.museum", -"educational.museum", -"egyptian.museum", -"eisenbahn.museum", -"elburg.museum", -"elvendrell.museum", -"embroidery.museum", -"encyclopedic.museum", -"england.museum", -"entomology.museum", -"environment.museum", -"environmentalconservation.museum", -"epilepsy.museum", -"essex.museum", -"estate.museum", -"ethnology.museum", -"exeter.museum", -"exhibition.museum", -"family.museum", -"farm.museum", -"farmequipment.museum", -"farmers.museum", -"farmstead.museum", -"field.museum", -"figueres.museum", -"filatelia.museum", -"film.museum", -"fineart.museum", -"finearts.museum", -"finland.museum", -"flanders.museum", -"florida.museum", -"force.museum", -"fortmissoula.museum", -"fortworth.museum", -"foundation.museum", -"francaise.museum", -"frankfurt.museum", -"franziskaner.museum", -"freemasonry.museum", -"freiburg.museum", -"fribourg.museum", -"frog.museum", -"fundacio.museum", -"furniture.museum", -"gallery.museum", -"garden.museum", -"gateway.museum", -"geelvinck.museum", -"gemological.museum", -"geology.museum", -"georgia.museum", -"giessen.museum", -"glas.museum", -"glass.museum", -"gorge.museum", -"grandrapids.museum", -"graz.museum", -"guernsey.museum", -"halloffame.museum", -"hamburg.museum", -"handson.museum", -"harvestcelebration.museum", -"hawaii.museum", -"health.museum", -"heimatunduhren.museum", -"hellas.museum", -"helsinki.museum", -"hembygdsforbund.museum", -"heritage.museum", -"histoire.museum", -"historical.museum", -"historicalsociety.museum", -"historichouses.museum", -"historisch.museum", -"historisches.museum", -"history.museum", -"historyofscience.museum", -"horology.museum", -"house.museum", -"humanities.museum", -"illustration.museum", -"imageandsound.museum", -"indian.museum", -"indiana.museum", -"indianapolis.museum", -"indianmarket.museum", -"intelligence.museum", -"interactive.museum", -"iraq.museum", -"iron.museum", -"isleofman.museum", -"jamison.museum", -"jefferson.museum", -"jerusalem.museum", -"jewelry.museum", -"jewish.museum", -"jewishart.museum", -"jfk.museum", -"journalism.museum", -"judaica.museum", -"judygarland.museum", -"juedisches.museum", -"juif.museum", -"karate.museum", -"karikatur.museum", -"kids.museum", -"koebenhavn.museum", -"koeln.museum", -"kunst.museum", -"kunstsammlung.museum", -"kunstunddesign.museum", -"labor.museum", -"labour.museum", -"lajolla.museum", -"lancashire.museum", -"landes.museum", -"lans.museum", -"läns.museum", -"larsson.museum", -"lewismiller.museum", -"lincoln.museum", -"linz.museum", -"living.museum", -"livinghistory.museum", -"localhistory.museum", -"london.museum", -"losangeles.museum", -"louvre.museum", -"loyalist.museum", -"lucerne.museum", -"luxembourg.museum", -"luzern.museum", -"mad.museum", -"madrid.museum", -"mallorca.museum", -"manchester.museum", -"mansion.museum", -"mansions.museum", -"manx.museum", -"marburg.museum", -"maritime.museum", -"maritimo.museum", -"maryland.museum", -"marylhurst.museum", -"media.museum", -"medical.museum", -"medizinhistorisches.museum", -"meeres.museum", -"memorial.museum", -"mesaverde.museum", -"michigan.museum", -"midatlantic.museum", -"military.museum", -"mill.museum", -"miners.museum", -"mining.museum", -"minnesota.museum", -"missile.museum", -"missoula.museum", -"modern.museum", -"moma.museum", -"money.museum", -"monmouth.museum", -"monticello.museum", -"montreal.museum", -"moscow.museum", -"motorcycle.museum", -"muenchen.museum", -"muenster.museum", -"mulhouse.museum", -"muncie.museum", -"museet.museum", -"museumcenter.museum", -"museumvereniging.museum", -"music.museum", -"national.museum", -"nationalfirearms.museum", -"nationalheritage.museum", -"nativeamerican.museum", -"naturalhistory.museum", -"naturalhistorymuseum.museum", -"naturalsciences.museum", -"nature.museum", -"naturhistorisches.museum", -"natuurwetenschappen.museum", -"naumburg.museum", -"naval.museum", -"nebraska.museum", -"neues.museum", -"newhampshire.museum", -"newjersey.museum", -"newmexico.museum", -"newport.museum", -"newspaper.museum", -"newyork.museum", -"niepce.museum", -"norfolk.museum", -"north.museum", -"nrw.museum", -"nyc.museum", -"nyny.museum", -"oceanographic.museum", -"oceanographique.museum", -"omaha.museum", -"online.museum", -"ontario.museum", -"openair.museum", -"oregon.museum", -"oregontrail.museum", -"otago.museum", -"oxford.museum", -"pacific.museum", -"paderborn.museum", -"palace.museum", -"paleo.museum", -"palmsprings.museum", -"panama.museum", -"paris.museum", -"pasadena.museum", -"pharmacy.museum", -"philadelphia.museum", -"philadelphiaarea.museum", -"philately.museum", -"phoenix.museum", -"photography.museum", -"pilots.museum", -"pittsburgh.museum", -"planetarium.museum", -"plantation.museum", -"plants.museum", -"plaza.museum", -"portal.museum", -"portland.museum", -"portlligat.museum", -"posts-and-telecommunications.museum", -"preservation.museum", -"presidio.museum", -"press.museum", -"project.museum", -"public.museum", -"pubol.museum", -"quebec.museum", -"railroad.museum", -"railway.museum", -"research.museum", -"resistance.museum", -"riodejaneiro.museum", -"rochester.museum", -"rockart.museum", -"roma.museum", -"russia.museum", -"saintlouis.museum", -"salem.museum", -"salvadordali.museum", -"salzburg.museum", -"sandiego.museum", -"sanfrancisco.museum", -"santabarbara.museum", -"santacruz.museum", -"santafe.museum", -"saskatchewan.museum", -"satx.museum", -"savannahga.museum", -"schlesisches.museum", -"schoenbrunn.museum", -"schokoladen.museum", -"school.museum", -"schweiz.museum", -"science.museum", -"scienceandhistory.museum", -"scienceandindustry.museum", -"sciencecenter.museum", -"sciencecenters.museum", -"science-fiction.museum", -"sciencehistory.museum", -"sciences.museum", -"sciencesnaturelles.museum", -"scotland.museum", -"seaport.museum", -"settlement.museum", -"settlers.museum", -"shell.museum", -"sherbrooke.museum", -"sibenik.museum", -"silk.museum", -"ski.museum", -"skole.museum", -"society.museum", -"sologne.museum", -"soundandvision.museum", -"southcarolina.museum", -"southwest.museum", -"space.museum", -"spy.museum", -"square.museum", -"stadt.museum", -"stalbans.museum", -"starnberg.museum", -"state.museum", -"stateofdelaware.museum", -"station.museum", -"steam.museum", -"steiermark.museum", -"stjohn.museum", -"stockholm.museum", -"stpetersburg.museum", -"stuttgart.museum", -"suisse.museum", -"surgeonshall.museum", -"surrey.museum", -"svizzera.museum", -"sweden.museum", -"sydney.museum", -"tank.museum", -"tcm.museum", -"technology.museum", -"telekommunikation.museum", -"television.museum", -"texas.museum", -"textile.museum", -"theater.museum", -"time.museum", -"timekeeping.museum", -"topology.museum", -"torino.museum", -"touch.museum", -"town.museum", -"transport.museum", -"tree.museum", -"trolley.museum", -"trust.museum", -"trustee.museum", -"uhren.museum", -"ulm.museum", -"undersea.museum", -"university.museum", -"usa.museum", -"usantiques.museum", -"usarts.museum", -"uscountryestate.museum", -"usculture.museum", -"usdecorativearts.museum", -"usgarden.museum", -"ushistory.museum", -"ushuaia.museum", -"uslivinghistory.museum", -"utah.museum", -"uvic.museum", -"valley.museum", -"vantaa.museum", -"versailles.museum", -"viking.museum", -"village.museum", -"virginia.museum", -"virtual.museum", -"virtuel.museum", -"vlaanderen.museum", -"volkenkunde.museum", -"wales.museum", -"wallonie.museum", -"war.museum", -"washingtondc.museum", -"watchandclock.museum", -"watch-and-clock.museum", -"western.museum", -"westfalen.museum", -"whaling.museum", -"wildlife.museum", -"williamsburg.museum", -"windmill.museum", -"workshop.museum", -"york.museum", -"yorkshire.museum", -"yosemite.museum", -"youth.museum", -"zoological.museum", -"zoology.museum", -"ירושלים.museum", -"иком.museum", -"mv", -"aero.mv", -"biz.mv", -"com.mv", -"coop.mv", -"edu.mv", -"gov.mv", -"info.mv", -"int.mv", -"mil.mv", -"museum.mv", -"name.mv", -"net.mv", -"org.mv", -"pro.mv", -"mw", -"ac.mw", -"biz.mw", -"co.mw", -"com.mw", -"coop.mw", -"edu.mw", -"gov.mw", -"int.mw", -"museum.mw", -"net.mw", -"org.mw", -"mx", -"com.mx", -"org.mx", -"gob.mx", -"edu.mx", -"net.mx", -"my", -"com.my", -"net.my", -"org.my", -"gov.my", -"edu.my", -"mil.my", -"name.my", -"mz", -"ac.mz", -"adv.mz", -"co.mz", -"edu.mz", -"gov.mz", -"mil.mz", -"net.mz", -"org.mz", -"na", -"info.na", -"pro.na", -"name.na", -"school.na", -"or.na", -"dr.na", -"us.na", -"mx.na", -"ca.na", -"in.na", -"cc.na", -"tv.na", -"ws.na", -"mobi.na", -"co.na", -"com.na", -"org.na", -"name", -"nc", -"asso.nc", -"nom.nc", -"ne", -"net", -"nf", -"com.nf", -"net.nf", -"per.nf", -"rec.nf", -"web.nf", -"arts.nf", -"firm.nf", -"info.nf", -"other.nf", -"store.nf", -"ng", -"com.ng", -"edu.ng", -"gov.ng", -"i.ng", -"mil.ng", -"mobi.ng", -"name.ng", -"net.ng", -"org.ng", -"sch.ng", -"ni", -"ac.ni", -"biz.ni", -"co.ni", -"com.ni", -"edu.ni", -"gob.ni", -"in.ni", -"info.ni", -"int.ni", -"mil.ni", -"net.ni", -"nom.ni", -"org.ni", -"web.ni", -"nl", -"no", -"fhs.no", -"vgs.no", -"fylkesbibl.no", -"folkebibl.no", -"museum.no", -"idrett.no", -"priv.no", -"mil.no", -"stat.no", -"dep.no", -"kommune.no", -"herad.no", -"aa.no", -"ah.no", -"bu.no", -"fm.no", -"hl.no", -"hm.no", -"jan-mayen.no", -"mr.no", -"nl.no", -"nt.no", -"of.no", -"ol.no", -"oslo.no", -"rl.no", -"sf.no", -"st.no", -"svalbard.no", -"tm.no", -"tr.no", -"va.no", -"vf.no", -"gs.aa.no", -"gs.ah.no", -"gs.bu.no", -"gs.fm.no", -"gs.hl.no", -"gs.hm.no", -"gs.jan-mayen.no", -"gs.mr.no", -"gs.nl.no", -"gs.nt.no", -"gs.of.no", -"gs.ol.no", -"gs.oslo.no", -"gs.rl.no", -"gs.sf.no", -"gs.st.no", -"gs.svalbard.no", -"gs.tm.no", -"gs.tr.no", -"gs.va.no", -"gs.vf.no", -"akrehamn.no", -"åkrehamn.no", -"algard.no", -"ålgård.no", -"arna.no", -"brumunddal.no", -"bryne.no", -"bronnoysund.no", -"brønnøysund.no", -"drobak.no", -"drøbak.no", -"egersund.no", -"fetsund.no", -"floro.no", -"florø.no", -"fredrikstad.no", -"hokksund.no", -"honefoss.no", -"hønefoss.no", -"jessheim.no", -"jorpeland.no", -"jørpeland.no", -"kirkenes.no", -"kopervik.no", -"krokstadelva.no", -"langevag.no", -"langevåg.no", -"leirvik.no", -"mjondalen.no", -"mjøndalen.no", -"mo-i-rana.no", -"mosjoen.no", -"mosjøen.no", -"nesoddtangen.no", -"orkanger.no", -"osoyro.no", -"osøyro.no", -"raholt.no", -"råholt.no", -"sandnessjoen.no", -"sandnessjøen.no", -"skedsmokorset.no", -"slattum.no", -"spjelkavik.no", -"stathelle.no", -"stavern.no", -"stjordalshalsen.no", -"stjørdalshalsen.no", -"tananger.no", -"tranby.no", -"vossevangen.no", -"afjord.no", -"åfjord.no", -"agdenes.no", -"al.no", -"ål.no", -"alesund.no", -"ålesund.no", -"alstahaug.no", -"alta.no", -"áltá.no", -"alaheadju.no", -"álaheadju.no", -"alvdal.no", -"amli.no", -"åmli.no", -"amot.no", -"åmot.no", -"andebu.no", -"andoy.no", -"andøy.no", -"andasuolo.no", -"ardal.no", -"årdal.no", -"aremark.no", -"arendal.no", -"ås.no", -"aseral.no", -"åseral.no", -"asker.no", -"askim.no", -"askvoll.no", -"askoy.no", -"askøy.no", -"asnes.no", -"åsnes.no", -"audnedaln.no", -"aukra.no", -"aure.no", -"aurland.no", -"aurskog-holand.no", -"aurskog-høland.no", -"austevoll.no", -"austrheim.no", -"averoy.no", -"averøy.no", -"balestrand.no", -"ballangen.no", -"balat.no", -"bálát.no", -"balsfjord.no", -"bahccavuotna.no", -"báhccavuotna.no", -"bamble.no", -"bardu.no", -"beardu.no", -"beiarn.no", -"bajddar.no", -"bájddar.no", -"baidar.no", -"báidár.no", -"berg.no", -"bergen.no", -"berlevag.no", -"berlevåg.no", -"bearalvahki.no", -"bearalváhki.no", -"bindal.no", -"birkenes.no", -"bjarkoy.no", -"bjarkøy.no", -"bjerkreim.no", -"bjugn.no", -"bodo.no", -"bodø.no", -"badaddja.no", -"bådåddjå.no", -"budejju.no", -"bokn.no", -"bremanger.no", -"bronnoy.no", -"brønnøy.no", -"bygland.no", -"bykle.no", -"barum.no", -"bærum.no", -"bo.telemark.no", -"bø.telemark.no", -"bo.nordland.no", -"bø.nordland.no", -"bievat.no", -"bievát.no", -"bomlo.no", -"bømlo.no", -"batsfjord.no", -"båtsfjord.no", -"bahcavuotna.no", -"báhcavuotna.no", -"dovre.no", -"drammen.no", -"drangedal.no", -"dyroy.no", -"dyrøy.no", -"donna.no", -"dønna.no", -"eid.no", -"eidfjord.no", -"eidsberg.no", -"eidskog.no", -"eidsvoll.no", -"eigersund.no", -"elverum.no", -"enebakk.no", -"engerdal.no", -"etne.no", -"etnedal.no", -"evenes.no", -"evenassi.no", -"evenášši.no", -"evje-og-hornnes.no", -"farsund.no", -"fauske.no", -"fuossko.no", -"fuoisku.no", -"fedje.no", -"fet.no", -"finnoy.no", -"finnøy.no", -"fitjar.no", -"fjaler.no", -"fjell.no", -"flakstad.no", -"flatanger.no", -"flekkefjord.no", -"flesberg.no", -"flora.no", -"fla.no", -"flå.no", -"folldal.no", -"forsand.no", -"fosnes.no", -"frei.no", -"frogn.no", -"froland.no", -"frosta.no", -"frana.no", -"fræna.no", -"froya.no", -"frøya.no", -"fusa.no", -"fyresdal.no", -"forde.no", -"førde.no", -"gamvik.no", -"gangaviika.no", -"gáŋgaviika.no", -"gaular.no", -"gausdal.no", -"gildeskal.no", -"gildeskål.no", -"giske.no", -"gjemnes.no", -"gjerdrum.no", -"gjerstad.no", -"gjesdal.no", -"gjovik.no", -"gjøvik.no", -"gloppen.no", -"gol.no", -"gran.no", -"grane.no", -"granvin.no", -"gratangen.no", -"grimstad.no", -"grong.no", -"kraanghke.no", -"kråanghke.no", -"grue.no", -"gulen.no", -"hadsel.no", -"halden.no", -"halsa.no", -"hamar.no", -"hamaroy.no", -"habmer.no", -"hábmer.no", -"hapmir.no", -"hápmir.no", -"hammerfest.no", -"hammarfeasta.no", -"hámmárfeasta.no", -"haram.no", -"hareid.no", -"harstad.no", -"hasvik.no", -"aknoluokta.no", -"ákŋoluokta.no", -"hattfjelldal.no", -"aarborte.no", -"haugesund.no", -"hemne.no", -"hemnes.no", -"hemsedal.no", -"heroy.more-og-romsdal.no", -"herøy.møre-og-romsdal.no", -"heroy.nordland.no", -"herøy.nordland.no", -"hitra.no", -"hjartdal.no", -"hjelmeland.no", -"hobol.no", -"hobøl.no", -"hof.no", -"hol.no", -"hole.no", -"holmestrand.no", -"holtalen.no", -"holtålen.no", -"hornindal.no", -"horten.no", -"hurdal.no", -"hurum.no", -"hvaler.no", -"hyllestad.no", -"hagebostad.no", -"hægebostad.no", -"hoyanger.no", -"høyanger.no", -"hoylandet.no", -"høylandet.no", -"ha.no", -"hå.no", -"ibestad.no", -"inderoy.no", -"inderøy.no", -"iveland.no", -"jevnaker.no", -"jondal.no", -"jolster.no", -"jølster.no", -"karasjok.no", -"karasjohka.no", -"kárášjohka.no", -"karlsoy.no", -"galsa.no", -"gálsá.no", -"karmoy.no", -"karmøy.no", -"kautokeino.no", -"guovdageaidnu.no", -"klepp.no", -"klabu.no", -"klæbu.no", -"kongsberg.no", -"kongsvinger.no", -"kragero.no", -"kragerø.no", -"kristiansand.no", -"kristiansund.no", -"krodsherad.no", -"krødsherad.no", -"kvalsund.no", -"rahkkeravju.no", -"ráhkkerávju.no", -"kvam.no", -"kvinesdal.no", -"kvinnherad.no", -"kviteseid.no", -"kvitsoy.no", -"kvitsøy.no", -"kvafjord.no", -"kvæfjord.no", -"giehtavuoatna.no", -"kvanangen.no", -"kvænangen.no", -"navuotna.no", -"návuotna.no", -"kafjord.no", -"kåfjord.no", -"gaivuotna.no", -"gáivuotna.no", -"larvik.no", -"lavangen.no", -"lavagis.no", -"loabat.no", -"loabát.no", -"lebesby.no", -"davvesiida.no", -"leikanger.no", -"leirfjord.no", -"leka.no", -"leksvik.no", -"lenvik.no", -"leangaviika.no", -"leaŋgaviika.no", -"lesja.no", -"levanger.no", -"lier.no", -"lierne.no", -"lillehammer.no", -"lillesand.no", -"lindesnes.no", -"lindas.no", -"lindås.no", -"lom.no", -"loppa.no", -"lahppi.no", -"láhppi.no", -"lund.no", -"lunner.no", -"luroy.no", -"lurøy.no", -"luster.no", -"lyngdal.no", -"lyngen.no", -"ivgu.no", -"lardal.no", -"lerdal.no", -"lærdal.no", -"lodingen.no", -"lødingen.no", -"lorenskog.no", -"lørenskog.no", -"loten.no", -"løten.no", -"malvik.no", -"masoy.no", -"måsøy.no", -"muosat.no", -"muosát.no", -"mandal.no", -"marker.no", -"marnardal.no", -"masfjorden.no", -"meland.no", -"meldal.no", -"melhus.no", -"meloy.no", -"meløy.no", -"meraker.no", -"meråker.no", -"moareke.no", -"moåreke.no", -"midsund.no", -"midtre-gauldal.no", -"modalen.no", -"modum.no", -"molde.no", -"moskenes.no", -"moss.no", -"mosvik.no", -"malselv.no", -"målselv.no", -"malatvuopmi.no", -"málatvuopmi.no", -"namdalseid.no", -"aejrie.no", -"namsos.no", -"namsskogan.no", -"naamesjevuemie.no", -"nååmesjevuemie.no", -"laakesvuemie.no", -"nannestad.no", -"narvik.no", -"narviika.no", -"naustdal.no", -"nedre-eiker.no", -"nes.akershus.no", -"nes.buskerud.no", -"nesna.no", -"nesodden.no", -"nesseby.no", -"unjarga.no", -"unjárga.no", -"nesset.no", -"nissedal.no", -"nittedal.no", -"nord-aurdal.no", -"nord-fron.no", -"nord-odal.no", -"norddal.no", -"nordkapp.no", -"davvenjarga.no", -"davvenjárga.no", -"nordre-land.no", -"nordreisa.no", -"raisa.no", -"ráisa.no", -"nore-og-uvdal.no", -"notodden.no", -"naroy.no", -"nærøy.no", -"notteroy.no", -"nøtterøy.no", -"odda.no", -"oksnes.no", -"øksnes.no", -"oppdal.no", -"oppegard.no", -"oppegård.no", -"orkdal.no", -"orland.no", -"ørland.no", -"orskog.no", -"ørskog.no", -"orsta.no", -"ørsta.no", -"os.hedmark.no", -"os.hordaland.no", -"osen.no", -"osteroy.no", -"osterøy.no", -"ostre-toten.no", -"østre-toten.no", -"overhalla.no", -"ovre-eiker.no", -"øvre-eiker.no", -"oyer.no", -"øyer.no", -"oygarden.no", -"øygarden.no", -"oystre-slidre.no", -"øystre-slidre.no", -"porsanger.no", -"porsangu.no", -"porsáŋgu.no", -"porsgrunn.no", -"radoy.no", -"radøy.no", -"rakkestad.no", -"rana.no", -"ruovat.no", -"randaberg.no", -"rauma.no", -"rendalen.no", -"rennebu.no", -"rennesoy.no", -"rennesøy.no", -"rindal.no", -"ringebu.no", -"ringerike.no", -"ringsaker.no", -"rissa.no", -"risor.no", -"risør.no", -"roan.no", -"rollag.no", -"rygge.no", -"ralingen.no", -"rælingen.no", -"rodoy.no", -"rødøy.no", -"romskog.no", -"rømskog.no", -"roros.no", -"røros.no", -"rost.no", -"røst.no", -"royken.no", -"røyken.no", -"royrvik.no", -"røyrvik.no", -"rade.no", -"råde.no", -"salangen.no", -"siellak.no", -"saltdal.no", -"salat.no", -"sálát.no", -"sálat.no", -"samnanger.no", -"sande.more-og-romsdal.no", -"sande.møre-og-romsdal.no", -"sande.vestfold.no", -"sandefjord.no", -"sandnes.no", -"sandoy.no", -"sandøy.no", -"sarpsborg.no", -"sauda.no", -"sauherad.no", -"sel.no", -"selbu.no", -"selje.no", -"seljord.no", -"sigdal.no", -"siljan.no", -"sirdal.no", -"skaun.no", -"skedsmo.no", -"ski.no", -"skien.no", -"skiptvet.no", -"skjervoy.no", -"skjervøy.no", -"skierva.no", -"skiervá.no", -"skjak.no", -"skjåk.no", -"skodje.no", -"skanland.no", -"skånland.no", -"skanit.no", -"skánit.no", -"smola.no", -"smøla.no", -"snillfjord.no", -"snasa.no", -"snåsa.no", -"snoasa.no", -"snaase.no", -"snåase.no", -"sogndal.no", -"sokndal.no", -"sola.no", -"solund.no", -"songdalen.no", -"sortland.no", -"spydeberg.no", -"stange.no", -"stavanger.no", -"steigen.no", -"steinkjer.no", -"stjordal.no", -"stjørdal.no", -"stokke.no", -"stor-elvdal.no", -"stord.no", -"stordal.no", -"storfjord.no", -"omasvuotna.no", -"strand.no", -"stranda.no", -"stryn.no", -"sula.no", -"suldal.no", -"sund.no", -"sunndal.no", -"surnadal.no", -"sveio.no", -"svelvik.no", -"sykkylven.no", -"sogne.no", -"søgne.no", -"somna.no", -"sømna.no", -"sondre-land.no", -"søndre-land.no", -"sor-aurdal.no", -"sør-aurdal.no", -"sor-fron.no", -"sør-fron.no", -"sor-odal.no", -"sør-odal.no", -"sor-varanger.no", -"sør-varanger.no", -"matta-varjjat.no", -"mátta-várjjat.no", -"sorfold.no", -"sørfold.no", -"sorreisa.no", -"sørreisa.no", -"sorum.no", -"sørum.no", -"tana.no", -"deatnu.no", -"time.no", -"tingvoll.no", -"tinn.no", -"tjeldsund.no", -"dielddanuorri.no", -"tjome.no", -"tjøme.no", -"tokke.no", -"tolga.no", -"torsken.no", -"tranoy.no", -"tranøy.no", -"tromso.no", -"tromsø.no", -"tromsa.no", -"romsa.no", -"trondheim.no", -"troandin.no", -"trysil.no", -"trana.no", -"træna.no", -"trogstad.no", -"trøgstad.no", -"tvedestrand.no", -"tydal.no", -"tynset.no", -"tysfjord.no", -"divtasvuodna.no", -"divttasvuotna.no", -"tysnes.no", -"tysvar.no", -"tysvær.no", -"tonsberg.no", -"tønsberg.no", -"ullensaker.no", -"ullensvang.no", -"ulvik.no", -"utsira.no", -"vadso.no", -"vadsø.no", -"cahcesuolo.no", -"čáhcesuolo.no", -"vaksdal.no", -"valle.no", -"vang.no", -"vanylven.no", -"vardo.no", -"vardø.no", -"varggat.no", -"várggát.no", -"vefsn.no", -"vaapste.no", -"vega.no", -"vegarshei.no", -"vegårshei.no", -"vennesla.no", -"verdal.no", -"verran.no", -"vestby.no", -"vestnes.no", -"vestre-slidre.no", -"vestre-toten.no", -"vestvagoy.no", -"vestvågøy.no", -"vevelstad.no", -"vik.no", -"vikna.no", -"vindafjord.no", -"volda.no", -"voss.no", -"varoy.no", -"værøy.no", -"vagan.no", -"vågan.no", -"voagat.no", -"vagsoy.no", -"vågsøy.no", -"vaga.no", -"vågå.no", -"valer.ostfold.no", -"våler.østfold.no", -"valer.hedmark.no", -"våler.hedmark.no", -"*.np", -"nr", -"biz.nr", -"info.nr", -"gov.nr", -"edu.nr", -"org.nr", -"net.nr", -"com.nr", -"nu", -"nz", -"ac.nz", -"co.nz", -"cri.nz", -"geek.nz", -"gen.nz", -"govt.nz", -"health.nz", -"iwi.nz", -"kiwi.nz", -"maori.nz", -"mil.nz", -"māori.nz", -"net.nz", -"org.nz", -"parliament.nz", -"school.nz", -"om", -"co.om", -"com.om", -"edu.om", -"gov.om", -"med.om", -"museum.om", -"net.om", -"org.om", -"pro.om", -"onion", -"org", -"pa", -"ac.pa", -"gob.pa", -"com.pa", -"org.pa", -"sld.pa", -"edu.pa", -"net.pa", -"ing.pa", -"abo.pa", -"med.pa", -"nom.pa", -"pe", -"edu.pe", -"gob.pe", -"nom.pe", -"mil.pe", -"org.pe", -"com.pe", -"net.pe", -"pf", -"com.pf", -"org.pf", -"edu.pf", -"*.pg", -"ph", -"com.ph", -"net.ph", -"org.ph", -"gov.ph", -"edu.ph", -"ngo.ph", -"mil.ph", -"i.ph", -"pk", -"com.pk", -"net.pk", -"edu.pk", -"org.pk", -"fam.pk", -"biz.pk", -"web.pk", -"gov.pk", -"gob.pk", -"gok.pk", -"gon.pk", -"gop.pk", -"gos.pk", -"info.pk", -"pl", -"com.pl", -"net.pl", -"org.pl", -"aid.pl", -"agro.pl", -"atm.pl", -"auto.pl", -"biz.pl", -"edu.pl", -"gmina.pl", -"gsm.pl", -"info.pl", -"mail.pl", -"miasta.pl", -"media.pl", -"mil.pl", -"nieruchomosci.pl", -"nom.pl", -"pc.pl", -"powiat.pl", -"priv.pl", -"realestate.pl", -"rel.pl", -"sex.pl", -"shop.pl", -"sklep.pl", -"sos.pl", -"szkola.pl", -"targi.pl", -"tm.pl", -"tourism.pl", -"travel.pl", -"turystyka.pl", -"gov.pl", -"ap.gov.pl", -"ic.gov.pl", -"is.gov.pl", -"us.gov.pl", -"kmpsp.gov.pl", -"kppsp.gov.pl", -"kwpsp.gov.pl", -"psp.gov.pl", -"wskr.gov.pl", -"kwp.gov.pl", -"mw.gov.pl", -"ug.gov.pl", -"um.gov.pl", -"umig.gov.pl", -"ugim.gov.pl", -"upow.gov.pl", -"uw.gov.pl", -"starostwo.gov.pl", -"pa.gov.pl", -"po.gov.pl", -"psse.gov.pl", -"pup.gov.pl", -"rzgw.gov.pl", -"sa.gov.pl", -"so.gov.pl", -"sr.gov.pl", -"wsa.gov.pl", -"sko.gov.pl", -"uzs.gov.pl", -"wiih.gov.pl", -"winb.gov.pl", -"pinb.gov.pl", -"wios.gov.pl", -"witd.gov.pl", -"wzmiuw.gov.pl", -"piw.gov.pl", -"wiw.gov.pl", -"griw.gov.pl", -"wif.gov.pl", -"oum.gov.pl", -"sdn.gov.pl", -"zp.gov.pl", -"uppo.gov.pl", -"mup.gov.pl", -"wuoz.gov.pl", -"konsulat.gov.pl", -"oirm.gov.pl", -"augustow.pl", -"babia-gora.pl", -"bedzin.pl", -"beskidy.pl", -"bialowieza.pl", -"bialystok.pl", -"bielawa.pl", -"bieszczady.pl", -"boleslawiec.pl", -"bydgoszcz.pl", -"bytom.pl", -"cieszyn.pl", -"czeladz.pl", -"czest.pl", -"dlugoleka.pl", -"elblag.pl", -"elk.pl", -"glogow.pl", -"gniezno.pl", -"gorlice.pl", -"grajewo.pl", -"ilawa.pl", -"jaworzno.pl", -"jelenia-gora.pl", -"jgora.pl", -"kalisz.pl", -"kazimierz-dolny.pl", -"karpacz.pl", -"kartuzy.pl", -"kaszuby.pl", -"katowice.pl", -"kepno.pl", -"ketrzyn.pl", -"klodzko.pl", -"kobierzyce.pl", -"kolobrzeg.pl", -"konin.pl", -"konskowola.pl", -"kutno.pl", -"lapy.pl", -"lebork.pl", -"legnica.pl", -"lezajsk.pl", -"limanowa.pl", -"lomza.pl", -"lowicz.pl", -"lubin.pl", -"lukow.pl", -"malbork.pl", -"malopolska.pl", -"mazowsze.pl", -"mazury.pl", -"mielec.pl", -"mielno.pl", -"mragowo.pl", -"naklo.pl", -"nowaruda.pl", -"nysa.pl", -"olawa.pl", -"olecko.pl", -"olkusz.pl", -"olsztyn.pl", -"opoczno.pl", -"opole.pl", -"ostroda.pl", -"ostroleka.pl", -"ostrowiec.pl", -"ostrowwlkp.pl", -"pila.pl", -"pisz.pl", -"podhale.pl", -"podlasie.pl", -"polkowice.pl", -"pomorze.pl", -"pomorskie.pl", -"prochowice.pl", -"pruszkow.pl", -"przeworsk.pl", -"pulawy.pl", -"radom.pl", -"rawa-maz.pl", -"rybnik.pl", -"rzeszow.pl", -"sanok.pl", -"sejny.pl", -"slask.pl", -"slupsk.pl", -"sosnowiec.pl", -"stalowa-wola.pl", -"skoczow.pl", -"starachowice.pl", -"stargard.pl", -"suwalki.pl", -"swidnica.pl", -"swiebodzin.pl", -"swinoujscie.pl", -"szczecin.pl", -"szczytno.pl", -"tarnobrzeg.pl", -"tgory.pl", -"turek.pl", -"tychy.pl", -"ustka.pl", -"walbrzych.pl", -"warmia.pl", -"warszawa.pl", -"waw.pl", -"wegrow.pl", -"wielun.pl", -"wlocl.pl", -"wloclawek.pl", -"wodzislaw.pl", -"wolomin.pl", -"wroclaw.pl", -"zachpomor.pl", -"zagan.pl", -"zarow.pl", -"zgora.pl", -"zgorzelec.pl", -"pm", -"pn", -"gov.pn", -"co.pn", -"org.pn", -"edu.pn", -"net.pn", -"post", -"pr", -"com.pr", -"net.pr", -"org.pr", -"gov.pr", -"edu.pr", -"isla.pr", -"pro.pr", -"biz.pr", -"info.pr", -"name.pr", -"est.pr", -"prof.pr", -"ac.pr", -"pro", -"aaa.pro", -"aca.pro", -"acct.pro", -"avocat.pro", -"bar.pro", -"cpa.pro", -"eng.pro", -"jur.pro", -"law.pro", -"med.pro", -"recht.pro", -"ps", -"edu.ps", -"gov.ps", -"sec.ps", -"plo.ps", -"com.ps", -"org.ps", -"net.ps", -"pt", -"net.pt", -"gov.pt", -"org.pt", -"edu.pt", -"int.pt", -"publ.pt", -"com.pt", -"nome.pt", -"pw", -"co.pw", -"ne.pw", -"or.pw", -"ed.pw", -"go.pw", -"belau.pw", -"py", -"com.py", -"coop.py", -"edu.py", -"gov.py", -"mil.py", -"net.py", -"org.py", -"qa", -"com.qa", -"edu.qa", -"gov.qa", -"mil.qa", -"name.qa", -"net.qa", -"org.qa", -"sch.qa", -"re", -"asso.re", -"com.re", -"nom.re", -"ro", -"arts.ro", -"com.ro", -"firm.ro", -"info.ro", -"nom.ro", -"nt.ro", -"org.ro", -"rec.ro", -"store.ro", -"tm.ro", -"www.ro", -"rs", -"ac.rs", -"co.rs", -"edu.rs", -"gov.rs", -"in.rs", -"org.rs", -"ru", -"ac.ru", -"edu.ru", -"gov.ru", -"int.ru", -"mil.ru", -"test.ru", -"rw", -"ac.rw", -"co.rw", -"coop.rw", -"gov.rw", -"mil.rw", -"net.rw", -"org.rw", -"sa", -"com.sa", -"net.sa", -"org.sa", -"gov.sa", -"med.sa", -"pub.sa", -"edu.sa", -"sch.sa", -"sb", -"com.sb", -"edu.sb", -"gov.sb", -"net.sb", -"org.sb", -"sc", -"com.sc", -"gov.sc", -"net.sc", -"org.sc", -"edu.sc", -"sd", -"com.sd", -"net.sd", -"org.sd", -"edu.sd", -"med.sd", -"tv.sd", -"gov.sd", -"info.sd", -"se", -"a.se", -"ac.se", -"b.se", -"bd.se", -"brand.se", -"c.se", -"d.se", -"e.se", -"f.se", -"fh.se", -"fhsk.se", -"fhv.se", -"g.se", -"h.se", -"i.se", -"k.se", -"komforb.se", -"kommunalforbund.se", -"komvux.se", -"l.se", -"lanbib.se", -"m.se", -"n.se", -"naturbruksgymn.se", -"o.se", -"org.se", -"p.se", -"parti.se", -"pp.se", -"press.se", -"r.se", -"s.se", -"t.se", -"tm.se", -"u.se", -"w.se", -"x.se", -"y.se", -"z.se", -"sg", -"com.sg", -"net.sg", -"org.sg", -"gov.sg", -"edu.sg", -"per.sg", -"sh", -"com.sh", -"net.sh", -"gov.sh", -"org.sh", -"mil.sh", -"si", -"sj", -"sk", -"sl", -"com.sl", -"net.sl", -"edu.sl", -"gov.sl", -"org.sl", -"sm", -"sn", -"art.sn", -"com.sn", -"edu.sn", -"gouv.sn", -"org.sn", -"perso.sn", -"univ.sn", -"so", -"com.so", -"net.so", -"org.so", -"sr", -"st", -"co.st", -"com.st", -"consulado.st", -"edu.st", -"embaixada.st", -"gov.st", -"mil.st", -"net.st", -"org.st", -"principe.st", -"saotome.st", -"store.st", -"su", -"sv", -"com.sv", -"edu.sv", -"gob.sv", -"org.sv", -"red.sv", -"sx", -"gov.sx", -"sy", -"edu.sy", -"gov.sy", -"net.sy", -"mil.sy", -"com.sy", -"org.sy", -"sz", -"co.sz", -"ac.sz", -"org.sz", -"tc", -"td", -"tel", -"tf", -"tg", -"th", -"ac.th", -"co.th", -"go.th", -"in.th", -"mi.th", -"net.th", -"or.th", -"tj", -"ac.tj", -"biz.tj", -"co.tj", -"com.tj", -"edu.tj", -"go.tj", -"gov.tj", -"int.tj", -"mil.tj", -"name.tj", -"net.tj", -"nic.tj", -"org.tj", -"test.tj", -"web.tj", -"tk", -"tl", -"gov.tl", -"tm", -"com.tm", -"co.tm", -"org.tm", -"net.tm", -"nom.tm", -"gov.tm", -"mil.tm", -"edu.tm", -"tn", -"com.tn", -"ens.tn", -"fin.tn", -"gov.tn", -"ind.tn", -"intl.tn", -"nat.tn", -"net.tn", -"org.tn", -"info.tn", -"perso.tn", -"tourism.tn", -"edunet.tn", -"rnrt.tn", -"rns.tn", -"rnu.tn", -"mincom.tn", -"agrinet.tn", -"defense.tn", -"turen.tn", -"to", -"com.to", -"gov.to", -"net.to", -"org.to", -"edu.to", -"mil.to", -"tr", -"av.tr", -"bbs.tr", -"bel.tr", -"biz.tr", -"com.tr", -"dr.tr", -"edu.tr", -"gen.tr", -"gov.tr", -"info.tr", -"mil.tr", -"k12.tr", -"kep.tr", -"name.tr", -"net.tr", -"org.tr", -"pol.tr", -"tel.tr", -"tsk.tr", -"tv.tr", -"web.tr", -"nc.tr", -"gov.nc.tr", -"tt", -"co.tt", -"com.tt", -"org.tt", -"net.tt", -"biz.tt", -"info.tt", -"pro.tt", -"int.tt", -"coop.tt", -"jobs.tt", -"mobi.tt", -"travel.tt", -"museum.tt", -"aero.tt", -"name.tt", -"gov.tt", -"edu.tt", -"tv", -"tw", -"edu.tw", -"gov.tw", -"mil.tw", -"com.tw", -"net.tw", -"org.tw", -"idv.tw", -"game.tw", -"ebiz.tw", -"club.tw", -"網路.tw", -"組織.tw", -"商業.tw", -"tz", -"ac.tz", -"co.tz", -"go.tz", -"hotel.tz", -"info.tz", -"me.tz", -"mil.tz", -"mobi.tz", -"ne.tz", -"or.tz", -"sc.tz", -"tv.tz", -"ua", -"com.ua", -"edu.ua", -"gov.ua", -"in.ua", -"net.ua", -"org.ua", -"cherkassy.ua", -"cherkasy.ua", -"chernigov.ua", -"chernihiv.ua", -"chernivtsi.ua", -"chernovtsy.ua", -"ck.ua", -"cn.ua", -"cr.ua", -"crimea.ua", -"cv.ua", -"dn.ua", -"dnepropetrovsk.ua", -"dnipropetrovsk.ua", -"dominic.ua", -"donetsk.ua", -"dp.ua", -"if.ua", -"ivano-frankivsk.ua", -"kh.ua", -"kharkiv.ua", -"kharkov.ua", -"kherson.ua", -"khmelnitskiy.ua", -"khmelnytskyi.ua", -"kiev.ua", -"kirovograd.ua", -"km.ua", -"kr.ua", -"krym.ua", -"ks.ua", -"kv.ua", -"kyiv.ua", -"lg.ua", -"lt.ua", -"lugansk.ua", -"lutsk.ua", -"lv.ua", -"lviv.ua", -"mk.ua", -"mykolaiv.ua", -"nikolaev.ua", -"od.ua", -"odesa.ua", -"odessa.ua", -"pl.ua", -"poltava.ua", -"rivne.ua", -"rovno.ua", -"rv.ua", -"sb.ua", -"sebastopol.ua", -"sevastopol.ua", -"sm.ua", -"sumy.ua", -"te.ua", -"ternopil.ua", -"uz.ua", -"uzhgorod.ua", -"vinnica.ua", -"vinnytsia.ua", -"vn.ua", -"volyn.ua", -"yalta.ua", -"zaporizhzhe.ua", -"zaporizhzhia.ua", -"zhitomir.ua", -"zhytomyr.ua", -"zp.ua", -"zt.ua", -"ug", -"co.ug", -"or.ug", -"ac.ug", -"sc.ug", -"go.ug", -"ne.ug", -"com.ug", -"org.ug", -"uk", -"ac.uk", -"co.uk", -"gov.uk", -"ltd.uk", -"me.uk", -"net.uk", -"nhs.uk", -"org.uk", -"plc.uk", -"police.uk", -"*.sch.uk", -"us", -"dni.us", -"fed.us", -"isa.us", -"kids.us", -"nsn.us", -"ak.us", -"al.us", -"ar.us", -"as.us", -"az.us", -"ca.us", -"co.us", -"ct.us", -"dc.us", -"de.us", -"fl.us", -"ga.us", -"gu.us", -"hi.us", -"ia.us", -"id.us", -"il.us", -"in.us", -"ks.us", -"ky.us", -"la.us", -"ma.us", -"md.us", -"me.us", -"mi.us", -"mn.us", -"mo.us", -"ms.us", -"mt.us", -"nc.us", -"nd.us", -"ne.us", -"nh.us", -"nj.us", -"nm.us", -"nv.us", -"ny.us", -"oh.us", -"ok.us", -"or.us", -"pa.us", -"pr.us", -"ri.us", -"sc.us", -"sd.us", -"tn.us", -"tx.us", -"ut.us", -"vi.us", -"vt.us", -"va.us", -"wa.us", -"wi.us", -"wv.us", -"wy.us", -"k12.ak.us", -"k12.al.us", -"k12.ar.us", -"k12.as.us", -"k12.az.us", -"k12.ca.us", -"k12.co.us", -"k12.ct.us", -"k12.dc.us", -"k12.de.us", -"k12.fl.us", -"k12.ga.us", -"k12.gu.us", -"k12.ia.us", -"k12.id.us", -"k12.il.us", -"k12.in.us", -"k12.ks.us", -"k12.ky.us", -"k12.la.us", -"k12.ma.us", -"k12.md.us", -"k12.me.us", -"k12.mi.us", -"k12.mn.us", -"k12.mo.us", -"k12.ms.us", -"k12.mt.us", -"k12.nc.us", -"k12.ne.us", -"k12.nh.us", -"k12.nj.us", -"k12.nm.us", -"k12.nv.us", -"k12.ny.us", -"k12.oh.us", -"k12.ok.us", -"k12.or.us", -"k12.pa.us", -"k12.pr.us", -"k12.ri.us", -"k12.sc.us", -"k12.tn.us", -"k12.tx.us", -"k12.ut.us", -"k12.vi.us", -"k12.vt.us", -"k12.va.us", -"k12.wa.us", -"k12.wi.us", -"k12.wy.us", -"cc.ak.us", -"cc.al.us", -"cc.ar.us", -"cc.as.us", -"cc.az.us", -"cc.ca.us", -"cc.co.us", -"cc.ct.us", -"cc.dc.us", -"cc.de.us", -"cc.fl.us", -"cc.ga.us", -"cc.gu.us", -"cc.hi.us", -"cc.ia.us", -"cc.id.us", -"cc.il.us", -"cc.in.us", -"cc.ks.us", -"cc.ky.us", -"cc.la.us", -"cc.ma.us", -"cc.md.us", -"cc.me.us", -"cc.mi.us", -"cc.mn.us", -"cc.mo.us", -"cc.ms.us", -"cc.mt.us", -"cc.nc.us", -"cc.nd.us", -"cc.ne.us", -"cc.nh.us", -"cc.nj.us", -"cc.nm.us", -"cc.nv.us", -"cc.ny.us", -"cc.oh.us", -"cc.ok.us", -"cc.or.us", -"cc.pa.us", -"cc.pr.us", -"cc.ri.us", -"cc.sc.us", -"cc.sd.us", -"cc.tn.us", -"cc.tx.us", -"cc.ut.us", -"cc.vi.us", -"cc.vt.us", -"cc.va.us", -"cc.wa.us", -"cc.wi.us", -"cc.wv.us", -"cc.wy.us", -"lib.ak.us", -"lib.al.us", -"lib.ar.us", -"lib.as.us", -"lib.az.us", -"lib.ca.us", -"lib.co.us", -"lib.ct.us", -"lib.dc.us", -"lib.fl.us", -"lib.ga.us", -"lib.gu.us", -"lib.hi.us", -"lib.ia.us", -"lib.id.us", -"lib.il.us", -"lib.in.us", -"lib.ks.us", -"lib.ky.us", -"lib.la.us", -"lib.ma.us", -"lib.md.us", -"lib.me.us", -"lib.mi.us", -"lib.mn.us", -"lib.mo.us", -"lib.ms.us", -"lib.mt.us", -"lib.nc.us", -"lib.nd.us", -"lib.ne.us", -"lib.nh.us", -"lib.nj.us", -"lib.nm.us", -"lib.nv.us", -"lib.ny.us", -"lib.oh.us", -"lib.ok.us", -"lib.or.us", -"lib.pa.us", -"lib.pr.us", -"lib.ri.us", -"lib.sc.us", -"lib.sd.us", -"lib.tn.us", -"lib.tx.us", -"lib.ut.us", -"lib.vi.us", -"lib.vt.us", -"lib.va.us", -"lib.wa.us", -"lib.wi.us", -"lib.wy.us", -"pvt.k12.ma.us", -"chtr.k12.ma.us", -"paroch.k12.ma.us", -"ann-arbor.mi.us", -"cog.mi.us", -"dst.mi.us", -"eaton.mi.us", -"gen.mi.us", -"mus.mi.us", -"tec.mi.us", -"washtenaw.mi.us", -"uy", -"com.uy", -"edu.uy", -"gub.uy", -"mil.uy", -"net.uy", -"org.uy", -"uz", -"co.uz", -"com.uz", -"net.uz", -"org.uz", -"va", -"vc", -"com.vc", -"net.vc", -"org.vc", -"gov.vc", -"mil.vc", -"edu.vc", -"ve", -"arts.ve", -"co.ve", -"com.ve", -"e12.ve", -"edu.ve", -"firm.ve", -"gob.ve", -"gov.ve", -"info.ve", -"int.ve", -"mil.ve", -"net.ve", -"org.ve", -"rec.ve", -"store.ve", -"tec.ve", -"web.ve", -"vg", -"vi", -"co.vi", -"com.vi", -"k12.vi", -"net.vi", -"org.vi", -"vn", -"com.vn", -"net.vn", -"org.vn", -"edu.vn", -"gov.vn", -"int.vn", -"ac.vn", -"biz.vn", -"info.vn", -"name.vn", -"pro.vn", -"health.vn", -"vu", -"com.vu", -"edu.vu", -"net.vu", -"org.vu", -"wf", -"ws", -"com.ws", -"net.ws", -"org.ws", -"gov.ws", -"edu.ws", -"yt", -"امارات", -"հայ", -"বাংলা", -"бг", -"бел", -"中国", -"中國", -"الجزائر", -"مصر", -"ею", -"გე", -"ελ", -"香港", -"公司.香港", -"教育.香港", -"政府.香港", -"個人.香港", -"網絡.香港", -"組織.香港", -"ಭಾರತ", -"ଭାରତ", -"ভাৰত", -"भारतम्", -"भारोत", -"ڀارت", -"ഭാരതം", -"भारत", -"بارت", -"بھارت", -"భారత్", -"ભારત", -"ਭਾਰਤ", -"ভারত", -"இந்தியா", -"ایران", -"ايران", -"عراق", -"الاردن", -"한국", -"қаз", -"ලංකා", -"இலங்கை", -"المغرب", -"мкд", -"мон", -"澳門", -"澳门", -"مليسيا", -"عمان", -"پاکستان", -"پاكستان", -"فلسطين", -"срб", -"пр.срб", -"орг.срб", -"обр.срб", -"од.срб", -"упр.срб", -"ак.срб", -"рф", -"قطر", -"السعودية", -"السعودیة", -"السعودیۃ", -"السعوديه", -"سودان", -"新加坡", -"சிங்கப்பூர்", -"سورية", -"سوريا", -"ไทย", -"ศึกษา.ไทย", -"ธุรกิจ.ไทย", -"รัฐบาล.ไทย", -"ทหาร.ไทย", -"เน็ต.ไทย", -"องค์กร.ไทย", -"تونس", -"台灣", -"台湾", -"臺灣", -"укр", -"اليمن", -"xxx", -"*.ye", -"ac.za", -"agric.za", -"alt.za", -"co.za", -"edu.za", -"gov.za", -"grondar.za", -"law.za", -"mil.za", -"net.za", -"ngo.za", -"nic.za", -"nis.za", -"nom.za", -"org.za", -"school.za", -"tm.za", -"web.za", -"zm", -"ac.zm", -"biz.zm", -"co.zm", -"com.zm", -"edu.zm", -"gov.zm", -"info.zm", -"mil.zm", -"net.zm", -"org.zm", -"sch.zm", -"zw", -"ac.zw", -"co.zw", -"gov.zw", -"mil.zw", -"org.zw", -"aaa", -"aarp", -"abarth", -"abb", -"abbott", -"abbvie", -"abc", -"able", -"abogado", -"abudhabi", -"academy", -"accenture", -"accountant", -"accountants", -"aco", -"actor", -"adac", -"ads", -"adult", -"aeg", -"aetna", -"afamilycompany", -"afl", -"africa", -"agakhan", -"agency", -"aig", -"aigo", -"airbus", -"airforce", -"airtel", -"akdn", -"alfaromeo", -"alibaba", -"alipay", -"allfinanz", -"allstate", -"ally", -"alsace", -"alstom", -"americanexpress", -"americanfamily", -"amex", -"amfam", -"amica", -"amsterdam", -"analytics", -"android", -"anquan", -"anz", -"aol", -"apartments", -"app", -"apple", -"aquarelle", -"arab", -"aramco", -"archi", -"army", -"art", -"arte", -"asda", -"associates", -"athleta", -"attorney", -"auction", -"audi", -"audible", -"audio", -"auspost", -"author", -"auto", -"autos", -"avianca", -"aws", -"axa", -"azure", -"baby", -"baidu", -"banamex", -"bananarepublic", -"band", -"bank", -"bar", -"barcelona", -"barclaycard", -"barclays", -"barefoot", -"bargains", -"baseball", -"basketball", -"bauhaus", -"bayern", -"bbc", -"bbt", -"bbva", -"bcg", -"bcn", -"beats", -"beauty", -"beer", -"bentley", -"berlin", -"best", -"bestbuy", -"bet", -"bharti", -"bible", -"bid", -"bike", -"bing", -"bingo", -"bio", -"black", -"blackfriday", -"blockbuster", -"blog", -"bloomberg", -"blue", -"bms", -"bmw", -"bnpparibas", -"boats", -"boehringer", -"bofa", -"bom", -"bond", -"boo", -"book", -"booking", -"bosch", -"bostik", -"boston", -"bot", -"boutique", -"box", -"bradesco", -"bridgestone", -"broadway", -"broker", -"brother", -"brussels", -"budapest", -"bugatti", -"build", -"builders", -"business", -"buy", -"buzz", -"bzh", -"cab", -"cafe", -"cal", -"call", -"calvinklein", -"cam", -"camera", -"camp", -"cancerresearch", -"canon", -"capetown", -"capital", -"capitalone", -"car", -"caravan", -"cards", -"care", -"career", -"careers", -"cars", -"cartier", -"casa", -"case", -"caseih", -"cash", -"casino", -"catering", -"catholic", -"cba", -"cbn", -"cbre", -"cbs", -"ceb", -"center", -"ceo", -"cern", -"cfa", -"cfd", -"chanel", -"channel", -"charity", -"chase", -"chat", -"cheap", -"chintai", -"christmas", -"chrome", -"chrysler", -"church", -"cipriani", -"circle", -"cisco", -"citadel", -"citi", -"citic", -"city", -"cityeats", -"claims", -"cleaning", -"click", -"clinic", -"clinique", -"clothing", -"cloud", -"club", -"clubmed", -"coach", -"codes", -"coffee", -"college", -"cologne", -"comcast", -"commbank", -"community", -"company", -"compare", -"computer", -"comsec", -"condos", -"construction", -"consulting", -"contact", -"contractors", -"cooking", -"cookingchannel", -"cool", -"corsica", -"country", -"coupon", -"coupons", -"courses", -"cpa", -"credit", -"creditcard", -"creditunion", -"cricket", -"crown", -"crs", -"cruise", -"cruises", -"csc", -"cuisinella", -"cymru", -"cyou", -"dabur", -"dad", -"dance", -"data", -"date", -"dating", -"datsun", -"day", -"dclk", -"dds", -"deal", -"dealer", -"deals", -"degree", -"delivery", -"dell", -"deloitte", -"delta", -"democrat", -"dental", -"dentist", -"desi", -"design", -"dev", -"dhl", -"diamonds", -"diet", -"digital", -"direct", -"directory", -"discount", -"discover", -"dish", -"diy", -"dnp", -"docs", -"doctor", -"dodge", -"dog", -"domains", -"dot", -"download", -"drive", -"dtv", -"dubai", -"duck", -"dunlop", -"dupont", -"durban", -"dvag", -"dvr", -"earth", -"eat", -"eco", -"edeka", -"education", -"email", -"emerck", -"energy", -"engineer", -"engineering", -"enterprises", -"epson", -"equipment", -"ericsson", -"erni", -"esq", -"estate", -"esurance", -"etisalat", -"eurovision", -"eus", -"events", -"everbank", -"exchange", -"expert", -"exposed", -"express", -"extraspace", -"fage", -"fail", -"fairwinds", -"faith", -"family", -"fan", -"fans", -"farm", -"farmers", -"fashion", -"fast", -"fedex", -"feedback", -"ferrari", -"ferrero", -"fiat", -"fidelity", -"fido", -"film", -"final", -"finance", -"financial", -"fire", -"firestone", -"firmdale", -"fish", -"fishing", -"fit", -"fitness", -"flickr", -"flights", -"flir", -"florist", -"flowers", -"fly", -"foo", -"food", -"foodnetwork", -"football", -"ford", -"forex", -"forsale", -"forum", -"foundation", -"fox", -"free", -"fresenius", -"frl", -"frogans", -"frontdoor", -"frontier", -"ftr", -"fujitsu", -"fujixerox", -"fun", -"fund", -"furniture", -"futbol", -"fyi", -"gal", -"gallery", -"gallo", -"gallup", -"game", -"games", -"gap", -"garden", -"gay", -"gbiz", -"gdn", -"gea", -"gent", -"genting", -"george", -"ggee", -"gift", -"gifts", -"gives", -"giving", -"glade", -"glass", -"gle", -"global", -"globo", -"gmail", -"gmbh", -"gmo", -"gmx", -"godaddy", -"gold", -"goldpoint", -"golf", -"goo", -"goodyear", -"goog", -"google", -"gop", -"got", -"grainger", -"graphics", -"gratis", -"green", -"gripe", -"grocery", -"group", -"guardian", -"gucci", -"guge", -"guide", -"guitars", -"guru", -"hair", -"hamburg", -"hangout", -"haus", -"hbo", -"hdfc", -"hdfcbank", -"health", -"healthcare", -"help", -"helsinki", -"here", -"hermes", -"hgtv", -"hiphop", -"hisamitsu", -"hitachi", -"hiv", -"hkt", -"hockey", -"holdings", -"holiday", -"homedepot", -"homegoods", -"homes", -"homesense", -"honda", -"horse", -"hospital", -"host", -"hosting", -"hot", -"hoteles", -"hotels", -"hotmail", -"house", -"how", -"hsbc", -"hughes", -"hyatt", -"hyundai", -"ibm", -"icbc", -"ice", -"icu", -"ieee", -"ifm", -"ikano", -"imamat", -"imdb", -"immo", -"immobilien", -"inc", -"industries", -"infiniti", -"ing", -"ink", -"institute", -"insurance", -"insure", -"intel", -"international", -"intuit", -"investments", -"ipiranga", -"irish", -"ismaili", -"ist", -"istanbul", -"itau", -"itv", -"iveco", -"jaguar", -"java", -"jcb", -"jcp", -"jeep", -"jetzt", -"jewelry", -"jio", -"jll", -"jmp", -"jnj", -"joburg", -"jot", -"joy", -"jpmorgan", -"jprs", -"juegos", -"juniper", -"kaufen", -"kddi", -"kerryhotels", -"kerrylogistics", -"kerryproperties", -"kfh", -"kia", -"kim", -"kinder", -"kindle", -"kitchen", -"kiwi", -"koeln", -"komatsu", -"kosher", -"kpmg", -"kpn", -"krd", -"kred", -"kuokgroup", -"kyoto", -"lacaixa", -"ladbrokes", -"lamborghini", -"lamer", -"lancaster", -"lancia", -"lancome", -"land", -"landrover", -"lanxess", -"lasalle", -"lat", -"latino", -"latrobe", -"law", -"lawyer", -"lds", -"lease", -"leclerc", -"lefrak", -"legal", -"lego", -"lexus", -"lgbt", -"liaison", -"lidl", -"life", -"lifeinsurance", -"lifestyle", -"lighting", -"like", -"lilly", -"limited", -"limo", -"lincoln", -"linde", -"link", -"lipsy", -"live", -"living", -"lixil", -"llc", -"llp", -"loan", -"loans", -"locker", -"locus", -"loft", -"lol", -"london", -"lotte", -"lotto", -"love", -"lpl", -"lplfinancial", -"ltd", -"ltda", -"lundbeck", -"lupin", -"luxe", -"luxury", -"macys", -"madrid", -"maif", -"maison", -"makeup", -"man", -"management", -"mango", -"map", -"market", -"marketing", -"markets", -"marriott", -"marshalls", -"maserati", -"mattel", -"mba", -"mckinsey", -"med", -"media", -"meet", -"melbourne", -"meme", -"memorial", -"men", -"menu", -"merckmsd", -"metlife", -"miami", -"microsoft", -"mini", -"mint", -"mit", -"mitsubishi", -"mlb", -"mls", -"mma", -"mobile", -"mobily", -"moda", -"moe", -"moi", -"mom", -"monash", -"money", -"monster", -"mopar", -"mormon", -"mortgage", -"moscow", -"moto", -"motorcycles", -"mov", -"movie", -"movistar", -"msd", -"mtn", -"mtr", -"mutual", -"nab", -"nadex", -"nagoya", -"nationwide", -"natura", -"navy", -"nba", -"nec", -"netbank", -"netflix", -"network", -"neustar", -"new", -"newholland", -"news", -"next", -"nextdirect", -"nexus", -"nfl", -"ngo", -"nhk", -"nico", -"nike", -"nikon", -"ninja", -"nissan", -"nissay", -"nokia", -"northwesternmutual", -"norton", -"now", -"nowruz", -"nowtv", -"nra", -"nrw", -"ntt", -"nyc", -"obi", -"observer", -"off", -"office", -"okinawa", -"olayan", -"olayangroup", -"oldnavy", -"ollo", -"omega", -"one", -"ong", -"onl", -"online", -"onyourside", -"ooo", -"open", -"oracle", -"orange", -"organic", -"origins", -"osaka", -"otsuka", -"ott", -"ovh", -"page", -"panasonic", -"paris", -"pars", -"partners", -"parts", -"party", -"passagens", -"pay", -"pccw", -"pet", -"pfizer", -"pharmacy", -"phd", -"philips", -"phone", -"photo", -"photography", -"photos", -"physio", -"piaget", -"pics", -"pictet", -"pictures", -"pid", -"pin", -"ping", -"pink", -"pioneer", -"pizza", -"place", -"play", -"playstation", -"plumbing", -"plus", -"pnc", -"pohl", -"poker", -"politie", -"porn", -"pramerica", -"praxi", -"press", -"prime", -"prod", -"productions", -"prof", -"progressive", -"promo", -"properties", -"property", -"protection", -"pru", -"prudential", -"pub", -"pwc", -"qpon", -"quebec", -"quest", -"qvc", -"racing", -"radio", -"raid", -"read", -"realestate", -"realtor", -"realty", -"recipes", -"red", -"redstone", -"redumbrella", -"rehab", -"reise", -"reisen", -"reit", -"reliance", -"ren", -"rent", -"rentals", -"repair", -"report", -"republican", -"rest", -"restaurant", -"review", -"reviews", -"rexroth", -"rich", -"richardli", -"ricoh", -"rightathome", -"ril", -"rio", -"rip", -"rmit", -"rocher", -"rocks", -"rodeo", -"rogers", -"room", -"rsvp", -"rugby", -"ruhr", -"run", -"rwe", -"ryukyu", -"saarland", -"safe", -"safety", -"sakura", -"sale", -"salon", -"samsclub", -"samsung", -"sandvik", -"sandvikcoromant", -"sanofi", -"sap", -"sarl", -"sas", -"save", -"saxo", -"sbi", -"sbs", -"sca", -"scb", -"schaeffler", -"schmidt", -"scholarships", -"school", -"schule", -"schwarz", -"science", -"scjohnson", -"scor", -"scot", -"search", -"seat", -"secure", -"security", -"seek", -"select", -"sener", -"services", -"ses", -"seven", -"sew", -"sex", -"sexy", -"sfr", -"shangrila", -"sharp", -"shaw", -"shell", -"shia", -"shiksha", -"shoes", -"shop", -"shopping", -"shouji", -"show", -"showtime", -"shriram", -"silk", -"sina", -"singles", -"site", -"ski", -"skin", -"sky", -"skype", -"sling", -"smart", -"smile", -"sncf", -"soccer", -"social", -"softbank", -"software", -"sohu", -"solar", -"solutions", -"song", -"sony", -"soy", -"space", -"sport", -"spot", -"spreadbetting", -"srl", -"srt", -"stada", -"staples", -"star", -"statebank", -"statefarm", -"stc", -"stcgroup", -"stockholm", -"storage", -"store", -"stream", -"studio", -"study", -"style", -"sucks", -"supplies", -"supply", -"support", -"surf", -"surgery", -"suzuki", -"swatch", -"swiftcover", -"swiss", -"sydney", -"symantec", -"systems", -"tab", -"taipei", -"talk", -"taobao", -"target", -"tatamotors", -"tatar", -"tattoo", -"tax", -"taxi", -"tci", -"tdk", -"team", -"tech", -"technology", -"telefonica", -"temasek", -"tennis", -"teva", -"thd", -"theater", -"theatre", -"tiaa", -"tickets", -"tienda", -"tiffany", -"tips", -"tires", -"tirol", -"tjmaxx", -"tjx", -"tkmaxx", -"tmall", -"today", -"tokyo", -"tools", -"top", -"toray", -"toshiba", -"total", -"tours", -"town", -"toyota", -"toys", -"trade", -"trading", -"training", -"travel", -"travelchannel", -"travelers", -"travelersinsurance", -"trust", -"trv", -"tube", -"tui", -"tunes", -"tushu", -"tvs", -"ubank", -"ubs", -"uconnect", -"unicom", -"university", -"uno", -"uol", -"ups", -"vacations", -"vana", -"vanguard", -"vegas", -"ventures", -"verisign", -"versicherung", -"vet", -"viajes", -"video", -"vig", -"viking", -"villas", -"vin", -"vip", -"virgin", -"visa", -"vision", -"vistaprint", -"viva", -"vivo", -"vlaanderen", -"vodka", -"volkswagen", -"volvo", -"vote", -"voting", -"voto", -"voyage", -"vuelos", -"wales", -"walmart", -"walter", -"wang", -"wanggou", -"warman", -"watch", -"watches", -"weather", -"weatherchannel", -"webcam", -"weber", -"website", -"wed", -"wedding", -"weibo", -"weir", -"whoswho", -"wien", -"wiki", -"williamhill", -"win", -"windows", -"wine", -"winners", -"wme", -"wolterskluwer", -"woodside", -"work", -"works", -"world", -"wow", -"wtc", -"wtf", -"xbox", -"xerox", -"xfinity", -"xihuan", -"xin", -"कॉम", -"セール", -"佛山", -"慈善", -"集团", -"在线", -"大众汽车", -"点看", -"คอม", -"八卦", -"موقع", -"公益", -"公司", -"香格里拉", -"网站", -"移动", -"我爱你", -"москва", -"католик", -"онлайн", -"сайт", -"联通", -"קום", -"时尚", -"微博", -"淡马锡", -"ファッション", -"орг", -"नेट", -"ストア", -"삼성", -"商标", -"商店", -"商城", -"дети", -"ポイント", -"新闻", -"工行", -"家電", -"كوم", -"中文网", -"中信", -"娱乐", -"谷歌", -"電訊盈科", -"购物", -"クラウド", -"通販", -"网店", -"संगठन", -"餐厅", -"网络", -"ком", -"诺基亚", -"食品", -"飞利浦", -"手表", -"手机", -"ارامكو", -"العليان", -"اتصالات", -"بازار", -"موبايلي", -"ابوظبي", -"كاثوليك", -"همراه", -"닷컴", -"政府", -"شبكة", -"بيتك", -"عرب", -"机构", -"组织机构", -"健康", -"招聘", -"рус", -"珠宝", -"大拿", -"みんな", -"グーグル", -"世界", -"書籍", -"网址", -"닷넷", -"コム", -"天主教", -"游戏", -"vermögensberater", -"vermögensberatung", -"企业", -"信息", -"嘉里大酒店", -"嘉里", -"广东", -"政务", -"xyz", -"yachts", -"yahoo", -"yamaxun", -"yandex", -"yodobashi", -"yoga", -"yokohama", -"you", -"youtube", -"yun", -"zappos", -"zara", -"zero", -"zip", -"zone", -"zuerich", -"cc.ua", -"inf.ua", -"ltd.ua", -"beep.pl", -"barsy.ca", -"*.compute.estate", -"*.alces.network", -"alwaysdata.net", -"cloudfront.net", -"*.compute.amazonaws.com", -"*.compute-1.amazonaws.com", -"*.compute.amazonaws.com.cn", -"us-east-1.amazonaws.com", -"cn-north-1.eb.amazonaws.com.cn", -"cn-northwest-1.eb.amazonaws.com.cn", -"elasticbeanstalk.com", -"ap-northeast-1.elasticbeanstalk.com", -"ap-northeast-2.elasticbeanstalk.com", -"ap-northeast-3.elasticbeanstalk.com", -"ap-south-1.elasticbeanstalk.com", -"ap-southeast-1.elasticbeanstalk.com", -"ap-southeast-2.elasticbeanstalk.com", -"ca-central-1.elasticbeanstalk.com", -"eu-central-1.elasticbeanstalk.com", -"eu-west-1.elasticbeanstalk.com", -"eu-west-2.elasticbeanstalk.com", -"eu-west-3.elasticbeanstalk.com", -"sa-east-1.elasticbeanstalk.com", -"us-east-1.elasticbeanstalk.com", -"us-east-2.elasticbeanstalk.com", -"us-gov-west-1.elasticbeanstalk.com", -"us-west-1.elasticbeanstalk.com", -"us-west-2.elasticbeanstalk.com", -"*.elb.amazonaws.com", -"*.elb.amazonaws.com.cn", -"s3.amazonaws.com", -"s3-ap-northeast-1.amazonaws.com", -"s3-ap-northeast-2.amazonaws.com", -"s3-ap-south-1.amazonaws.com", -"s3-ap-southeast-1.amazonaws.com", -"s3-ap-southeast-2.amazonaws.com", -"s3-ca-central-1.amazonaws.com", -"s3-eu-central-1.amazonaws.com", -"s3-eu-west-1.amazonaws.com", -"s3-eu-west-2.amazonaws.com", -"s3-eu-west-3.amazonaws.com", -"s3-external-1.amazonaws.com", -"s3-fips-us-gov-west-1.amazonaws.com", -"s3-sa-east-1.amazonaws.com", -"s3-us-gov-west-1.amazonaws.com", -"s3-us-east-2.amazonaws.com", -"s3-us-west-1.amazonaws.com", -"s3-us-west-2.amazonaws.com", -"s3.ap-northeast-2.amazonaws.com", -"s3.ap-south-1.amazonaws.com", -"s3.cn-north-1.amazonaws.com.cn", -"s3.ca-central-1.amazonaws.com", -"s3.eu-central-1.amazonaws.com", -"s3.eu-west-2.amazonaws.com", -"s3.eu-west-3.amazonaws.com", -"s3.us-east-2.amazonaws.com", -"s3.dualstack.ap-northeast-1.amazonaws.com", -"s3.dualstack.ap-northeast-2.amazonaws.com", -"s3.dualstack.ap-south-1.amazonaws.com", -"s3.dualstack.ap-southeast-1.amazonaws.com", -"s3.dualstack.ap-southeast-2.amazonaws.com", -"s3.dualstack.ca-central-1.amazonaws.com", -"s3.dualstack.eu-central-1.amazonaws.com", -"s3.dualstack.eu-west-1.amazonaws.com", -"s3.dualstack.eu-west-2.amazonaws.com", -"s3.dualstack.eu-west-3.amazonaws.com", -"s3.dualstack.sa-east-1.amazonaws.com", -"s3.dualstack.us-east-1.amazonaws.com", -"s3.dualstack.us-east-2.amazonaws.com", -"s3-website-us-east-1.amazonaws.com", -"s3-website-us-west-1.amazonaws.com", -"s3-website-us-west-2.amazonaws.com", -"s3-website-ap-northeast-1.amazonaws.com", -"s3-website-ap-southeast-1.amazonaws.com", -"s3-website-ap-southeast-2.amazonaws.com", -"s3-website-eu-west-1.amazonaws.com", -"s3-website-sa-east-1.amazonaws.com", -"s3-website.ap-northeast-2.amazonaws.com", -"s3-website.ap-south-1.amazonaws.com", -"s3-website.ca-central-1.amazonaws.com", -"s3-website.eu-central-1.amazonaws.com", -"s3-website.eu-west-2.amazonaws.com", -"s3-website.eu-west-3.amazonaws.com", -"s3-website.us-east-2.amazonaws.com", -"t3l3p0rt.net", -"tele.amune.org", -"apigee.io", -"on-aptible.com", -"user.aseinet.ne.jp", -"gv.vc", -"d.gv.vc", -"user.party.eus", -"pimienta.org", -"poivron.org", -"potager.org", -"sweetpepper.org", -"myasustor.com", -"go-vip.co", -"go-vip.net", -"wpcomstaging.com", -"myfritz.net", -"*.awdev.ca", -"*.advisor.ws", -"b-data.io", -"backplaneapp.io", -"balena-devices.com", -"app.banzaicloud.io", -"betainabox.com", -"bnr.la", -"blackbaudcdn.net", -"boomla.net", -"boxfuse.io", -"square7.ch", -"bplaced.com", -"bplaced.de", -"square7.de", -"bplaced.net", -"square7.net", -"browsersafetymark.io", -"uk0.bigv.io", -"dh.bytemark.co.uk", -"vm.bytemark.co.uk", -"mycd.eu", -"carrd.co", -"crd.co", -"uwu.ai", -"ae.org", -"ar.com", -"br.com", -"cn.com", -"com.de", -"com.se", -"de.com", -"eu.com", -"gb.com", -"gb.net", -"hu.com", -"hu.net", -"jp.net", -"jpn.com", -"kr.com", -"mex.com", -"no.com", -"qc.com", -"ru.com", -"sa.com", -"se.net", -"uk.com", -"uk.net", -"us.com", -"uy.com", -"za.bz", -"za.com", -"africa.com", -"gr.com", -"in.net", -"us.org", -"co.com", -"c.la", -"certmgr.org", -"xenapponazure.com", -"discourse.group", -"virtueeldomein.nl", -"cleverapps.io", -"*.lcl.dev", -"*.stg.dev", -"c66.me", -"cloud66.ws", -"cloud66.zone", -"jdevcloud.com", -"wpdevcloud.com", -"cloudaccess.host", -"freesite.host", -"cloudaccess.net", -"cloudcontrolled.com", -"cloudcontrolapp.com", -"cloudera.site", -"trycloudflare.com", -"workers.dev", -"wnext.app", -"co.ca", -"*.otap.co", -"co.cz", -"c.cdn77.org", -"cdn77-ssl.net", -"r.cdn77.net", -"rsc.cdn77.org", -"ssl.origin.cdn77-secure.org", -"cloudns.asia", -"cloudns.biz", -"cloudns.club", -"cloudns.cc", -"cloudns.eu", -"cloudns.in", -"cloudns.info", -"cloudns.org", -"cloudns.pro", -"cloudns.pw", -"cloudns.us", -"cloudeity.net", -"cnpy.gdn", -"co.nl", -"co.no", -"webhosting.be", -"hosting-cluster.nl", -"dyn.cosidns.de", -"dynamisches-dns.de", -"dnsupdater.de", -"internet-dns.de", -"l-o-g-i-n.de", -"dynamic-dns.info", -"feste-ip.net", -"knx-server.net", -"static-access.net", -"realm.cz", -"*.cryptonomic.net", -"cupcake.is", -"cyon.link", -"cyon.site", -"daplie.me", -"localhost.daplie.me", -"dattolocal.com", -"dattorelay.com", -"dattoweb.com", -"mydatto.com", -"dattolocal.net", -"mydatto.net", -"biz.dk", -"co.dk", -"firm.dk", -"reg.dk", -"store.dk", -"*.dapps.earth", -"*.bzz.dapps.earth", -"debian.net", -"dedyn.io", -"dnshome.de", -"online.th", -"shop.th", -"drayddns.com", -"dreamhosters.com", -"mydrobo.com", -"drud.io", -"drud.us", -"duckdns.org", -"dy.fi", -"tunk.org", -"dyndns-at-home.com", -"dyndns-at-work.com", -"dyndns-blog.com", -"dyndns-free.com", -"dyndns-home.com", -"dyndns-ip.com", -"dyndns-mail.com", -"dyndns-office.com", -"dyndns-pics.com", -"dyndns-remote.com", -"dyndns-server.com", -"dyndns-web.com", -"dyndns-wiki.com", -"dyndns-work.com", -"dyndns.biz", -"dyndns.info", -"dyndns.org", -"dyndns.tv", -"at-band-camp.net", -"ath.cx", -"barrel-of-knowledge.info", -"barrell-of-knowledge.info", -"better-than.tv", -"blogdns.com", -"blogdns.net", -"blogdns.org", -"blogsite.org", -"boldlygoingnowhere.org", -"broke-it.net", -"buyshouses.net", -"cechire.com", -"dnsalias.com", -"dnsalias.net", -"dnsalias.org", -"dnsdojo.com", -"dnsdojo.net", -"dnsdojo.org", -"does-it.net", -"doesntexist.com", -"doesntexist.org", -"dontexist.com", -"dontexist.net", -"dontexist.org", -"doomdns.com", -"doomdns.org", -"dvrdns.org", -"dyn-o-saur.com", -"dynalias.com", -"dynalias.net", -"dynalias.org", -"dynathome.net", -"dyndns.ws", -"endofinternet.net", -"endofinternet.org", -"endoftheinternet.org", -"est-a-la-maison.com", -"est-a-la-masion.com", -"est-le-patron.com", -"est-mon-blogueur.com", -"for-better.biz", -"for-more.biz", -"for-our.info", -"for-some.biz", -"for-the.biz", -"forgot.her.name", -"forgot.his.name", -"from-ak.com", -"from-al.com", -"from-ar.com", -"from-az.net", -"from-ca.com", -"from-co.net", -"from-ct.com", -"from-dc.com", -"from-de.com", -"from-fl.com", -"from-ga.com", -"from-hi.com", -"from-ia.com", -"from-id.com", -"from-il.com", -"from-in.com", -"from-ks.com", -"from-ky.com", -"from-la.net", -"from-ma.com", -"from-md.com", -"from-me.org", -"from-mi.com", -"from-mn.com", -"from-mo.com", -"from-ms.com", -"from-mt.com", -"from-nc.com", -"from-nd.com", -"from-ne.com", -"from-nh.com", -"from-nj.com", -"from-nm.com", -"from-nv.com", -"from-ny.net", -"from-oh.com", -"from-ok.com", -"from-or.com", -"from-pa.com", -"from-pr.com", -"from-ri.com", -"from-sc.com", -"from-sd.com", -"from-tn.com", -"from-tx.com", -"from-ut.com", -"from-va.com", -"from-vt.com", -"from-wa.com", -"from-wi.com", -"from-wv.com", -"from-wy.com", -"ftpaccess.cc", -"fuettertdasnetz.de", -"game-host.org", -"game-server.cc", -"getmyip.com", -"gets-it.net", -"go.dyndns.org", -"gotdns.com", -"gotdns.org", -"groks-the.info", -"groks-this.info", -"ham-radio-op.net", -"here-for-more.info", -"hobby-site.com", -"hobby-site.org", -"home.dyndns.org", -"homedns.org", -"homeftp.net", -"homeftp.org", -"homeip.net", -"homelinux.com", -"homelinux.net", -"homelinux.org", -"homeunix.com", -"homeunix.net", -"homeunix.org", -"iamallama.com", -"in-the-band.net", -"is-a-anarchist.com", -"is-a-blogger.com", -"is-a-bookkeeper.com", -"is-a-bruinsfan.org", -"is-a-bulls-fan.com", -"is-a-candidate.org", -"is-a-caterer.com", -"is-a-celticsfan.org", -"is-a-chef.com", -"is-a-chef.net", -"is-a-chef.org", -"is-a-conservative.com", -"is-a-cpa.com", -"is-a-cubicle-slave.com", -"is-a-democrat.com", -"is-a-designer.com", -"is-a-doctor.com", -"is-a-financialadvisor.com", -"is-a-geek.com", -"is-a-geek.net", -"is-a-geek.org", -"is-a-green.com", -"is-a-guru.com", -"is-a-hard-worker.com", -"is-a-hunter.com", -"is-a-knight.org", -"is-a-landscaper.com", -"is-a-lawyer.com", -"is-a-liberal.com", -"is-a-libertarian.com", -"is-a-linux-user.org", -"is-a-llama.com", -"is-a-musician.com", -"is-a-nascarfan.com", -"is-a-nurse.com", -"is-a-painter.com", -"is-a-patsfan.org", -"is-a-personaltrainer.com", -"is-a-photographer.com", -"is-a-player.com", -"is-a-republican.com", -"is-a-rockstar.com", -"is-a-socialist.com", -"is-a-soxfan.org", -"is-a-student.com", -"is-a-teacher.com", -"is-a-techie.com", -"is-a-therapist.com", -"is-an-accountant.com", -"is-an-actor.com", -"is-an-actress.com", -"is-an-anarchist.com", -"is-an-artist.com", -"is-an-engineer.com", -"is-an-entertainer.com", -"is-by.us", -"is-certified.com", -"is-found.org", -"is-gone.com", -"is-into-anime.com", -"is-into-cars.com", -"is-into-cartoons.com", -"is-into-games.com", -"is-leet.com", -"is-lost.org", -"is-not-certified.com", -"is-saved.org", -"is-slick.com", -"is-uberleet.com", -"is-very-bad.org", -"is-very-evil.org", -"is-very-good.org", -"is-very-nice.org", -"is-very-sweet.org", -"is-with-theband.com", -"isa-geek.com", -"isa-geek.net", -"isa-geek.org", -"isa-hockeynut.com", -"issmarterthanyou.com", -"isteingeek.de", -"istmein.de", -"kicks-ass.net", -"kicks-ass.org", -"knowsitall.info", -"land-4-sale.us", -"lebtimnetz.de", -"leitungsen.de", -"likes-pie.com", -"likescandy.com", -"merseine.nu", -"mine.nu", -"misconfused.org", -"mypets.ws", -"myphotos.cc", -"neat-url.com", -"office-on-the.net", -"on-the-web.tv", -"podzone.net", -"podzone.org", -"readmyblog.org", -"saves-the-whales.com", -"scrapper-site.net", -"scrapping.cc", -"selfip.biz", -"selfip.com", -"selfip.info", -"selfip.net", -"selfip.org", -"sells-for-less.com", -"sells-for-u.com", -"sells-it.net", -"sellsyourhome.org", -"servebbs.com", -"servebbs.net", -"servebbs.org", -"serveftp.net", -"serveftp.org", -"servegame.org", -"shacknet.nu", -"simple-url.com", -"space-to-rent.com", -"stuff-4-sale.org", -"stuff-4-sale.us", -"teaches-yoga.com", -"thruhere.net", -"traeumtgerade.de", -"webhop.biz", -"webhop.info", -"webhop.net", -"webhop.org", -"worse-than.tv", -"writesthisblog.com", -"ddnss.de", -"dyn.ddnss.de", -"dyndns.ddnss.de", -"dyndns1.de", -"dyn-ip24.de", -"home-webserver.de", -"dyn.home-webserver.de", -"myhome-server.de", -"ddnss.org", -"definima.net", -"definima.io", -"bci.dnstrace.pro", -"ddnsfree.com", -"ddnsgeek.com", -"giize.com", -"gleeze.com", -"kozow.com", -"loseyourip.com", -"ooguy.com", -"theworkpc.com", -"casacam.net", -"dynu.net", -"accesscam.org", -"camdvr.org", -"freeddns.org", -"mywire.org", -"webredirect.org", -"myddns.rocks", -"blogsite.xyz", -"dynv6.net", -"e4.cz", -"mytuleap.com", -"onred.one", -"staging.onred.one", -"enonic.io", -"customer.enonic.io", -"eu.org", -"al.eu.org", -"asso.eu.org", -"at.eu.org", -"au.eu.org", -"be.eu.org", -"bg.eu.org", -"ca.eu.org", -"cd.eu.org", -"ch.eu.org", -"cn.eu.org", -"cy.eu.org", -"cz.eu.org", -"de.eu.org", -"dk.eu.org", -"edu.eu.org", -"ee.eu.org", -"es.eu.org", -"fi.eu.org", -"fr.eu.org", -"gr.eu.org", -"hr.eu.org", -"hu.eu.org", -"ie.eu.org", -"il.eu.org", -"in.eu.org", -"int.eu.org", -"is.eu.org", -"it.eu.org", -"jp.eu.org", -"kr.eu.org", -"lt.eu.org", -"lu.eu.org", -"lv.eu.org", -"mc.eu.org", -"me.eu.org", -"mk.eu.org", -"mt.eu.org", -"my.eu.org", -"net.eu.org", -"ng.eu.org", -"nl.eu.org", -"no.eu.org", -"nz.eu.org", -"paris.eu.org", -"pl.eu.org", -"pt.eu.org", -"q-a.eu.org", -"ro.eu.org", -"ru.eu.org", -"se.eu.org", -"si.eu.org", -"sk.eu.org", -"tr.eu.org", -"uk.eu.org", -"us.eu.org", -"eu-1.evennode.com", -"eu-2.evennode.com", -"eu-3.evennode.com", -"eu-4.evennode.com", -"us-1.evennode.com", -"us-2.evennode.com", -"us-3.evennode.com", -"us-4.evennode.com", -"twmail.cc", -"twmail.net", -"twmail.org", -"mymailer.com.tw", -"url.tw", -"apps.fbsbx.com", -"ru.net", -"adygeya.ru", -"bashkiria.ru", -"bir.ru", -"cbg.ru", -"com.ru", -"dagestan.ru", -"grozny.ru", -"kalmykia.ru", -"kustanai.ru", -"marine.ru", -"mordovia.ru", -"msk.ru", -"mytis.ru", -"nalchik.ru", -"nov.ru", -"pyatigorsk.ru", -"spb.ru", -"vladikavkaz.ru", -"vladimir.ru", -"abkhazia.su", -"adygeya.su", -"aktyubinsk.su", -"arkhangelsk.su", -"armenia.su", -"ashgabad.su", -"azerbaijan.su", -"balashov.su", -"bashkiria.su", -"bryansk.su", -"bukhara.su", -"chimkent.su", -"dagestan.su", -"east-kazakhstan.su", -"exnet.su", -"georgia.su", -"grozny.su", -"ivanovo.su", -"jambyl.su", -"kalmykia.su", -"kaluga.su", -"karacol.su", -"karaganda.su", -"karelia.su", -"khakassia.su", -"krasnodar.su", -"kurgan.su", -"kustanai.su", -"lenug.su", -"mangyshlak.su", -"mordovia.su", -"msk.su", -"murmansk.su", -"nalchik.su", -"navoi.su", -"north-kazakhstan.su", -"nov.su", -"obninsk.su", -"penza.su", -"pokrovsk.su", -"sochi.su", -"spb.su", -"tashkent.su", -"termez.su", -"togliatti.su", -"troitsk.su", -"tselinograd.su", -"tula.su", -"tuva.su", -"vladikavkaz.su", -"vladimir.su", -"vologda.su", -"channelsdvr.net", -"fastly-terrarium.com", -"fastlylb.net", -"map.fastlylb.net", -"freetls.fastly.net", -"map.fastly.net", -"a.prod.fastly.net", -"global.prod.fastly.net", -"a.ssl.fastly.net", -"b.ssl.fastly.net", -"global.ssl.fastly.net", -"fastpanel.direct", -"fastvps-server.com", -"fhapp.xyz", -"fedorainfracloud.org", -"fedorapeople.org", -"cloud.fedoraproject.org", -"app.os.fedoraproject.org", -"app.os.stg.fedoraproject.org", -"mydobiss.com", -"filegear.me", -"filegear-au.me", -"filegear-de.me", -"filegear-gb.me", -"filegear-ie.me", -"filegear-jp.me", -"filegear-sg.me", -"firebaseapp.com", -"flynnhub.com", -"flynnhosting.net", -"freebox-os.com", -"freeboxos.com", -"fbx-os.fr", -"fbxos.fr", -"freebox-os.fr", -"freeboxos.fr", -"freedesktop.org", -"*.futurecms.at", -"*.ex.futurecms.at", -"*.in.futurecms.at", -"futurehosting.at", -"futuremailing.at", -"*.ex.ortsinfo.at", -"*.kunden.ortsinfo.at", -"*.statics.cloud", -"service.gov.uk", -"gehirn.ne.jp", -"usercontent.jp", -"lab.ms", -"github.io", -"githubusercontent.com", -"gitlab.io", -"glitch.me", -"cloudapps.digital", -"london.cloudapps.digital", -"homeoffice.gov.uk", -"ro.im", -"shop.ro", -"goip.de", -"run.app", -"a.run.app", -"web.app", -"*.0emm.com", -"appspot.com", -"blogspot.ae", -"blogspot.al", -"blogspot.am", -"blogspot.ba", -"blogspot.be", -"blogspot.bg", -"blogspot.bj", -"blogspot.ca", -"blogspot.cf", -"blogspot.ch", -"blogspot.cl", -"blogspot.co.at", -"blogspot.co.id", -"blogspot.co.il", -"blogspot.co.ke", -"blogspot.co.nz", -"blogspot.co.uk", -"blogspot.co.za", -"blogspot.com", -"blogspot.com.ar", -"blogspot.com.au", -"blogspot.com.br", -"blogspot.com.by", -"blogspot.com.co", -"blogspot.com.cy", -"blogspot.com.ee", -"blogspot.com.eg", -"blogspot.com.es", -"blogspot.com.mt", -"blogspot.com.ng", -"blogspot.com.tr", -"blogspot.com.uy", -"blogspot.cv", -"blogspot.cz", -"blogspot.de", -"blogspot.dk", -"blogspot.fi", -"blogspot.fr", -"blogspot.gr", -"blogspot.hk", -"blogspot.hr", -"blogspot.hu", -"blogspot.ie", -"blogspot.in", -"blogspot.is", -"blogspot.it", -"blogspot.jp", -"blogspot.kr", -"blogspot.li", -"blogspot.lt", -"blogspot.lu", -"blogspot.md", -"blogspot.mk", -"blogspot.mr", -"blogspot.mx", -"blogspot.my", -"blogspot.nl", -"blogspot.no", -"blogspot.pe", -"blogspot.pt", -"blogspot.qa", -"blogspot.re", -"blogspot.ro", -"blogspot.rs", -"blogspot.ru", -"blogspot.se", -"blogspot.sg", -"blogspot.si", -"blogspot.sk", -"blogspot.sn", -"blogspot.td", -"blogspot.tw", -"blogspot.ug", -"blogspot.vn", -"cloudfunctions.net", -"cloud.goog", -"codespot.com", -"googleapis.com", -"googlecode.com", -"pagespeedmobilizer.com", -"publishproxy.com", -"withgoogle.com", -"withyoutube.com", -"fin.ci", -"free.hr", -"caa.li", -"ua.rs", -"conf.se", -"hs.zone", -"hs.run", -"hashbang.sh", -"hasura.app", -"hasura-app.io", -"hepforge.org", -"herokuapp.com", -"herokussl.com", -"myravendb.com", -"ravendb.community", -"ravendb.me", -"development.run", -"ravendb.run", -"bpl.biz", -"orx.biz", -"ng.city", -"biz.gl", -"ng.ink", -"col.ng", -"firm.ng", -"gen.ng", -"ltd.ng", -"ng.school", -"sch.so", -"häkkinen.fi", -"*.moonscale.io", -"moonscale.net", -"iki.fi", -"dyn-berlin.de", -"in-berlin.de", -"in-brb.de", -"in-butter.de", -"in-dsl.de", -"in-dsl.net", -"in-dsl.org", -"in-vpn.de", -"in-vpn.net", -"in-vpn.org", -"biz.at", -"info.at", -"info.cx", -"ac.leg.br", -"al.leg.br", -"am.leg.br", -"ap.leg.br", -"ba.leg.br", -"ce.leg.br", -"df.leg.br", -"es.leg.br", -"go.leg.br", -"ma.leg.br", -"mg.leg.br", -"ms.leg.br", -"mt.leg.br", -"pa.leg.br", -"pb.leg.br", -"pe.leg.br", -"pi.leg.br", -"pr.leg.br", -"rj.leg.br", -"rn.leg.br", -"ro.leg.br", -"rr.leg.br", -"rs.leg.br", -"sc.leg.br", -"se.leg.br", -"sp.leg.br", -"to.leg.br", -"pixolino.com", -"ipifony.net", -"mein-iserv.de", -"test-iserv.de", -"iserv.dev", -"iobb.net", -"myjino.ru", -"*.hosting.myjino.ru", -"*.landing.myjino.ru", -"*.spectrum.myjino.ru", -"*.vps.myjino.ru", -"*.triton.zone", -"*.cns.joyent.com", -"js.org", -"kaas.gg", -"khplay.nl", -"keymachine.de", -"kinghost.net", -"uni5.net", -"knightpoint.systems", -"co.krd", -"edu.krd", -"git-repos.de", -"lcube-server.de", -"svn-repos.de", -"leadpages.co", -"lpages.co", -"lpusercontent.com", -"lelux.site", -"co.business", -"co.education", -"co.events", -"co.financial", -"co.network", -"co.place", -"co.technology", -"app.lmpm.com", -"linkitools.space", -"linkyard.cloud", -"linkyard-cloud.ch", -"members.linode.com", -"nodebalancer.linode.com", -"we.bs", -"loginline.app", -"loginline.dev", -"loginline.io", -"loginline.services", -"loginline.site", -"krasnik.pl", -"leczna.pl", -"lubartow.pl", -"lublin.pl", -"poniatowa.pl", -"swidnik.pl", -"uklugs.org", -"glug.org.uk", -"lug.org.uk", -"lugs.org.uk", -"barsy.bg", -"barsy.co.uk", -"barsyonline.co.uk", -"barsycenter.com", -"barsyonline.com", -"barsy.club", -"barsy.de", -"barsy.eu", -"barsy.in", -"barsy.info", -"barsy.io", -"barsy.me", -"barsy.menu", -"barsy.mobi", -"barsy.net", -"barsy.online", -"barsy.org", -"barsy.pro", -"barsy.pub", -"barsy.shop", -"barsy.site", -"barsy.support", -"barsy.uk", -"*.magentosite.cloud", -"mayfirst.info", -"mayfirst.org", -"hb.cldmail.ru", -"miniserver.com", -"memset.net", -"cloud.metacentrum.cz", -"custom.metacentrum.cz", -"flt.cloud.muni.cz", -"usr.cloud.muni.cz", -"meteorapp.com", -"eu.meteorapp.com", -"co.pl", -"azurecontainer.io", -"azurewebsites.net", -"azure-mobile.net", -"cloudapp.net", -"mozilla-iot.org", -"bmoattachments.org", -"net.ru", -"org.ru", -"pp.ru", -"ui.nabu.casa", -"pony.club", -"of.fashion", -"on.fashion", -"of.football", -"in.london", -"of.london", -"for.men", -"and.mom", -"for.mom", -"for.one", -"for.sale", -"of.work", -"to.work", -"nctu.me", -"bitballoon.com", -"netlify.com", -"4u.com", -"ngrok.io", -"nh-serv.co.uk", -"nfshost.com", -"dnsking.ch", -"mypi.co", -"n4t.co", -"001www.com", -"ddnslive.com", -"myiphost.com", -"forumz.info", -"16-b.it", -"32-b.it", -"64-b.it", -"soundcast.me", -"tcp4.me", -"dnsup.net", -"hicam.net", -"now-dns.net", -"ownip.net", -"vpndns.net", -"dynserv.org", -"now-dns.org", -"x443.pw", -"now-dns.top", -"ntdll.top", -"freeddns.us", -"crafting.xyz", -"zapto.xyz", -"nsupdate.info", -"nerdpol.ovh", -"blogsyte.com", -"brasilia.me", -"cable-modem.org", -"ciscofreak.com", -"collegefan.org", -"couchpotatofries.org", -"damnserver.com", -"ddns.me", -"ditchyourip.com", -"dnsfor.me", -"dnsiskinky.com", -"dvrcam.info", -"dynns.com", -"eating-organic.net", -"fantasyleague.cc", -"geekgalaxy.com", -"golffan.us", -"health-carereform.com", -"homesecuritymac.com", -"homesecuritypc.com", -"hopto.me", -"ilovecollege.info", -"loginto.me", -"mlbfan.org", -"mmafan.biz", -"myactivedirectory.com", -"mydissent.net", -"myeffect.net", -"mymediapc.net", -"mypsx.net", -"mysecuritycamera.com", -"mysecuritycamera.net", -"mysecuritycamera.org", -"net-freaks.com", -"nflfan.org", -"nhlfan.net", -"no-ip.ca", -"no-ip.co.uk", -"no-ip.net", -"noip.us", -"onthewifi.com", -"pgafan.net", -"point2this.com", -"pointto.us", -"privatizehealthinsurance.net", -"quicksytes.com", -"read-books.org", -"securitytactics.com", -"serveexchange.com", -"servehumour.com", -"servep2p.com", -"servesarcasm.com", -"stufftoread.com", -"ufcfan.org", -"unusualperson.com", -"workisboring.com", -"3utilities.com", -"bounceme.net", -"ddns.net", -"ddnsking.com", -"gotdns.ch", -"hopto.org", -"myftp.biz", -"myftp.org", -"myvnc.com", -"no-ip.biz", -"no-ip.info", -"no-ip.org", -"noip.me", -"redirectme.net", -"servebeer.com", -"serveblog.net", -"servecounterstrike.com", -"serveftp.com", -"servegame.com", -"servehalflife.com", -"servehttp.com", -"serveirc.com", -"serveminecraft.net", -"servemp3.com", -"servepics.com", -"servequake.com", -"sytes.net", -"webhop.me", -"zapto.org", -"stage.nodeart.io", -"nodum.co", -"nodum.io", -"pcloud.host", -"nyc.mn", -"nom.ae", -"nom.af", -"nom.ai", -"nom.al", -"nym.by", -"nym.bz", -"nom.cl", -"nym.ec", -"nom.gd", -"nom.ge", -"nom.gl", -"nym.gr", -"nom.gt", -"nym.gy", -"nym.hk", -"nom.hn", -"nym.ie", -"nom.im", -"nom.ke", -"nym.kz", -"nym.la", -"nym.lc", -"nom.li", -"nym.li", -"nym.lt", -"nym.lu", -"nym.me", -"nom.mk", -"nym.mn", -"nym.mx", -"nom.nu", -"nym.nz", -"nym.pe", -"nym.pt", -"nom.pw", -"nom.qa", -"nym.ro", -"nom.rs", -"nom.si", -"nym.sk", -"nom.st", -"nym.su", -"nym.sx", -"nom.tj", -"nym.tw", -"nom.ug", -"nom.uy", -"nom.vc", -"nom.vg", -"cya.gg", -"cloudycluster.net", -"nid.io", -"opencraft.hosting", -"operaunite.com", -"outsystemscloud.com", -"ownprovider.com", -"own.pm", -"ox.rs", -"oy.lc", -"pgfog.com", -"pagefrontapp.com", -"art.pl", -"gliwice.pl", -"krakow.pl", -"poznan.pl", -"wroc.pl", -"zakopane.pl", -"pantheonsite.io", -"gotpantheon.com", -"mypep.link", -"on-web.fr", -"*.platform.sh", -"*.platformsh.site", -"dyn53.io", -"co.bn", -"xen.prgmr.com", -"priv.at", -"prvcy.page", -"*.dweb.link", -"protonet.io", -"chirurgiens-dentistes-en-france.fr", -"byen.site", -"pubtls.org", -"qualifioapp.com", -"instantcloud.cn", -"ras.ru", -"qa2.com", -"dev-myqnapcloud.com", -"alpha-myqnapcloud.com", -"myqnapcloud.com", -"*.quipelements.com", -"vapor.cloud", -"vaporcloud.io", -"rackmaze.com", -"rackmaze.net", -"*.on-rancher.cloud", -"*.on-rio.io", -"readthedocs.io", -"rhcloud.com", -"app.render.com", -"onrender.com", -"repl.co", -"repl.run", -"resindevice.io", -"devices.resinstaging.io", -"hzc.io", -"wellbeingzone.eu", -"ptplus.fit", -"wellbeingzone.co.uk", -"git-pages.rit.edu", -"sandcats.io", -"logoip.de", -"logoip.com", -"schokokeks.net", -"scrysec.com", -"firewall-gateway.com", -"firewall-gateway.de", -"my-gateway.de", -"my-router.de", -"spdns.de", -"spdns.eu", -"firewall-gateway.net", -"my-firewall.org", -"myfirewall.org", -"spdns.org", -"biz.ua", -"co.ua", -"pp.ua", -"shiftedit.io", -"myshopblocks.com", -"shopitsite.com", -"mo-siemens.io", -"1kapp.com", -"appchizi.com", -"applinzi.com", -"sinaapp.com", -"vipsinaapp.com", -"siteleaf.net", -"bounty-full.com", -"alpha.bounty-full.com", -"beta.bounty-full.com", -"stackhero-network.com", -"static.land", -"dev.static.land", -"sites.static.land", -"apps.lair.io", -"*.stolos.io", -"spacekit.io", -"customer.speedpartner.de", -"api.stdlib.com", -"storj.farm", -"utwente.io", -"soc.srcf.net", -"user.srcf.net", -"temp-dns.com", -"applicationcloud.io", -"scapp.io", -"*.s5y.io", -"*.sensiosite.cloud", -"syncloud.it", -"diskstation.me", -"dscloud.biz", -"dscloud.me", -"dscloud.mobi", -"dsmynas.com", -"dsmynas.net", -"dsmynas.org", -"familyds.com", -"familyds.net", -"familyds.org", -"i234.me", -"myds.me", -"synology.me", -"vpnplus.to", -"direct.quickconnect.to", -"taifun-dns.de", -"gda.pl", -"gdansk.pl", -"gdynia.pl", -"med.pl", -"sopot.pl", -"edugit.org", -"telebit.app", -"telebit.io", -"*.telebit.xyz", -"gwiddle.co.uk", -"thingdustdata.com", -"cust.dev.thingdust.io", -"cust.disrec.thingdust.io", -"cust.prod.thingdust.io", -"cust.testing.thingdust.io", -"arvo.network", -"azimuth.network", -"bloxcms.com", -"townnews-staging.com", -"12hp.at", -"2ix.at", -"4lima.at", -"lima-city.at", -"12hp.ch", -"2ix.ch", -"4lima.ch", -"lima-city.ch", -"trafficplex.cloud", -"de.cool", -"12hp.de", -"2ix.de", -"4lima.de", -"lima-city.de", -"1337.pictures", -"clan.rip", -"lima-city.rocks", -"webspace.rocks", -"lima.zone", -"*.transurl.be", -"*.transurl.eu", -"*.transurl.nl", -"tuxfamily.org", -"dd-dns.de", -"diskstation.eu", -"diskstation.org", -"dray-dns.de", -"draydns.de", -"dyn-vpn.de", -"dynvpn.de", -"mein-vigor.de", -"my-vigor.de", -"my-wan.de", -"syno-ds.de", -"synology-diskstation.de", -"synology-ds.de", -"uber.space", -"*.uberspace.de", -"hk.com", -"hk.org", -"ltd.hk", -"inc.hk", -"virtualuser.de", -"virtual-user.de", -"lib.de.us", -"2038.io", -"router.management", -"v-info.info", -"voorloper.cloud", -"wafflecell.com", -"*.webhare.dev", -"wedeploy.io", -"wedeploy.me", -"wedeploy.sh", -"remotewd.com", -"wmflabs.org", -"half.host", -"xnbay.com", -"u2.xnbay.com", -"u2-local.xnbay.com", -"cistron.nl", -"demon.nl", -"xs4all.space", -"yandexcloud.net", -"storage.yandexcloud.net", -"website.yandexcloud.net", -"official.academy", -"yolasite.com", -"ybo.faith", -"yombo.me", -"homelink.one", -"ybo.party", -"ybo.review", -"ybo.science", -"ybo.trade", -"nohost.me", -"noho.st", -"za.net", -"za.org", -"now.sh", -"bss.design", -"basicserver.io", -"virtualserver.io", -"site.builder.nu", -"enterprisecloud.nu", -"zone.id" -] -},{}],1457:[function(require,module,exports){ -/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ -'use strict'; - - -var Punycode = require('punycode'); - - -var internals = {}; - - -// -// Read rules from file. -// -internals.rules = require('./data/rules.json').map(function (rule) { - - return { - rule: rule, - suffix: rule.replace(/^(\*\.|\!)/, ''), - punySuffix: -1, - wildcard: rule.charAt(0) === '*', - exception: rule.charAt(0) === '!' - }; -}); - - -// -// Check is given string ends with `suffix`. -// -internals.endsWith = function (str, suffix) { - - return str.indexOf(suffix, str.length - suffix.length) !== -1; -}; - - -// -// Find rule for a given domain. -// -internals.findRule = function (domain) { - - var punyDomain = Punycode.toASCII(domain); - return internals.rules.reduce(function (memo, rule) { - - if (rule.punySuffix === -1){ - rule.punySuffix = Punycode.toASCII(rule.suffix); - } - if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { - return memo; - } - // This has been commented out as it never seems to run. This is because - // sub tlds always appear after their parents and we never find a shorter - // match. - //if (memo) { - // var memoSuffix = Punycode.toASCII(memo.suffix); - // if (memoSuffix.length >= punySuffix.length) { - // return memo; - // } - //} - return rule; - }, null); -}; - - -// -// Error codes and messages. -// -exports.errorCodes = { - DOMAIN_TOO_SHORT: 'Domain name too short.', - DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', - LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', - LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', - LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', - LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', - LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' -}; - - -// -// Validate domain name and throw if not valid. -// -// From wikipedia: -// -// Hostnames are composed of series of labels concatenated with dots, as are all -// domain names. Each label must be between 1 and 63 characters long, and the -// entire hostname (including the delimiting dots) has a maximum of 255 chars. -// -// Allowed chars: -// -// * `a-z` -// * `0-9` -// * `-` but not as a starting or ending character -// * `.` as a separator for the textual portions of a domain name -// -// * http://en.wikipedia.org/wiki/Domain_name -// * http://en.wikipedia.org/wiki/Hostname -// -internals.validate = function (input) { - - // Before we can validate we need to take care of IDNs with unicode chars. - var ascii = Punycode.toASCII(input); - - if (ascii.length < 1) { - return 'DOMAIN_TOO_SHORT'; - } - if (ascii.length > 255) { - return 'DOMAIN_TOO_LONG'; - } - - // Check each part's length and allowed chars. - var labels = ascii.split('.'); - var label; - - for (var i = 0; i < labels.length; ++i) { - label = labels[i]; - if (!label.length) { - return 'LABEL_TOO_SHORT'; - } - if (label.length > 63) { - return 'LABEL_TOO_LONG'; - } - if (label.charAt(0) === '-') { - return 'LABEL_STARTS_WITH_DASH'; - } - if (label.charAt(label.length - 1) === '-') { - return 'LABEL_ENDS_WITH_DASH'; - } - if (!/^[a-z0-9\-]+$/.test(label)) { - return 'LABEL_INVALID_CHARS'; - } - } -}; - - -// -// Public API -// - - -// -// Parse domain. -// -exports.parse = function (input) { - - if (typeof input !== 'string') { - throw new TypeError('Domain name must be a string.'); - } - - // Force domain to lowercase. - var domain = input.slice(0).toLowerCase(); - - // Handle FQDN. - // TODO: Simply remove trailing dot? - if (domain.charAt(domain.length - 1) === '.') { - domain = domain.slice(0, domain.length - 1); - } - - // Validate and sanitise input. - var error = internals.validate(domain); - if (error) { - return { - input: input, - error: { - message: exports.errorCodes[error], - code: error - } - }; - } - - var parsed = { - input: input, - tld: null, - sld: null, - domain: null, - subdomain: null, - listed: false - }; - - var domainParts = domain.split('.'); - - // Non-Internet TLD - if (domainParts[domainParts.length - 1] === 'local') { - return parsed; - } - - var handlePunycode = function () { - - if (!/xn--/.test(domain)) { - return parsed; - } - if (parsed.domain) { - parsed.domain = Punycode.toASCII(parsed.domain); - } - if (parsed.subdomain) { - parsed.subdomain = Punycode.toASCII(parsed.subdomain); - } - return parsed; - }; - - var rule = internals.findRule(domain); - - // Unlisted tld. - if (!rule) { - if (domainParts.length < 2) { - return parsed; - } - parsed.tld = domainParts.pop(); - parsed.sld = domainParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); - if (domainParts.length) { - parsed.subdomain = domainParts.pop(); - } - return handlePunycode(); - } - - // At this point we know the public suffix is listed. - parsed.listed = true; - - var tldParts = rule.suffix.split('.'); - var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); - - if (rule.exception) { - privateParts.push(tldParts.shift()); - } - - parsed.tld = tldParts.join('.'); - - if (!privateParts.length) { - return handlePunycode(); - } - - if (rule.wildcard) { - tldParts.unshift(privateParts.pop()); - parsed.tld = tldParts.join('.'); - } - - if (!privateParts.length) { - return handlePunycode(); - } - - parsed.sld = privateParts.pop(); - parsed.domain = [parsed.sld, parsed.tld].join('.'); - - if (privateParts.length) { - parsed.subdomain = privateParts.join('.'); - } - - return handlePunycode(); -}; - - -// -// Get domain. -// -exports.get = function (domain) { - - if (!domain) { - return null; - } - return exports.parse(domain).domain || null; -}; - - -// -// Check whether domain belongs to a known public suffix. -// -exports.isValid = function (domain) { - - var parsed = exports.parse(domain); - return Boolean(parsed.domain && parsed.listed); -}; - -},{"./data/rules.json":1456,"punycode":1538}],1458:[function(require,module,exports){ +},{}],1276:[function(require,module,exports){ exports.publicEncrypt = require('./publicEncrypt') exports.privateDecrypt = require('./privateDecrypt') @@ -196595,7 +146387,7 @@ exports.publicDecrypt = function publicDecrypt (key, buf) { return exports.privateDecrypt(key, buf, true) } -},{"./privateDecrypt":1460,"./publicEncrypt":1461}],1459:[function(require,module,exports){ +},{"./privateDecrypt":1278,"./publicEncrypt":1279}],1277:[function(require,module,exports){ var createHash = require('create-hash') var Buffer = require('safe-buffer').Buffer @@ -196616,7 +146408,7 @@ function i2ops (c) { return out } -},{"create-hash":232,"safe-buffer":1593}],1460:[function(require,module,exports){ +},{"create-hash":193,"safe-buffer":1371}],1278:[function(require,module,exports){ var parseKeys = require('parse-asn1') var mgf = require('./mgf') var xor = require('./xor') @@ -196723,7 +146515,7 @@ function compare (a, b) { return dif } -},{"./mgf":1459,"./withPublic":1462,"./xor":1463,"bn.js":171,"browserify-rsa":203,"create-hash":232,"parse-asn1":1421,"safe-buffer":1593}],1461:[function(require,module,exports){ +},{"./mgf":1277,"./withPublic":1280,"./xor":1281,"bn.js":135,"browserify-rsa":167,"create-hash":193,"parse-asn1":1243,"safe-buffer":1371}],1279:[function(require,module,exports){ var parseKeys = require('parse-asn1') var randomBytes = require('randombytes') var createHash = require('create-hash') @@ -196813,7 +146605,7 @@ function nonZero (len) { return out } -},{"./mgf":1459,"./withPublic":1462,"./xor":1463,"bn.js":171,"browserify-rsa":203,"create-hash":232,"parse-asn1":1421,"randombytes":1552,"safe-buffer":1593}],1462:[function(require,module,exports){ +},{"./mgf":1277,"./withPublic":1280,"./xor":1281,"bn.js":135,"browserify-rsa":167,"create-hash":193,"parse-asn1":1243,"randombytes":1366,"safe-buffer":1371}],1280:[function(require,module,exports){ var BN = require('bn.js') var Buffer = require('safe-buffer').Buffer @@ -196827,7 +146619,7 @@ function withPublic (paddedMsg, key) { module.exports = withPublic -},{"bn.js":171,"safe-buffer":1593}],1463:[function(require,module,exports){ +},{"bn.js":135,"safe-buffer":1371}],1281:[function(require,module,exports){ module.exports = function xor (a, b) { var len = a.length var i = -1 @@ -196837,7 +146629,7 @@ module.exports = function xor (a, b) { return a } -},{}],1464:[function(require,module,exports){ +},{}],1282:[function(require,module,exports){ function abortable(onEnd) { var aborted = false, reading = false, ended = false, _cb, _read @@ -196903,7 +146695,7 @@ module.exports = abortable -},{}],1465:[function(require,module,exports){ +},{}],1283:[function(require,module,exports){ var noop = function () {} function abortAll(ary, abort, cb) { @@ -196946,7 +146738,7 @@ module.exports = function (streams) { -},{}],1466:[function(require,module,exports){ +},{}],1284:[function(require,module,exports){ var Source = require('./source') var Sink = require('./sink') @@ -196969,14 +146761,14 @@ module.exports = function () { } -},{"./sink":1468,"./source":1469}],1467:[function(require,module,exports){ +},{"./sink":1286,"./source":1287}],1285:[function(require,module,exports){ exports.source = require('./source') exports.through = require('./through') exports.sink = require('./sink') exports.duplex = require('./duplex') -},{"./duplex":1466,"./sink":1468,"./source":1469,"./through":1470}],1468:[function(require,module,exports){ +},{"./duplex":1284,"./sink":1286,"./source":1287,"./through":1288}],1286:[function(require,module,exports){ module.exports = function (stream) { var read, started = false @@ -196997,7 +146789,7 @@ module.exports = function (stream) { return consume } -},{}],1469:[function(require,module,exports){ +},{}],1287:[function(require,module,exports){ module.exports = function () { var _read, _cb, abortCb, _end @@ -197029,7 +146821,7 @@ module.exports = function () { } -},{}],1470:[function(require,module,exports){ +},{}],1288:[function(require,module,exports){ module.exports = function () { var read, reader, cb, abort, stream @@ -197059,45 +146851,7 @@ module.exports = function () { return delayed } -},{}],1471:[function(require,module,exports){ -/* global FileReader */ -var toBuffer = require('typedarray-to-buffer') - -module.exports = function (file, opts) { - opts = opts || {} - - var offset = opts.offset || 0 - var chunkSize = opts.chunkSize || 1024 * 1024 // default 1MB chunk has tolerable perf on large files - - return function (end, cb) { - if (end) return cb(end) - // If finished reading then stop - if (offset >= file.size) return cb(true) - - var fileReader = new FileReader(file) - - fileReader.onloadend = function loaded (event) { - var data = event.target.result - - if (data instanceof ArrayBuffer) { - data = toBuffer(new Uint8Array(event.target.result)) - } - - cb(null, data) - } - - fileReader.onerror = function (err) { - cb(err) - } - - var endIndex = offset + chunkSize - var slice = file.slice(offset, endIndex) - fileReader.readAsArrayBuffer(slice) - offset = endIndex - } -} - -},{"typedarray-to-buffer":1763}],1472:[function(require,module,exports){ +},{}],1289:[function(require,module,exports){ var Reader = require('pull-reader') var Writer = require('pull-pushable') var cat = require('pull-cat') @@ -197148,7 +146902,7 @@ module.exports = function (opts, _cb) { } } -},{"pull-cat":1465,"pull-pair":1489,"pull-pushable":1490,"pull-reader":1491}],1473:[function(require,module,exports){ +},{"pull-cat":1283,"pull-pair":1305,"pull-pushable":1306,"pull-reader":1307}],1290:[function(require,module,exports){ 'use strict' const varint = require('varint') @@ -197299,7 +147053,7 @@ function readMessage (reader, size, cb) { }) } -},{"pull-pushable":1490,"pull-reader":1491,"safe-buffer":1593,"varint":1785}],1474:[function(require,module,exports){ +},{"pull-pushable":1306,"pull-reader":1307,"safe-buffer":1371,"varint":1521}],1291:[function(require,module,exports){ 'use strict' const Buffer = require('safe-buffer').Buffer @@ -197366,7 +147120,7 @@ function createPool () { return Buffer.alloc(poolSize) } -},{"safe-buffer":1593,"varint":1785}],1475:[function(require,module,exports){ +},{"safe-buffer":1371,"varint":1521}],1292:[function(require,module,exports){ 'use strict' const encode = require('./encode') @@ -197376,7 +147130,7 @@ exports.encode = encode exports.decode = d.decode exports.decodeFromReader = d.decodeFromReader -},{"./decode":1473,"./encode":1474}],1476:[function(require,module,exports){ +},{"./decode":1290,"./encode":1291}],1293:[function(require,module,exports){ /* @@ -197512,11 +147266,11 @@ module.exports = function (ary) { } -},{}],1477:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1478,"_process":1438,"dup":247}],1478:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1480}],1479:[function(require,module,exports){ +},{}],1294:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":1295,"_process":1258,"dup":208}],1295:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],1296:[function(require,module,exports){ module.exports = function (fn) { @@ -197542,9 +147296,7 @@ module.exports = function (fn) { -},{}],1480:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1481:[function(require,module,exports){ +},{}],1297:[function(require,module,exports){ 'use strict' const pushable = require('pull-pushable') @@ -197800,12 +147552,12 @@ class Channel extends EE { module.exports = Channel -},{"./consts":1484,"./util":1488,"async/nextTick":140,"debug":1477,"events":370,"looper":1479,"pull-pushable":1490}],1482:[function(require,module,exports){ +},{"./consts":1300,"./util":1304,"async/nextTick":90,"debug":1294,"events":272,"looper":1296,"pull-pushable":1306}],1298:[function(require,module,exports){ 'use strict' module.exports = '/mplex/6.7.0' -},{}],1483:[function(require,module,exports){ +},{}],1299:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -197970,7 +147722,7 @@ exports.decode = () => { } }).call(this,require("buffer").Buffer) -},{"buffer":217,"debug":1477,"pull-through":1526,"varint":1785}],1484:[function(require,module,exports){ +},{"buffer":181,"debug":1294,"pull-through":1342,"varint":1521}],1300:[function(require,module,exports){ 'use strict' /** @@ -197992,7 +147744,7 @@ exports.Types = { exports.MAX_MSG_SIZE = 1 << 20 // 1MB -},{}],1485:[function(require,module,exports){ +},{}],1301:[function(require,module,exports){ 'use strict' const abortable = require('pull-abortable') @@ -198043,7 +147795,7 @@ exports.multicodec = MULTIPLEX_CODEC exports.dialer = (conn) => create(conn, false) exports.listener = (conn) => create(conn, true) -},{"./codec":1482,"./mplex":1486,"./muxer":1487,"debug":1477,"pull-abortable":1464,"pull-stream":1495}],1486:[function(require,module,exports){ +},{"./codec":1298,"./mplex":1302,"./muxer":1303,"debug":1294,"pull-abortable":1282,"pull-stream":1311}],1302:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -198367,7 +148119,7 @@ class Mplex extends EE { module.exports = Mplex }).call(this,require("buffer").Buffer) -},{"./channel":1481,"./coder":1483,"./consts":1484,"./util":1488,"async/nextTick":140,"buffer":217,"debug":1477,"events":370,"looper":1479,"pull-pushable":1490,"pull-stream":1495,"pull-through":1526}],1487:[function(require,module,exports){ +},{"./channel":1297,"./coder":1299,"./consts":1300,"./util":1304,"async/nextTick":90,"buffer":181,"debug":1294,"events":272,"looper":1296,"pull-pushable":1306,"pull-stream":1311,"pull-through":1342}],1303:[function(require,module,exports){ 'use strict' const EventEmitter = require('events').EventEmitter @@ -198440,7 +148192,7 @@ class MultiplexMuxer extends EventEmitter { module.exports = MultiplexMuxer -},{"./codec":1482,"async/nextTick":140,"debug":1477,"events":370,"interface-connection":455}],1488:[function(require,module,exports){ +},{"./codec":1298,"async/nextTick":90,"debug":1294,"events":272,"interface-connection":319}],1304:[function(require,module,exports){ 'use strict' /** @@ -198465,7 +148217,7 @@ function emitError (that, error) { module.exports.emitError = emitError module.exports.emitStream = emitStream -},{}],1489:[function(require,module,exports){ +},{}],1305:[function(require,module,exports){ 'use strict' //a pair of pull streams where one drains from the other @@ -198497,7 +148249,7 @@ module.exports = function () { } -},{}],1490:[function(require,module,exports){ +},{}],1306:[function(require,module,exports){ module.exports = pullPushable function pullPushable (separated, onClose) { @@ -198585,7 +148337,7 @@ function pullPushable (separated, onClose) { } } -},{}],1491:[function(require,module,exports){ +},{}],1307:[function(require,module,exports){ 'use strict' var State = require('./state') @@ -198714,7 +148466,7 @@ module.exports = function (timeout) { -},{"./state":1492}],1492:[function(require,module,exports){ +},{"./state":1308}],1308:[function(require,module,exports){ (function (Buffer){ module.exports = function () { @@ -198791,7 +148543,7 @@ module.exports = function () { }).call(this,require("buffer").Buffer) -},{"buffer":217}],1493:[function(require,module,exports){ +},{"buffer":181}],1309:[function(require,module,exports){ const pull = require('pull-stream/pull') module.exports = source => { @@ -198818,7 +148570,7 @@ module.exports = source => { })() } -},{"pull-stream/pull":1496}],1494:[function(require,module,exports){ +},{"pull-stream/pull":1312}],1310:[function(require,module,exports){ (function (process,setImmediate){ var Stream = require('stream') @@ -198972,7 +148724,7 @@ function duplex (reader, read) { } }).call(this,require('_process'),require("timers").setImmediate) -},{"_process":1438,"stream":1715,"timers":1749}],1495:[function(require,module,exports){ +},{"_process":1258,"stream":1459,"timers":1500}],1311:[function(require,module,exports){ 'use strict' var sources = require('./sources') @@ -198993,7 +148745,7 @@ for(var k in sinks) exports[k] = sinks[k] -},{"./pull":1496,"./sinks":1501,"./sources":1508,"./throughs":1517}],1496:[function(require,module,exports){ +},{"./pull":1312,"./sinks":1317,"./sources":1324,"./throughs":1333}],1312:[function(require,module,exports){ 'use strict' module.exports = function pull (a) { @@ -199044,7 +148796,7 @@ module.exports = function pull (a) { return read } -},{}],1497:[function(require,module,exports){ +},{}],1313:[function(require,module,exports){ 'use strict' var reduce = require('./reduce') @@ -199056,7 +148808,7 @@ module.exports = function collect (cb) { }, [], cb) } -},{"./reduce":1504}],1498:[function(require,module,exports){ +},{"./reduce":1320}],1314:[function(require,module,exports){ 'use strict' var reduce = require('./reduce') @@ -199067,7 +148819,7 @@ module.exports = function concat (cb) { }, '', cb) } -},{"./reduce":1504}],1499:[function(require,module,exports){ +},{"./reduce":1320}],1315:[function(require,module,exports){ 'use strict' module.exports = function drain (op, done) { @@ -199117,7 +148869,7 @@ module.exports = function drain (op, done) { return sink } -},{}],1500:[function(require,module,exports){ +},{}],1316:[function(require,module,exports){ 'use strict' function id (e) { return e } @@ -199147,7 +148899,7 @@ module.exports = function find (test, cb) { -},{"../util/prop":1524,"./drain":1499}],1501:[function(require,module,exports){ +},{"../util/prop":1340,"./drain":1315}],1317:[function(require,module,exports){ 'use strict' module.exports = { @@ -199161,7 +148913,7 @@ module.exports = { } -},{"./collect":1497,"./concat":1498,"./drain":1499,"./find":1500,"./log":1502,"./on-end":1503,"./reduce":1504}],1502:[function(require,module,exports){ +},{"./collect":1313,"./concat":1314,"./drain":1315,"./find":1316,"./log":1318,"./on-end":1319,"./reduce":1320}],1318:[function(require,module,exports){ 'use strict' var drain = require('./drain') @@ -199172,7 +148924,7 @@ module.exports = function log (done) { }, done) } -},{"./drain":1499}],1503:[function(require,module,exports){ +},{"./drain":1315}],1319:[function(require,module,exports){ 'use strict' var drain = require('./drain') @@ -199181,7 +148933,7 @@ module.exports = function onEnd (done) { return drain(null, done) } -},{"./drain":1499}],1504:[function(require,module,exports){ +},{"./drain":1315}],1320:[function(require,module,exports){ 'use strict' var drain = require('./drain') @@ -199205,7 +148957,7 @@ module.exports = function reduce (reducer, acc, cb ) { return sink } -},{"./drain":1499}],1505:[function(require,module,exports){ +},{"./drain":1315}],1321:[function(require,module,exports){ 'use strict' module.exports = function count (max) { @@ -199220,7 +148972,7 @@ module.exports = function count (max) { -},{}],1506:[function(require,module,exports){ +},{}],1322:[function(require,module,exports){ 'use strict' //a stream that ends immediately. module.exports = function empty () { @@ -199229,7 +148981,7 @@ module.exports = function empty () { } } -},{}],1507:[function(require,module,exports){ +},{}],1323:[function(require,module,exports){ 'use strict' //a stream that errors immediately. module.exports = function error (err) { @@ -199239,7 +148991,7 @@ module.exports = function error (err) { } -},{}],1508:[function(require,module,exports){ +},{}],1324:[function(require,module,exports){ 'use strict' module.exports = { keys: require('./keys'), @@ -199251,7 +149003,7 @@ module.exports = { error: require('./error') } -},{"./count":1505,"./empty":1506,"./error":1507,"./infinite":1509,"./keys":1510,"./once":1511,"./values":1512}],1509:[function(require,module,exports){ +},{"./count":1321,"./empty":1322,"./error":1323,"./infinite":1325,"./keys":1326,"./once":1327,"./values":1328}],1325:[function(require,module,exports){ 'use strict' module.exports = function infinite (generate) { generate = generate || Math.random @@ -199263,7 +149015,7 @@ module.exports = function infinite (generate) { -},{}],1510:[function(require,module,exports){ +},{}],1326:[function(require,module,exports){ 'use strict' var values = require('./values') module.exports = function (object) { @@ -199272,7 +149024,7 @@ module.exports = function (object) { -},{"./values":1512}],1511:[function(require,module,exports){ +},{"./values":1328}],1327:[function(require,module,exports){ 'use strict' var abortCb = require('../util/abort-cb') @@ -199290,7 +149042,7 @@ module.exports = function once (value, onAbort) { -},{"../util/abort-cb":1523}],1512:[function(require,module,exports){ +},{"../util/abort-cb":1339}],1328:[function(require,module,exports){ 'use strict' var abortCb = require('../util/abort-cb') @@ -199315,7 +149067,7 @@ module.exports = function values (array, onAbort) { } } -},{"../util/abort-cb":1523}],1513:[function(require,module,exports){ +},{"../util/abort-cb":1339}],1329:[function(require,module,exports){ 'use strict' function id (e) { return e } @@ -199369,7 +149121,7 @@ module.exports = function asyncMap (map) { -},{"../util/prop":1524}],1514:[function(require,module,exports){ +},{"../util/prop":1340}],1330:[function(require,module,exports){ 'use strict' var tester = require('../util/tester') @@ -199380,7 +149132,7 @@ module.exports = function filterNot (test) { return filter(function (data) { return !test(data) }) } -},{"../util/tester":1525,"./filter":1515}],1515:[function(require,module,exports){ +},{"../util/tester":1341,"./filter":1331}],1331:[function(require,module,exports){ 'use strict' var tester = require('../util/tester') @@ -199406,7 +149158,7 @@ module.exports = function filter (test) { } -},{"../util/tester":1525}],1516:[function(require,module,exports){ +},{"../util/tester":1341}],1332:[function(require,module,exports){ 'use strict' var values = require('../sources/values') @@ -199455,7 +149207,7 @@ module.exports = function flatten () { } -},{"../sources/once":1511,"../sources/values":1512}],1517:[function(require,module,exports){ +},{"../sources/once":1327,"../sources/values":1328}],1333:[function(require,module,exports){ 'use strict' module.exports = { @@ -199473,7 +149225,7 @@ module.exports = { -},{"./async-map":1513,"./filter":1515,"./filter-not":1514,"./flatten":1516,"./map":1518,"./non-unique":1519,"./take":1520,"./through":1521,"./unique":1522}],1518:[function(require,module,exports){ +},{"./async-map":1329,"./filter":1331,"./filter-not":1330,"./flatten":1332,"./map":1334,"./non-unique":1335,"./take":1336,"./through":1337,"./unique":1338}],1334:[function(require,module,exports){ 'use strict' function id (e) { return e } @@ -199498,7 +149250,7 @@ module.exports = function map (mapper) { } } -},{"../util/prop":1524}],1519:[function(require,module,exports){ +},{"../util/prop":1340}],1335:[function(require,module,exports){ 'use strict' var unique = require('./unique') @@ -199508,7 +149260,7 @@ module.exports = function nonUnique (field) { return unique(field, true) } -},{"./unique":1522}],1520:[function(require,module,exports){ +},{"./unique":1338}],1336:[function(require,module,exports){ 'use strict' //read a number of items and then stop. @@ -199551,7 +149303,7 @@ module.exports = function take (test, opts) { } } -},{}],1521:[function(require,module,exports){ +},{}],1337:[function(require,module,exports){ 'use strict' //a pass through stream that doesn't change the value. @@ -199576,7 +149328,7 @@ module.exports = function through (op, onEnd) { } } -},{}],1522:[function(require,module,exports){ +},{}],1338:[function(require,module,exports){ 'use strict' function id (e) { return e } @@ -199596,7 +149348,7 @@ module.exports = function unique (field, invert) { } -},{"../util/prop":1524,"./filter":1515}],1523:[function(require,module,exports){ +},{"../util/prop":1340,"./filter":1331}],1339:[function(require,module,exports){ module.exports = function abortCb(cb, abort, onAbort) { cb(abort) onAbort && onAbort(abort === true ? null: abort) @@ -199604,7 +149356,7 @@ module.exports = function abortCb(cb, abort, onAbort) { } -},{}],1524:[function(require,module,exports){ +},{}],1340:[function(require,module,exports){ module.exports = function prop (key) { return key && ( 'string' == typeof key @@ -199615,7 +149367,7 @@ module.exports = function prop (key) { ) } -},{}],1525:[function(require,module,exports){ +},{}],1341:[function(require,module,exports){ var prop = require('./prop') function id (e) { return e } @@ -199628,7 +149380,7 @@ module.exports = function tester (test) { ) } -},{"./prop":1524}],1526:[function(require,module,exports){ +},{"./prop":1340}],1342:[function(require,module,exports){ var looper = require('looper') module.exports = function (writer, ender) { @@ -199699,7 +149451,7 @@ module.exports = function (writer, ender) { } -},{"looper":1294}],1527:[function(require,module,exports){ +},{"looper":1123}],1343:[function(require,module,exports){ var once = exports.once = function (value) { @@ -199733,7 +149485,7 @@ function (start, createStream) { while(reads.length) reads.shift()(end, function () {}) - + return cb(end) } //if this stream has ended, go to the next queue @@ -199747,7 +149499,7 @@ function (start, createStream) { } //width first is just like depth first, //but push each new stream onto the end of the queue -var widthFirst = exports.widthFirst = +var widthFirst = exports.widthFirst = function (start, createStream) { var reads = [] @@ -199770,12 +149522,12 @@ function (start, createStream) { //this came out different to the first (strm) //attempt at leafFirst, but it's still a valid //topological sort. -var leafFirst = exports.leafFirst = +var leafFirst = exports.leafFirst = function (start, createStream) { var reads = [] var output = [] reads.push(once(start)) - + return function next (end, cb) { reads[0](end, function (end, data) { if(end) { @@ -199792,7 +149544,7 @@ function (start, createStream) { } -},{}],1528:[function(require,module,exports){ +},{}],1344:[function(require,module,exports){ 'use strict'; //load websocket library if we are not in the browser @@ -199832,7 +149584,7 @@ module.exports = function (addr, opts) { module.exports.connect = module.exports -},{"./duplex":1529,"./web-socket":1535,"./ws-url":1536}],1529:[function(require,module,exports){ +},{"./duplex":1345,"./web-socket":1351,"./ws-url":1352}],1345:[function(require,module,exports){ var source = require('./source') var sink = require('./sink') @@ -199857,7 +149609,7 @@ function duplex (ws, opts) { }; -},{"./sink":1533,"./source":1534}],1530:[function(require,module,exports){ +},{"./sink":1349,"./source":1350}],1346:[function(require,module,exports){ var exports = module.exports = require('./duplex') exports.source = require('./source'); @@ -199865,7 +149617,7 @@ exports.sink = require('./sink'); exports.createServer = require('./server') exports.connect = require('./client') -},{"./client":1528,"./duplex":1529,"./server":182,"./sink":1533,"./source":1534}],1531:[function(require,module,exports){ +},{"./client":1344,"./duplex":1345,"./server":146,"./sink":1349,"./source":1350}],1347:[function(require,module,exports){ module.exports = function(socket, callback) { var remove = socket && (socket.removeEventListener || socket.removeListener); @@ -199898,7 +149650,7 @@ module.exports = function(socket, callback) { socket.addEventListener('error', handleErr); }; -},{}],1532:[function(require,module,exports){ +},{}],1348:[function(require,module,exports){ var ws = require('./') var WebSocket = require('ws') var url = require('url') @@ -199967,7 +149719,7 @@ module.exports = !WebSocket.Server ? null : function (opts, onConnection) { -},{"./":1530,"events":370,"http":1716,"https":446,"url":1769,"ws":182}],1533:[function(require,module,exports){ +},{"./":1346,"events":272,"http":1475,"https":311,"url":1507,"ws":146}],1349:[function(require,module,exports){ (function (process,setImmediate){ var ready = require('./ready'); @@ -200025,7 +149777,7 @@ module.exports = function(socket, opts) { } }).call(this,require('_process'),require("timers").setImmediate) -},{"./ready":1531,"_process":1438,"timers":1749}],1534:[function(require,module,exports){ +},{"./ready":1347,"_process":1258,"timers":1500}],1350:[function(require,module,exports){ /** ### `source(socket)` @@ -200113,11 +149865,11 @@ module.exports = function(socket, cb) { return read; }; -},{"safe-buffer":1593}],1535:[function(require,module,exports){ +},{"safe-buffer":1371}],1351:[function(require,module,exports){ module.exports = 'undefined' === typeof WebSocket ? require('ws') : WebSocket -},{"ws":182}],1536:[function(require,module,exports){ +},{"ws":146}],1352:[function(require,module,exports){ var { relative } = require('iso-url') var map = {http:'ws', https:'wss'} var def = 'ws' @@ -200127,7 +149879,7 @@ module.exports = function (url, location) { -},{"iso-url":802}],1537:[function(require,module,exports){ +},{"iso-url":641}],1353:[function(require,module,exports){ (function (process){ var once = require('once') var eos = require('end-of-stream') @@ -200213,544 +149965,7 @@ var pump = function () { module.exports = pump }).call(this,require('_process')) -},{"_process":1438,"end-of-stream":299,"fs":182,"once":1394}],1538:[function(require,module,exports){ -(function (global){ -/*! https://mths.be/punycode v1.4.1 by @mathias */ -;(function(root) { - - /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports && - !exports.nodeType && exports; - var freeModule = typeof module == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof global == 'object' && global; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.4.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { - // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { - // in Rhino or a web browser - root.punycode = punycode; - } - -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1539:[function(require,module,exports){ +},{"_process":1258,"end-of-stream":253,"fs":146,"once":1228}],1354:[function(require,module,exports){ 'use strict'; var replace = String.prototype.replace; @@ -200770,7 +149985,7 @@ module.exports = { RFC3986: 'RFC3986' }; -},{}],1540:[function(require,module,exports){ +},{}],1355:[function(require,module,exports){ 'use strict'; var stringify = require('./stringify'); @@ -200783,7 +149998,7 @@ module.exports = { stringify: stringify }; -},{"./formats":1539,"./parse":1541,"./stringify":1542}],1541:[function(require,module,exports){ +},{"./formats":1354,"./parse":1356,"./stringify":1357}],1356:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); @@ -200794,63 +150009,21 @@ var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, - charset: 'utf-8', - charsetSentinel: false, - comma: false, decoder: utils.decode, delimiter: '&', depth: 5, - ignoreQueryPrefix: false, - interpretNumericEntities: false, parameterLimit: 1000, - parseArrays: true, plainObjects: false, strictNullHandling: false }; -var interpretNumericEntities = function (str) { - return str.replace(/&#(\d+);/g, function ($0, numberStr) { - return String.fromCharCode(parseInt(numberStr, 10)); - }); -}; - -// This is what browsers will submit when the ✓ character occurs in an -// application/x-www-form-urlencoded body and the encoding of the page containing -// the form is iso-8859-1, or when the submitted form has an accept-charset -// attribute of iso-8859-1. Presumably also with other charsets that do not contain -// the ✓ character, such as us-ascii. -var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') - -// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. -var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') - var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); - var skipIndex = -1; // Keep track of where the utf8 sentinel was found - var i; - var charset = options.charset; - if (options.charsetSentinel) { - for (i = 0; i < parts.length; ++i) { - if (parts[i].indexOf('utf8=') === 0) { - if (parts[i] === charsetSentinel) { - charset = 'utf-8'; - } else if (parts[i] === isoSentinel) { - charset = 'iso-8859-1'; - } - skipIndex = i; - i = parts.length; // The eslint settings do not allow break; - } - } - } - - for (i = 0; i < parts.length; ++i) { - if (i === skipIndex) { - continue; - } + for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); @@ -200858,23 +150031,14 @@ var parseValues = function parseQueryStringValues(str, options) { var key, val; if (pos === -1) { - key = options.decoder(part, defaults.decoder, charset); + key = options.decoder(part, defaults.decoder); val = options.strictNullHandling ? null : ''; } else { - key = options.decoder(part.slice(0, pos), defaults.decoder, charset); - val = options.decoder(part.slice(pos + 1), defaults.decoder, charset); + key = options.decoder(part.slice(0, pos), defaults.decoder); + val = options.decoder(part.slice(pos + 1), defaults.decoder); } - - if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { - val = interpretNumericEntities(val); - } - - if (val && options.comma && val.indexOf(',') > -1) { - val = val.split(','); - } - if (has.call(obj, key)) { - obj[key] = utils.combine(obj[key], val); + obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } @@ -200890,15 +150054,14 @@ var parseObject = function (chain, val, options) { var obj; var root = chain[i]; - if (root === '[]' && options.parseArrays) { - obj = [].concat(leaf); + if (root === '[]') { + obj = []; + obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); - if (!options.parseArrays && cleanRoot === '') { - obj = { 0: leaf }; - } else if ( + if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot @@ -200940,7 +150103,8 @@ var parseKeys = function parseQueryStringKeys(givenKey, val, options) { var keys = []; if (parent) { - // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; @@ -200972,41 +150136,24 @@ var parseKeys = function parseQueryStringKeys(givenKey, val, options) { return parseObject(keys, val, options); }; -var normalizeParseOptions = function normalizeParseOptions(opts) { - if (!opts) { - return defaults; - } +module.exports = function (str, opts) { + var options = opts ? utils.assign({}, opts) : {}; - if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; - - return { - allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, - allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, - arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, - decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, - delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, - depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth, - ignoreQueryPrefix: opts.ignoreQueryPrefix === true, - interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, - parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, - parseArrays: opts.parseArrays !== false, - plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling - }; -}; - -module.exports = function (str, opts) { - var options = normalizeParseOptions(opts); + options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; + options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; @@ -201027,18 +150174,16 @@ module.exports = function (str, opts) { return utils.compact(obj); }; -},{"./utils":1543}],1542:[function(require,module,exports){ +},{"./utils":1358}],1357:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var formats = require('./formats'); -var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, - comma: 'comma', indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, @@ -201047,26 +150192,13 @@ var arrayPrefixGenerators = { } }; -var isArray = Array.isArray; -var push = Array.prototype.push; -var pushToArray = function (arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); -}; - var toISO = Date.prototype.toISOString; var defaults = { - addQueryPrefix: false, - allowDots: false, - charset: 'utf-8', - charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, - formatter: formats.formatters[formats['default']], - // deprecated - indices: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, @@ -201086,21 +150218,16 @@ var stringify = function stringify( // eslint-disable-line func-name-matching allowDots, serializeDate, formatter, - encodeValuesOnly, - charset + encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); - } else if (generateArrayPrefix === 'comma' && isArray(obj)) { - obj = obj.join(','); - } - - if (obj === null) { + } else if (obj === null) { if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix; + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; } obj = ''; @@ -201108,8 +150235,8 @@ var stringify = function stringify( // eslint-disable-line func-name-matching if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset); - return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))]; + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } @@ -201121,7 +150248,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching } var objKeys; - if (isArray(filter)) { + if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); @@ -201135,10 +150262,10 @@ var stringify = function stringify( // eslint-disable-line func-name-matching continue; } - if (isArray(obj)) { - pushToArray(values, stringify( + if (Array.isArray(obj)) { + values = values.concat(stringify( obj[key], - typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, + generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, @@ -201148,11 +150275,10 @@ var stringify = function stringify( // eslint-disable-line func-name-matching allowDots, serializeDate, formatter, - encodeValuesOnly, - charset + encodeValuesOnly )); } else { - pushToArray(values, stringify( + values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, @@ -201164,8 +150290,7 @@ var stringify = function stringify( // eslint-disable-line func-name-matching allowDots, serializeDate, formatter, - encodeValuesOnly, - charset + encodeValuesOnly )); } } @@ -201173,63 +150298,36 @@ var stringify = function stringify( // eslint-disable-line func-name-matching return values; }; -var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { - if (!opts) { - return defaults; - } +module.exports = function (object, opts) { + var obj = object; + var options = opts ? utils.assign({}, opts) : {}; - if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { + if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } - var charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; + var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; + var sort = typeof options.sort === 'function' ? options.sort : null; + var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; + var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; + var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; + if (typeof options.format === 'undefined') { + options.format = formats['default']; + } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { + throw new TypeError('Unknown format option provided.'); } - - var format = formats['default']; - if (typeof opts.format !== 'undefined') { - if (!has.call(formats.formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - var formatter = formats.formatters[format]; - - var filter = defaults.filter; - if (typeof opts.filter === 'function' || isArray(opts.filter)) { - filter = opts.filter; - } - - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling - }; -}; - -module.exports = function (object, opts) { - var obj = object; - var options = normalizeStringifyOptions(opts); - + var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); - } else if (isArray(options.filter)) { + } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } @@ -201241,10 +150339,10 @@ module.exports = function (object, opts) { } var arrayFormat; - if (opts && opts.arrayFormat in arrayPrefixGenerators) { - arrayFormat = opts.arrayFormat; - } else if (opts && 'indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; + if (options.arrayFormat in arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } @@ -201255,54 +150353,43 @@ module.exports = function (object, opts) { objKeys = Object.keys(obj); } - if (options.sort) { - objKeys.sort(options.sort); + if (sort) { + objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; - if (options.skipNulls && obj[key] === null) { + if (skipNulls && obj[key] === null) { continue; } - pushToArray(keys, stringify( + + keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, - options.strictNullHandling, - options.skipNulls, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.formatter, - options.encodeValuesOnly, - options.charset + strictNullHandling, + skipNulls, + encode ? encoder : null, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly )); } - var joined = keys.join(options.delimiter); + var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - return joined.length > 0 ? prefix + joined : ''; }; -},{"./formats":1539,"./utils":1543}],1543:[function(require,module,exports){ +},{"./formats":1354,"./utils":1358}],1358:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty; -var isArray = Array.isArray; var hexTable = (function () { var array = []; @@ -201314,11 +150401,13 @@ var hexTable = (function () { }()); var compactQueue = function compactQueue(queue) { - while (queue.length > 1) { - var item = queue.pop(); - var obj = item.obj[item.prop]; + var obj; - if (isArray(obj)) { + while (queue.length) { + var item = queue.pop(); + obj = item.obj[item.prop]; + + if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { @@ -201330,6 +150419,8 @@ var compactQueue = function compactQueue(queue) { item.obj[item.prop] = compacted; } } + + return obj; }; var arrayToObject = function arrayToObject(source, options) { @@ -201349,10 +150440,10 @@ var merge = function merge(target, source, options) { } if (typeof source !== 'object') { - if (isArray(target)) { + if (Array.isArray(target)) { target.push(source); - } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + } else if (typeof target === 'object') { + if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { @@ -201362,21 +150453,20 @@ var merge = function merge(target, source, options) { return target; } - if (!target || typeof target !== 'object') { + if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; - if (isArray(target) && !isArray(source)) { + if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = arrayToObject(target, options); } - if (isArray(target) && isArray(source)) { + if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { - var targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); + if (target[i] && typeof target[i] === 'object') { + target[i] = merge(target[i], item, options); } else { target.push(item); } @@ -201406,21 +150496,15 @@ var assign = function assignSingleSource(target, source) { }, target); }; -var decode = function (str, decoder, charset) { - var strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 +var decode = function (str) { try { - return decodeURIComponent(strWithoutPlus); + return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { - return strWithoutPlus; + return str; } }; -var encode = function encode(str, defaultEncoder, charset) { +var encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { @@ -201429,12 +150513,6 @@ var encode = function encode(str, defaultEncoder, charset) { var string = typeof str === 'string' ? str : String(str); - if (charset === 'iso-8859-1') { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { - return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; - }); - } - var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); @@ -201497,9 +150575,7 @@ var compact = function compact(value) { } } - compactQueue(queue); - - return value; + return compactQueue(queue); }; var isRegExp = function isRegExp(obj) { @@ -201507,21 +150583,16 @@ var isRegExp = function isRegExp(obj) { }; var isBuffer = function isBuffer(obj) { - if (!obj || typeof obj !== 'object') { + if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; -var combine = function combine(a, b) { - return [].concat(a, b); -}; - module.exports = { arrayToObject: arrayToObject, assign: assign, - combine: combine, compact: compact, decode: decode, encode: encode, @@ -201530,233 +150601,7 @@ module.exports = { merge: merge }; -},{}],1544:[function(require,module,exports){ -'use strict'; -var strictUriEncode = require('strict-uri-encode'); -var objectAssign = require('object-assign'); -var decodeComponent = require('decode-uri-component'); - -function encoderForArrayFormat(opts) { - switch (opts.arrayFormat) { - case 'index': - return function (key, value, index) { - return value === null ? [ - encode(key, opts), - '[', - index, - ']' - ].join('') : [ - encode(key, opts), - '[', - encode(index, opts), - ']=', - encode(value, opts) - ].join(''); - }; - - case 'bracket': - return function (key, value) { - return value === null ? encode(key, opts) : [ - encode(key, opts), - '[]=', - encode(value, opts) - ].join(''); - }; - - default: - return function (key, value) { - return value === null ? encode(key, opts) : [ - encode(key, opts), - '=', - encode(value, opts) - ].join(''); - }; - } -} - -function parserForArrayFormat(opts) { - var result; - - switch (opts.arrayFormat) { - case 'index': - return function (key, value, accumulator) { - result = /\[(\d*)\]$/.exec(key); - - key = key.replace(/\[\d*\]$/, ''); - - if (!result) { - accumulator[key] = value; - return; - } - - if (accumulator[key] === undefined) { - accumulator[key] = {}; - } - - accumulator[key][result[1]] = value; - }; - - case 'bracket': - return function (key, value, accumulator) { - result = /(\[\])$/.exec(key); - key = key.replace(/\[\]$/, ''); - - if (!result) { - accumulator[key] = value; - return; - } else if (accumulator[key] === undefined) { - accumulator[key] = [value]; - return; - } - - accumulator[key] = [].concat(accumulator[key], value); - }; - - default: - return function (key, value, accumulator) { - if (accumulator[key] === undefined) { - accumulator[key] = value; - return; - } - - accumulator[key] = [].concat(accumulator[key], value); - }; - } -} - -function encode(value, opts) { - if (opts.encode) { - return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); - } - - return value; -} - -function keysSorter(input) { - if (Array.isArray(input)) { - return input.sort(); - } else if (typeof input === 'object') { - return keysSorter(Object.keys(input)).sort(function (a, b) { - return Number(a) - Number(b); - }).map(function (key) { - return input[key]; - }); - } - - return input; -} - -function extract(str) { - var queryStart = str.indexOf('?'); - if (queryStart === -1) { - return ''; - } - return str.slice(queryStart + 1); -} - -function parse(str, opts) { - opts = objectAssign({arrayFormat: 'none'}, opts); - - var formatter = parserForArrayFormat(opts); - - // Create an object with no prototype - // https://github.com/sindresorhus/query-string/issues/47 - var ret = Object.create(null); - - if (typeof str !== 'string') { - return ret; - } - - str = str.trim().replace(/^[?#&]/, ''); - - if (!str) { - return ret; - } - - str.split('&').forEach(function (param) { - var parts = param.replace(/\+/g, ' ').split('='); - // Firefox (pre 40) decodes `%3D` to `=` - // https://github.com/sindresorhus/query-string/pull/37 - var key = parts.shift(); - var val = parts.length > 0 ? parts.join('=') : undefined; - - // missing `=` should be `null`: - // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters - val = val === undefined ? null : decodeComponent(val); - - formatter(decodeComponent(key), val, ret); - }); - - return Object.keys(ret).sort().reduce(function (result, key) { - var val = ret[key]; - if (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) { - // Sort object keys, not values - result[key] = keysSorter(val); - } else { - result[key] = val; - } - - return result; - }, Object.create(null)); -} - -exports.extract = extract; -exports.parse = parse; - -exports.stringify = function (obj, opts) { - var defaults = { - encode: true, - strict: true, - arrayFormat: 'none' - }; - - opts = objectAssign(defaults, opts); - - if (opts.sort === false) { - opts.sort = function () {}; - } - - var formatter = encoderForArrayFormat(opts); - - return obj ? Object.keys(obj).sort(opts.sort).map(function (key) { - var val = obj[key]; - - if (val === undefined) { - return ''; - } - - if (val === null) { - return encode(key, opts); - } - - if (Array.isArray(val)) { - var result = []; - - val.slice().forEach(function (val2) { - if (val2 === undefined) { - return; - } - - result.push(formatter(key, val2, result.length)); - }); - - return result.join('&'); - } - - return encode(key, opts) + '=' + encode(val, opts); - }).filter(function (x) { - return x.length > 0; - }).join('&') : ''; -}; - -exports.parseUrl = function (str, opts) { - return { - url: str.split('?')[0] || '', - query: parse(extract(str), opts) - }; -}; - -},{"decode-uri-component":255,"object-assign":1388,"strict-uri-encode":1736}],1545:[function(require,module,exports){ +},{}],1359:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -201842,7 +150687,7 @@ var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; -},{}],1546:[function(require,module,exports){ +},{}],1360:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -201929,13 +150774,13 @@ var objectKeys = Object.keys || function (obj) { return res; }; -},{}],1547:[function(require,module,exports){ +},{}],1361:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); -},{"./decode":1545,"./encode":1546}],1548:[function(require,module,exports){ +},{"./decode":1359,"./encode":1360}],1362:[function(require,module,exports){ let promise module.exports = typeof queueMicrotask === 'function' @@ -201945,7 +150790,7 @@ module.exports = typeof queueMicrotask === 'function' .then(cb) .catch(err => setTimeout(() => { throw err }, 0)) -},{}],1549:[function(require,module,exports){ +},{}],1363:[function(require,module,exports){ const { instantiateStreaming } = require("assemblyscript/lib/loader"); @@ -201953,14 +150798,14 @@ loadWebAssembly.supported = typeof WebAssembly !== 'undefined' function loadWebAssembly (imp = {}) { if (!loadWebAssembly.supported) return null - + var wasm = new Uint8Array([0,97,115,109,1,0,0,0,1,90,16,96,0,0,96,2,127,127,1,127,96,4,127,127,127,127,0,96,1,127,1,127,96,3,127,127,127,0,96,1,126,1,127,96,2,126,126,1,126,96,5,127,127,127,127,127,1,127,96,3,127,127,126,0,96,2,127,127,1,126,96,3,127,127,127,1,127,96,1,127,0,96,2,127,127,0,96,1,127,1,126,96,2,127,126,0,96,0,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,2,3,57,56,3,3,12,3,3,15,5,6,1,8,4,1,9,11,7,4,10,10,11,0,0,0,3,12,3,12,3,12,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,13,14,4,4,1,112,0,1,5,3,1,0,1,6,26,5,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,253,6,44,6,109,101,109,111,114,121,2,0,5,116,97,98,108,101,1,0,6,100,101,103,114,101,101,0,7,3,109,111,100,0,8,16,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,0,23,16,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,0,24,21,82,97,98,105,110,35,103,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,25,21,82,97,98,105,110,35,115,101,116,58,119,105,110,100,111,119,95,115,105,122,101,0,26,14,82,97,98,105,110,35,103,101,116,58,119,112,111,115,0,27,14,82,97,98,105,110,35,115,101,116,58,119,112,111,115,0,28,15,82,97,98,105,110,35,103,101,116,58,99,111,117,110,116,0,29,15,82,97,98,105,110,35,115,101,116,58,99,111,117,110,116,0,30,13,82,97,98,105,110,35,103,101,116,58,112,111,115,0,31,13,82,97,98,105,110,35,115,101,116,58,112,111,115,0,32,15,82,97,98,105,110,35,103,101,116,58,115,116,97,114,116,0,33,15,82,97,98,105,110,35,115,101,116,58,115,116,97,114,116,0,34,16,82,97,98,105,110,35,103,101,116,58,100,105,103,101,115,116,0,35,16,82,97,98,105,110,35,115,101,116,58,100,105,103,101,115,116,0,36,21,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,37,21,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,115,116,97,114,116,0,38,22,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,39,22,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,108,101,110,103,116,104,0,40,31,82,97,98,105,110,35,103,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,41,31,82,97,98,105,110,35,115,101,116,58,99,104,117,110,107,95,99,117,116,95,102,105,110,103,101,114,112,114,105,110,116,0,42,20,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,0,43,20,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,0,44,27,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,95,100,101,103,114,101,101,0,45,27,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,95,100,101,103,114,101,101,0,46,26,82,97,98,105,110,35,103,101,116,58,112,111,108,121,110,111,109,105,97,108,95,115,104,105,102,116,0,47,26,82,97,98,105,110,35,115,101,116,58,112,111,108,121,110,111,109,105,97,108,95,115,104,105,102,116,0,48,22,82,97,98,105,110,35,103,101,116,58,97,118,101,114,97,103,101,95,98,105,116,115,0,49,22,82,97,98,105,110,35,115,101,116,58,97,118,101,114,97,103,101,95,98,105,116,115,0,50,17,82,97,98,105,110,35,103,101,116,58,109,105,110,115,105,122,101,0,51,17,82,97,98,105,110,35,115,101,116,58,109,105,110,115,105,122,101,0,52,17,82,97,98,105,110,35,103,101,116,58,109,97,120,115,105,122,101,0,53,17,82,97,98,105,110,35,115,101,116,58,109,97,120,115,105,122,101,0,54,14,82,97,98,105,110,35,103,101,116,58,109,97,115,107,0,55,14,82,97,98,105,110,35,115,101,116,58,109,97,115,107,0,56,17,82,97,98,105,110,35,99,111,110,115,116,114,117,99,116,111,114,0,15,17,82,97,98,105,110,35,102,105,110,103,101,114,112,114,105,110,116,0,16,14,109,101,109,111,114,121,46,99,111,109,112,97,114,101,0,18,15,109,101,109,111,114,121,46,97,108,108,111,99,97,116,101,0,4,11,109,101,109,111,114,121,46,102,114,101,101,0,19,12,109,101,109,111,114,121,46,114,101,115,101,116,0,20,8,1,21,9,7,1,0,65,0,11,1,22,10,188,30,56,104,1,3,127,32,0,65,128,128,128,128,4,75,4,64,0,11,35,1,34,1,32,0,65,1,32,0,65,1,75,27,106,65,7,106,65,120,113,34,0,63,0,34,2,65,16,116,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,3,32,2,32,3,74,27,64,0,65,0,72,4,64,32,3,64,0,65,0,72,4,64,0,11,11,11,32,0,36,1,32,1,11,51,1,1,127,32,0,65,248,255,255,255,3,75,4,64,65,0,65,200,0,65,26,65,2,16,0,0,11,65,1,65,32,32,0,65,7,106,103,107,116,16,1,34,1,32,0,54,2,0,32,1,11,145,3,1,1,127,32,1,69,4,64,15,11,32,0,65,0,58,0,0,32,0,32,1,106,65,1,107,65,0,58,0,0,32,1,65,2,77,4,64,15,11,32,0,65,1,106,65,0,58,0,0,32,0,65,2,106,65,0,58,0,0,32,0,32,1,106,34,2,65,2,107,65,0,58,0,0,32,2,65,3,107,65,0,58,0,0,32,1,65,6,77,4,64,15,11,32,0,65,3,106,65,0,58,0,0,32,0,32,1,106,65,4,107,65,0,58,0,0,32,1,65,8,77,4,64,15,11,65,0,32,0,107,65,3,113,34,2,32,0,106,34,0,65,0,54,2,0,32,1,32,2,107,65,124,113,34,1,32,0,106,65,4,107,65,0,54,2,0,32,1,65,8,77,4,64,15,11,32,0,65,4,106,65,0,54,2,0,32,0,65,8,106,65,0,54,2,0,32,0,32,1,106,34,2,65,12,107,65,0,54,2,0,32,2,65,8,107,65,0,54,2,0,32,1,65,24,77,4,64,15,11,32,0,65,12,106,65,0,54,2,0,32,0,65,16,106,65,0,54,2,0,32,0,65,20,106,65,0,54,2,0,32,0,65,24,106,65,0,54,2,0,32,0,32,1,106,34,2,65,28,107,65,0,54,2,0,32,2,65,24,107,65,0,54,2,0,32,2,65,20,107,65,0,54,2,0,32,2,65,16,107,65,0,54,2,0,32,0,65,4,113,65,24,106,34,2,32,0,106,33,0,32,1,32,2,107,33,1,3,64,32,1,65,32,79,4,64,32,0,66,0,55,3,0,32,0,65,8,106,66,0,55,3,0,32,0,65,16,106,66,0,55,3,0,32,0,65,24,106,66,0,55,3,0,32,1,65,32,107,33,1,32,0,65,32,106,33,0,12,1,11,11,11,6,0,32,0,16,1,11,76,1,1,127,65,128,16,16,2,34,1,65,8,106,65,128,16,16,3,32,0,69,4,64,65,12,16,1,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,32,1,54,2,0,32,0,65,0,54,2,4,32,0,65,128,16,54,2,8,32,0,11,8,0,65,12,16,1,16,5,11,70,2,1,127,1,126,66,128,128,128,128,128,128,128,128,128,127,33,2,3,64,2,64,32,1,65,192,0,78,13,0,32,0,32,2,131,66,0,86,4,64,65,63,32,1,107,15,5,32,2,66,1,136,33,2,32,1,65,1,106,33,1,12,2,11,0,11,11,65,127,11,175,2,2,1,127,2,126,3,64,2,127,66,128,128,128,128,128,128,128,128,128,127,33,3,65,0,33,2,3,64,2,64,32,2,65,192,0,78,13,0,65,63,32,2,107,32,0,32,3,131,66,0,86,13,2,26,32,3,66,1,136,33,3,32,2,65,1,106,33,2,12,1,11,11,65,127,11,2,127,32,1,33,4,66,128,128,128,128,128,128,128,128,128,127,33,3,65,0,33,2,3,64,2,64,32,2,65,192,0,78,13,0,65,63,32,2,107,32,3,32,4,131,66,0,86,13,2,26,32,3,66,1,136,33,3,32,2,65,1,106,33,2,12,1,11,11,65,127,11,78,4,64,32,1,2,127,66,128,128,128,128,128,128,128,128,128,127,33,3,65,0,33,2,3,64,2,64,32,2,65,192,0,78,13,0,65,63,32,2,107,32,0,32,3,131,66,0,86,13,2,26,32,3,66,1,136,33,3,32,2,65,1,106,33,2,12,1,11,11,65,127,11,2,127,66,128,128,128,128,128,128,128,128,128,127,33,3,65,0,33,2,3,64,2,64,32,2,65,192,0,78,13,0,65,63,32,2,107,32,1,32,3,131,66,0,86,13,2,26,32,3,66,1,136,33,3,32,2,65,1,106,33,2,12,1,11,11,65,127,11,107,172,134,32,0,133,33,0,12,1,11,11,32,0,11,96,1,1,127,32,1,65,248,255,255,255,3,75,4,64,65,0,65,8,65,23,65,34,16,0,0,11,32,1,16,2,34,2,65,8,106,32,1,16,3,32,0,69,4,64,65,12,16,1,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,32,2,54,2,0,32,0,65,0,54,2,4,32,0,32,1,54,2,8,32,0,11,49,0,32,1,32,0,40,2,8,65,3,118,79,4,64,65,0,65,8,65,50,65,63,16,0,0,11,32,0,40,2,4,32,0,40,2,0,32,1,65,3,116,106,106,32,2,55,3,8,11,43,0,32,1,32,0,40,2,8,79,4,64,65,0,65,8,65,50,65,63,16,0,0,11,32,0,40,2,4,32,1,32,0,40,2,0,106,106,32,2,58,0,8,11,41,0,32,1,32,0,40,2,8,79,4,64,65,0,65,8,65,39,65,63,16,0,0,11,32,0,40,2,4,32,1,32,0,40,2,0,106,106,45,0,8,11,47,0,32,1,32,0,40,2,8,65,3,118,79,4,64,65,0,65,8,65,39,65,63,16,0,0,11,32,0,40,2,4,32,0,40,2,0,32,1,65,3,116,106,106,41,3,8,11,166,10,2,3,127,5,126,35,2,69,4,64,3,64,32,2,65,128,2,72,4,64,32,2,65,255,1,113,173,33,4,32,0,41,3,72,33,6,3,64,2,127,32,4,33,5,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,2,127,32,6,33,7,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,7,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,78,4,64,32,6,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,6,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,107,172,134,32,5,133,33,4,12,1,11,11,65,0,33,1,3,64,32,1,32,0,40,2,4,65,1,107,72,4,64,32,5,66,8,134,33,4,32,0,41,3,72,33,6,3,64,2,127,32,4,33,5,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,3,3,64,32,3,65,192,0,72,4,64,65,63,32,3,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,3,65,1,106,33,3,12,1,11,11,65,127,11,2,127,32,6,33,7,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,3,3,64,32,3,65,192,0,72,4,64,65,63,32,3,107,32,4,32,7,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,3,65,1,106,33,3,12,1,11,11,65,127,11,78,4,64,32,6,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,3,3,64,32,3,65,192,0,72,4,64,65,63,32,3,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,3,65,1,106,33,3,12,1,11,11,65,127,11,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,3,3,64,32,3,65,192,0,72,4,64,65,63,32,3,107,32,4,32,6,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,3,65,1,106,33,3,12,1,11,11,65,127,11,107,172,134,32,5,133,33,4,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,35,4,32,2,32,5,16,10,32,2,65,1,106,33,2,12,1,11,11,2,127,32,0,41,3,72,33,4,66,128,128,128,128,128,128,128,128,128,127,33,5,65,0,33,2,3,64,32,2,65,192,0,72,4,64,65,63,32,2,107,32,4,32,5,131,66,0,86,13,2,26,32,5,66,1,136,33,5,32,2,65,1,106,33,2,12,1,11,11,65,127,11,172,33,8,65,0,33,2,3,64,32,2,65,128,2,72,4,64,35,3,33,3,32,2,172,32,8,134,33,5,32,0,41,3,72,33,6,3,64,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,2,127,32,6,33,7,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,7,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,78,4,64,32,6,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,5,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,2,127,66,128,128,128,128,128,128,128,128,128,127,33,4,65,0,33,1,3,64,32,1,65,192,0,72,4,64,65,63,32,1,107,32,4,32,6,131,66,0,86,13,2,26,32,4,66,1,136,33,4,32,1,65,1,106,33,1,12,1,11,11,65,127,11,107,172,134,32,5,133,33,5,12,1,11,11,32,3,32,2,32,2,172,32,8,134,32,5,132,16,10,32,2,65,1,106,33,2,12,1,11,11,65,1,36,2,11,32,0,66,0,55,3,24,32,0,66,0,55,3,32,65,0,33,2,3,64,32,2,32,0,40,2,4,72,4,64,32,0,40,2,0,32,2,65,0,16,11,32,2,65,1,106,33,2,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,12,33,1,32,0,40,2,0,32,0,40,2,8,65,1,16,11,32,0,32,0,41,3,40,35,4,32,1,65,255,1,113,16,13,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,41,3,40,32,0,41,3,88,136,167,33,1,32,0,32,0,41,3,40,66,8,134,55,3,40,32,0,32,0,41,3,40,66,1,132,55,3,40,32,0,32,0,41,3,40,35,3,32,1,65,255,1,113,16,13,133,55,3,40,11,234,1,0,32,0,69,4,64,65,128,1,16,1,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,24,32,0,66,0,55,3,32,32,0,66,0,55,3,40,32,0,66,0,55,3,48,32,0,66,0,55,3,56,32,0,66,0,55,3,64,32,0,66,0,55,3,72,32,0,66,0,55,3,80,32,0,66,0,55,3,88,32,0,66,0,55,3,96,32,0,66,0,55,3,104,32,0,66,0,55,3,112,32,0,66,0,55,3,120,32,0,32,1,173,55,3,96,32,0,32,2,173,55,3,104,32,0,32,3,173,55,3,112,32,0,65,12,16,1,32,4,16,9,54,2,0,32,0,32,4,54,2,4,32,0,66,1,32,0,41,3,96,134,66,1,125,55,3,120,32,0,66,243,130,183,218,216,230,232,30,55,3,72,32,0,66,53,55,3,80,32,0,32,0,41,3,80,66,8,125,55,3,88,32,0,16,14,32,0,11,206,4,1,5,127,32,1,40,2,8,33,4,32,1,40,2,0,65,8,106,33,5,3,64,2,127,65,0,33,3,3,64,32,3,32,4,72,4,64,32,3,32,5,106,45,0,0,33,1,32,0,40,2,0,32,0,40,2,8,16,12,33,6,32,0,40,2,0,32,0,40,2,8,32,1,16,11,32,0,32,0,41,3,40,35,4,32,6,65,255,1,113,16,13,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,41,3,40,32,0,41,3,88,136,167,33,6,32,0,32,0,41,3,40,66,8,134,55,3,40,32,0,32,0,41,3,40,32,1,173,132,55,3,40,32,0,32,0,41,3,40,35,3,32,6,65,255,1,113,16,13,133,55,3,40,32,0,32,0,41,3,16,66,1,124,55,3,16,32,0,32,0,41,3,24,66,1,124,55,3,24,2,127,32,0,41,3,16,32,0,41,3,104,90,34,1,4,64,32,0,41,3,40,32,0,41,3,120,131,66,0,81,33,1,11,32,1,69,11,4,127,32,0,41,3,16,32,0,41,3,112,90,5,32,1,11,4,64,32,0,32,0,41,3,32,55,3,48,32,0,32,0,41,3,16,55,3,56,32,0,32,0,41,3,40,55,3,64,65,0,33,1,3,64,32,1,32,0,40,2,4,72,4,64,32,0,40,2,0,32,1,65,0,16,11,32,1,65,1,106,33,1,12,1,11,11,32,0,66,0,55,3,40,32,0,65,0,54,2,8,32,0,66,0,55,3,16,32,0,66,0,55,3,40,32,0,40,2,0,32,0,40,2,8,16,12,33,1,32,0,40,2,0,32,0,40,2,8,65,1,16,11,32,0,32,0,41,3,40,35,4,32,1,65,255,1,113,16,13,133,55,3,40,32,0,32,0,40,2,8,65,1,106,32,0,40,2,4,111,54,2,8,32,0,41,3,40,32,0,41,3,88,136,167,33,1,32,0,32,0,41,3,40,66,8,134,55,3,40,32,0,32,0,41,3,40,66,1,132,55,3,40,32,0,32,0,41,3,40,35,3,32,1,65,255,1,113,16,13,133,55,3,40,32,3,65,1,106,12,3,5,32,3,65,1,106,33,3,12,2,11,0,11,11,65,127,11,34,1,65,0,78,4,64,32,4,32,1,107,33,4,32,1,32,5,106,33,5,32,7,34,1,65,1,106,33,7,32,2,40,2,4,32,2,40,2,0,32,1,65,2,116,106,106,32,0,41,3,56,62,2,8,32,2,40,2,4,32,2,40,2,0,32,1,65,2,116,106,106,40,2,8,26,12,1,11,11,11,88,1,1,127,32,0,32,1,70,4,64,65,0,15,11,3,64,32,2,65,0,71,34,3,4,64,32,0,45,0,0,32,1,45,0,0,70,33,3,11,32,3,4,64,32,2,65,1,107,33,2,32,0,65,1,106,33,0,32,1,65,1,106,33,1,12,1,11,11,32,2,4,127,32,0,45,0,0,32,1,45,0,0,107,5,65,0,11,11,10,0,32,0,32,1,32,2,16,17,11,3,0,1,11,6,0,35,0,36,1,11,19,0,65,136,1,36,0,35,0,36,1,16,6,36,3,16,6,36,4,11,3,0,1,11,7,0,32,0,40,2,0,11,9,0,32,0,32,1,54,2,0,11,7,0,32,0,40,2,4,11,9,0,32,0,32,1,54,2,4,11,7,0,32,0,40,2,8,11,9,0,32,0,32,1,54,2,8,11,7,0,32,0,41,3,16,11,9,0,32,0,32,1,55,3,16,11,7,0,32,0,41,3,24,11,9,0,32,0,32,1,55,3,24,11,7,0,32,0,41,3,32,11,9,0,32,0,32,1,55,3,32,11,7,0,32,0,41,3,40,11,9,0,32,0,32,1,55,3,40,11,7,0,32,0,41,3,48,11,9,0,32,0,32,1,55,3,48,11,7,0,32,0,41,3,56,11,9,0,32,0,32,1,55,3,56,11,7,0,32,0,41,3,64,11,9,0,32,0,32,1,55,3,64,11,7,0,32,0,41,3,72,11,9,0,32,0,32,1,55,3,72,11,7,0,32,0,41,3,80,11,9,0,32,0,32,1,55,3,80,11,7,0,32,0,41,3,88,11,9,0,32,0,32,1,55,3,88,11,7,0,32,0,41,3,96,11,9,0,32,0,32,1,55,3,96,11,7,0,32,0,41,3,104,11,9,0,32,0,32,1,55,3,104,11,7,0,32,0,41,3,112,11,9,0,32,0,32,1,55,3,112,11,7,0,32,0,41,3,120,11,9,0,32,0,32,1,55,3,120,11,11,128,1,2,0,65,8,11,57,27,0,0,0,126,0,108,0,105,0,98,0,47,0,105,0,110,0,116,0,101,0,114,0,110,0,97,0,108,0,47,0,116,0,121,0,112,0,101,0,100,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,200,0,11,59,28,0,0,0,126,0,108,0,105,0,98,0,47,0,105,0,110,0,116,0,101,0,114,0,110,0,97,0,108,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,32,16,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,14,114,97,98,105,110,46,119,97,115,109,46,109,97,112]) // make it work async because browsers throw when a wasm module is bigger than 4kb and load sync return instantiateStreaming(new Response(new Blob([wasm], {type: 'application/wasm'})), imp) } module.exports = loadWebAssembly -},{"assemblyscript/lib/loader":76}],1550:[function(require,module,exports){ +},{"assemblyscript/lib/loader":25}],1364:[function(require,module,exports){ const Rabin = require('./rabin') const getRabin = require('../dist/rabin-wasm.node.js') @@ -201975,7 +150820,7 @@ module.exports = { create } -},{"../dist/rabin-wasm.node.js":1549,"./rabin":1551}],1551:[function(require,module,exports){ +},{"../dist/rabin-wasm.node.js":1363,"./rabin":1365}],1365:[function(require,module,exports){ /** * Rabin fingerprinting * @@ -202032,7 +150877,7 @@ class Rabin { } module.exports = Rabin -},{}],1552:[function(require,module,exports){ +},{}],1366:[function(require,module,exports){ (function (process,global){ 'use strict' @@ -202086,7 +150931,7 @@ function randomBytes (size, cb) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1438,"safe-buffer":1593}],1553:[function(require,module,exports){ +},{"_process":1258,"safe-buffer":1371}],1367:[function(require,module,exports){ (function (process,global){ 'use strict' @@ -202198,80 +151043,8159 @@ function randomFillSync (buf, offset, size) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1438,"randombytes":1552,"safe-buffer":1593}],1554:[function(require,module,exports){ -module.exports = window.crypto; -},{}],1555:[function(require,module,exports){ -module.exports = require('crypto'); -},{"crypto":1554}],1556:[function(require,module,exports){ -var randomHex = function(size, callback) { - var crypto = require('./crypto.js'); - var isCallback = (typeof callback === 'function'); +},{"_process":1258,"randombytes":1366,"safe-buffer":1371}],1368:[function(require,module,exports){ +'use strict' +var getTime = require('./time') - if (size > 65536) { - if(isCallback) { - callback(new Error('Requested too many random bytes.')); - } else { - throw new Error('Requested too many random bytes.'); - } - }; +function Retimer (callback, timeout, args) { + var that = this + this._started = getTime() + this._rescheduled = 0 + this._scheduled = timeout + this._args = args - // is node - if (typeof crypto !== 'undefined' && crypto.randomBytes) { + this._timer = setTimeout(timerWrapper, timeout) - if(isCallback) { - crypto.randomBytes(size, function(err, result){ - if(!err) { - callback(null, '0x'+ result.toString('hex')); - } else { - callback(error); - } - }) - } else { - return '0x'+ crypto.randomBytes(size).toString('hex'); - } - - // is browser + function timerWrapper () { + if (that._rescheduled > 0) { + that._scheduled = that._rescheduled - (getTime() - that._started) + that._timer = setTimeout(timerWrapper, that._scheduled) + that._rescheduled = 0 } else { - var cryptoLib; - - if (typeof crypto !== 'undefined') { - cryptoLib = crypto; - } else if(typeof msCrypto !== 'undefined') { - cryptoLib = msCrypto; - } - - if (cryptoLib && cryptoLib.getRandomValues) { - var randomBytes = cryptoLib.getRandomValues(new Uint8Array(size)); - var returnValue = '0x'+ Array.from(randomBytes).map(function(arr){ return arr.toString(16); }).join(''); - - if(isCallback) { - callback(null, returnValue); - } else { - return returnValue; - } - - // not crypto object - } else { - var error = new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.'); - - if(isCallback) { - callback(error); - } else { - throw error; - } - } + callback.apply(null, that._args) } + } +} + +Retimer.prototype.reschedule = function (timeout) { + var now = getTime() + if ((now + timeout) - (this._started + this._scheduled) < 0) { + return false + } else { + this._started = now + this._rescheduled = timeout + return true + } +} + +Retimer.prototype.clear = function () { + clearTimeout(this._timer) +} + +function retimer () { + if (typeof arguments[0] !== 'function') { + throw new Error('callback needed') + } + + if (typeof arguments[1] !== 'number') { + throw new Error('timeout needed') + } + + var args + + if (arguments.length > 0) { + args = new Array(arguments.length - 2) + + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 2] + } + } + + return new Retimer(arguments[0], arguments[1], args) +} + +module.exports = retimer + +},{"./time":1369}],1369:[function(require,module,exports){ +'use strict' + +module.exports = function getTime () { + return Date.now() +} + +},{}],1370:[function(require,module,exports){ +'use strict' +var Buffer = require('buffer').Buffer +var inherits = require('inherits') +var HashBase = require('hash-base') + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} + +module.exports = RIPEMD160 + +},{"buffer":181,"hash-base":293,"inherits":317}],1371:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +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) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +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) + } else { + buf.fill(fill) + } + } 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":181}],1372:[function(require,module,exports){ +/*jshint node:true*/ +'use strict'; + +/** + * Replaces characters in strings that are illegal/unsafe for filenames. + * Unsafe characters are either removed or replaced by a substitute set + * in the optional `options` object. + * + * Illegal Characters on Various Operating Systems + * / ? < > \ : * | " + * https://kb.acronis.com/content/39790 + * + * Unicode Control codes + * C0 0x00-0x1f & C1 (0x80-0x9f) + * http://en.wikipedia.org/wiki/C0_and_C1_control_codes + * + * Reserved filenames on Unix-based systems (".", "..") + * Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1", + * "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + * "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", and + * "LPT9") case-insesitively and with or without filename extensions. + * + * Capped at 255 characters in length. + * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs + * + * @param {String} input Original filename + * @param {Object} options {replacement: String} + * @return {String} Sanitized filename + */ + +var truncate = require("truncate-utf8-bytes"); + +var illegalRe = /[\/\?<>\\:\*\|":]/g; +var controlRe = /[\x00-\x1f\x80-\x9f]/g; +var reservedRe = /^\.+$/; +var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; +var windowsTrailingRe = /[\. ]+$/; + +function sanitize(input, replacement) { + var sanitized = input + .replace(illegalRe, replacement) + .replace(controlRe, replacement) + .replace(reservedRe, replacement) + .replace(windowsReservedRe, replacement) + .replace(windowsTrailingRe, replacement); + return truncate(sanitized, 255); +} + +module.exports = function (input, options) { + var replacement = (options && options.replacement) || ''; + var output = sanitize(input, replacement); + if (replacement === '') { + return output; + } + return sanitize(output, ''); +}; + +},{"truncate-utf8-bytes":1503}],1373:[function(require,module,exports){ +'use strict' +module.exports = require('./lib')(require('./lib/js')) + +},{"./lib":1376,"./lib/js":1382}],1374:[function(require,module,exports){ +(function (Buffer){ +'use strict' +var toString = Object.prototype.toString + +// TypeError +exports.isArray = function (value, message) { + if (!Array.isArray(value)) throw TypeError(message) +} + +exports.isBoolean = function (value, message) { + if (toString.call(value) !== '[object Boolean]') throw TypeError(message) +} + +exports.isBuffer = function (value, message) { + if (!Buffer.isBuffer(value)) throw TypeError(message) +} + +exports.isFunction = function (value, message) { + if (toString.call(value) !== '[object Function]') throw TypeError(message) +} + +exports.isNumber = function (value, message) { + if (toString.call(value) !== '[object Number]') throw TypeError(message) +} + +exports.isObject = function (value, message) { + if (toString.call(value) !== '[object Object]') throw TypeError(message) +} + +// RangeError +exports.isBufferLength = function (buffer, length, message) { + if (buffer.length !== length) throw RangeError(message) +} + +exports.isBufferLength2 = function (buffer, length1, length2, message) { + if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message) +} + +exports.isLengthGTZero = function (value, message) { + if (value.length === 0) throw RangeError(message) +} + +exports.isNumberInInterval = function (number, x, y, message) { + if (number <= x || number >= y) throw RangeError(message) +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":608}],1375:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var bip66 = require('bip66') + +var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([ + // begin + 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 +]) + +var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ + // begin + 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, + 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, + 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 +]) + +exports.privateKeyExport = function (privateKey, publicKey, compressed) { + var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED) + privateKey.copy(result, compressed ? 8 : 9) + publicKey.copy(result, compressed ? 181 : 214) + return result +} + +exports.privateKeyImport = function (privateKey) { + var length = privateKey.length + + // sequence header + var index = 0 + if (length < index + 1 || privateKey[index] !== 0x30) return + index += 1 + + // sequence length constructor + if (length < index + 1 || !(privateKey[index] & 0x80)) return + + var lenb = privateKey[index] & 0x7f + index += 1 + if (lenb < 1 || lenb > 2) return + if (length < index + lenb) return + + // sequence length + var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) + index += lenb + if (length < index + len) return + + // sequence element 0: version number (=1) + if (length < index + 3 || + privateKey[index] !== 0x02 || + privateKey[index + 1] !== 0x01 || + privateKey[index + 2] !== 0x01) { + return + } + index += 3 + + // sequence element 1: octet string, up to 32 bytes + if (length < index + 2 || + privateKey[index] !== 0x04 || + privateKey[index + 1] > 0x20 || + length < index + 2 + privateKey[index + 1]) { + return + } + + return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) +} + +exports.signatureExport = function (sigObj) { + var r = Buffer.concat([Buffer.from([0]), sigObj.r]) + for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR); + + var s = Buffer.concat([Buffer.from([0]), sigObj.s]) + for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); + + return bip66.encode(r.slice(posR), s.slice(posS)) +} + +exports.signatureImport = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + try { + var sigObj = bip66.decode(sig) + if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) + if (sigObj.r.length > 32) throw new Error('R length is too long') + if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) + if (sigObj.s.length > 32) throw new Error('S length is too long') + } catch (err) { + return + } + + sigObj.r.copy(r, 32 - sigObj.r.length) + sigObj.s.copy(s, 32 - sigObj.s.length) + + return { r: r, s: s } +} + +exports.signatureImportLax = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + var length = sig.length + var index = 0 + + // sequence tag byte + if (sig[index++] !== 0x30) return + + // sequence length byte + var lenbyte = sig[index++] + if (lenbyte & 0x80) { + index += lenbyte - 0x80 + if (index > length) return + } + + // sequence tag byte for r + if (sig[index++] !== 0x02) return + + // length for r + var rlen = sig[index++] + if (rlen & 0x80) { + lenbyte = rlen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] + } + if (rlen > length - index) return + var rindex = index + index += rlen + + // sequence tag byte for s + if (sig[index++] !== 0x02) return + + // length for s + var slen = sig[index++] + if (slen & 0x80) { + lenbyte = slen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] + } + if (slen > length - index) return + var sindex = index + index += slen + + // ignore leading zeros in r + for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); + // copy r value + if (rlen > 32) return + var rvalue = sig.slice(rindex, rindex + rlen) + rvalue.copy(r, 32 - rvalue.length) + + // ignore leading zeros in s + for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); + // copy s value + if (slen > 32) return + var svalue = sig.slice(sindex, sindex + slen) + svalue.copy(s, 32 - svalue.length) + + return { r: r, s: s } +} + +},{"bip66":111,"safe-buffer":1371}],1376:[function(require,module,exports){ +'use strict' +var assert = require('./assert') +var der = require('./der') +var messages = require('./messages.json') + +function initCompressedValue (value, defaultValue) { + if (value === undefined) return defaultValue + + assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID) + return value +} + +module.exports = function (secp256k1) { + return { + privateKeyVerify: function (privateKey) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey) + }, + + privateKeyExport: function (privateKey, compressed) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + var publicKey = secp256k1.privateKeyExport(privateKey, compressed) + + return der.privateKeyExport(privateKey, publicKey, compressed) + }, + + privateKeyImport: function (privateKey) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + + privateKey = der.privateKeyImport(privateKey) + if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey + + throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL) + }, + + privateKeyNegate: function (privateKey) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + return secp256k1.privateKeyNegate(privateKey) + }, + + privateKeyModInverse: function (privateKey) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + return secp256k1.privateKeyModInverse(privateKey) + }, + + privateKeyTweakAdd: function (privateKey, tweak) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) + assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) + + return secp256k1.privateKeyTweakAdd(privateKey, tweak) + }, + + privateKeyTweakMul: function (privateKey, tweak) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) + assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) + + return secp256k1.privateKeyTweakMul(privateKey, tweak) + }, + + publicKeyCreate: function (privateKey, compressed) { + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyCreate(privateKey, compressed) + }, + + publicKeyConvert: function (publicKey, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyConvert(publicKey, compressed) + }, + + publicKeyVerify: function (publicKey) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + return secp256k1.publicKeyVerify(publicKey) + }, + + publicKeyTweakAdd: function (publicKey, tweak, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) + assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed) + }, + + publicKeyTweakMul: function (publicKey, tweak, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) + assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed) + }, + + publicKeyCombine: function (publicKeys, compressed) { + assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID) + assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID) + for (var i = 0; i < publicKeys.length; ++i) { + assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + } + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyCombine(publicKeys, compressed) + }, + + signatureNormalize: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + return secp256k1.signatureNormalize(signature) + }, + + signatureExport: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = secp256k1.signatureExport(signature) + return der.signatureExport(sigObj) + }, + + signatureImport: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImport(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + signatureImportLax: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImportLax(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + sign: function (message, privateKey, options) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + var data = null + var noncefn = null + if (options !== undefined) { + assert.isObject(options, messages.OPTIONS_TYPE_INVALID) + + if (options.data !== undefined) { + assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) + assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) + data = options.data + } + + if (options.noncefn !== undefined) { + assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) + noncefn = options.noncefn + } + } + + return secp256k1.sign(message, privateKey, noncefn, data) + }, + + verify: function (message, signature, publicKey) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + return secp256k1.verify(message, signature, publicKey) + }, + + recover: function (message, signature, recovery, compressed) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) + assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.recover(message, signature, recovery, compressed) + }, + + ecdh: function (publicKey, privateKey) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + return secp256k1.ecdh(publicKey, privateKey) + }, + + ecdhUnsafe: function (publicKey, privateKey, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) + } + } +} + +},{"./assert":1374,"./der":1375,"./messages.json":1383}],1377:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var optimized = require('./optimized') + +function BN () { + this.negative = 0 + this.words = null + this.length = 0 +} + +BN.fromNumber = function (n) { + var bn = new BN() + bn.words = [n & 0x03ffffff] + bn.length = 1 + return bn +} + +BN.fromBuffer = function (b32) { + var bn = new BN() + + bn.words = new Array(10) + bn.words[0] = (b32[28] & 0x03) << 24 | b32[29] << 16 | b32[30] << 8 | b32[31] + bn.words[1] = (b32[25] & 0x0F) << 22 | b32[26] << 14 | b32[27] << 6 | b32[28] >>> 2 + bn.words[2] = (b32[22] & 0x3F) << 20 | b32[23] << 12 | b32[24] << 4 | b32[25] >>> 4 + bn.words[3] = (b32[19] & 0xFF) << 18 | b32[20] << 10 | b32[21] << 2 | b32[22] >>> 6 + + bn.words[4] = (b32[15] & 0x03) << 24 | b32[16] << 16 | b32[17] << 8 | b32[18] + bn.words[5] = (b32[12] & 0x0F) << 22 | b32[13] << 14 | b32[14] << 6 | b32[15] >>> 2 + bn.words[6] = (b32[9] & 0x3F) << 20 | b32[10] << 12 | b32[11] << 4 | b32[12] >>> 4 + bn.words[7] = (b32[6] & 0xFF) << 18 | b32[7] << 10 | b32[8] << 2 | b32[9] >>> 6 + + bn.words[8] = (b32[2] & 0x03) << 24 | b32[3] << 16 | b32[4] << 8 | b32[5] + bn.words[9] = b32[0] << 14 | b32[1] << 6 | b32[2] >>> 2 + + bn.length = 10 + return bn.strip() +} + +BN.prototype.toBuffer = function () { + var w = this.words + for (var i = this.length; i < 10; ++i) w[i] = 0 + + return Buffer.from([ + (w[9] >>> 14) & 0xFF, (w[9] >>> 6) & 0xFF, (w[9] & 0x3F) << 2 | ((w[8] >>> 24) & 0x03), // 0, 1, 2 + (w[8] >>> 16) & 0xFF, (w[8] >>> 8) & 0xFF, w[8] & 0xFF, // 3, 4, 5 + + (w[7] >>> 18) & 0xFF, (w[7] >>> 10) & 0xFF, (w[7] >>> 2) & 0xFF, // 6, 7, 8 + ((w[7] & 0x03) << 6) | ((w[6] >>> 20) & 0x3F), (w[6] >>> 12) & 0xFF, (w[6] >>> 4) & 0xFF, // 9, 10, 11 + ((w[6] & 0x0F) << 4) | ((w[5] >>> 22) & 0x0F), (w[5] >>> 14) & 0xFF, (w[5] >>> 6) & 0xFF, // 12, 13, 14 + ((w[5] & 0x3F) << 2) | ((w[4] >>> 24) & 0x03), (w[4] >>> 16) & 0xFF, (w[4] >>> 8) & 0xFF, w[4] & 0xFF, // 15, 16, 17, 18 + + (w[3] >>> 18) & 0xFF, (w[3] >>> 10) & 0xFF, (w[3] >>> 2) & 0xFF, // 19, 20, 21 + ((w[3] & 0x03) << 6) | ((w[2] >>> 20) & 0x3F), (w[2] >>> 12) & 0xFF, (w[2] >>> 4) & 0xFF, // 22, 23, 24 + ((w[2] & 0x0F) << 4) | ((w[1] >>> 22) & 0x0F), (w[1] >>> 14) & 0xFF, (w[1] >>> 6) & 0xFF, // 25, 26, 27 + ((w[1] & 0x3F) << 2) | ((w[0] >>> 24) & 0x03), (w[0] >>> 16) & 0xFF, (w[0] >>> 8) & 0xFF, w[0] & 0xFF // 28, 29, 30, 31 + ]) +} + +BN.prototype.clone = function () { + var r = new BN() + r.words = new Array(this.length) + for (var i = 0; i < this.length; i++) r.words[i] = this.words[i] + r.length = this.length + r.negative = this.negative + return r +} + +BN.prototype.strip = function () { + while (this.length > 1 && (this.words[this.length - 1] | 0) === 0) this.length-- + return this +} + +BN.prototype.normSign = function () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) this.negative = 0 + return this +} + +BN.prototype.isEven = function () { + return (this.words[0] & 1) === 0 +} + +BN.prototype.isOdd = function () { + return (this.words[0] & 1) === 1 +} + +BN.prototype.isZero = function () { + return this.length === 1 && this.words[0] === 0 +} + +BN.prototype.ucmp = function (num) { + if (this.length !== num.length) return this.length > num.length ? 1 : -1 + + for (var i = this.length - 1; i >= 0; --i) { + if (this.words[i] !== num.words[i]) return this.words[i] > num.words[i] ? 1 : -1 + } + + return 0 +} + +BN.prototype.gtOne = function () { + return this.length > 1 || this.words[0] > 1 +} + +BN.prototype.isOverflow = function () { + return this.ucmp(BN.n) >= 0 +} + +BN.prototype.isHigh = function () { + return this.ucmp(BN.nh) === 1 +} + +BN.prototype.bitLengthGT256 = function () { + return this.length > 10 || (this.length === 10 && this.words[9] > 0x003fffff) +} + +BN.prototype.iuaddn = function (num) { + this.words[0] += num + + for (var i = 0; this.words[i] > 0x03ffffff && i < this.length; ++i) { + this.words[i] -= 0x04000000 + this.words[i + 1] += 1 + } + + if (i === this.length) { + this.words[i] = 1 + this.length += 1 + } + + return this +} + +BN.prototype.iadd = function (num) { + // (-this) + num -> -(this - num) + // this + (-num) -> this - num + if (this.negative !== num.negative) { + if (this.negative !== 0) { + this.negative = 0 + this.isub(num) + this.negative ^= 1 + } else { + num.negative = 0 + this.isub(num) + num.negative = 1 + } + + return this.normSign() + } + + // a.length > b.length + var a + var b + if (this.length > num.length) { + a = this + b = num + } else { + a = num + b = this + } + + for (var i = 0, carry = 0; i < b.length; ++i) { + var word = a.words[i] + b.words[i] + carry + this.words[i] = word & 0x03ffffff + carry = word >>> 26 + } + + for (; carry !== 0 && i < a.length; ++i) { + word = a.words[i] + carry + this.words[i] = word & 0x03ffffff + carry = word >>> 26 + } + + this.length = a.length + if (carry !== 0) { + this.words[this.length++] = carry + } else if (a !== this) { + for (; i < a.length; ++i) { + this.words[i] = a.words[i] + } + } + + return this +} + +BN.prototype.add = function (num) { + return this.clone().iadd(num) +} + +BN.prototype.isub = function (num) { + // (-this) - num -> -(this + num) + // this - (-num) -> this + num + if (this.negative !== num.negative) { + if (this.negative !== 0) { + this.negative = 0 + this.iadd(num) + this.negative = 1 + } else { + num.negative = 0 + this.iadd(num) + num.negative = 1 + } + + return this.normSign() + } + + var cmp = this.ucmp(num) + if (cmp === 0) { + this.negative = 0 + this.words[0] = 0 + this.length = 1 + return this + } + + // a > b + var a + var b + if (cmp > 0) { + a = this + b = num + } else { + a = num + b = this + } + + for (var i = 0, carry = 0; i < b.length; ++i) { + var word = a.words[i] - b.words[i] + carry + carry = word >> 26 + this.words[i] = word & 0x03ffffff + } + + for (; carry !== 0 && i < a.length; ++i) { + word = a.words[i] + carry + carry = word >> 26 + this.words[i] = word & 0x03ffffff + } + + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; ++i) this.words[i] = a.words[i] + } + + this.length = Math.max(this.length, i) + + if (a !== this) this.negative ^= 1 + + return this.strip().normSign() +} + +BN.prototype.sub = function (num) { + return this.clone().isub(num) +} + +BN.umulTo = function (num1, num2, out) { + out.length = num1.length + num2.length - 1 + + var a1 = num1.words[0] + var b1 = num2.words[0] + var r1 = a1 * b1 + + var carry = (r1 / 0x04000000) | 0 + out.words[0] = r1 & 0x03ffffff + + for (var k = 1, maxK = out.length; k < maxK; k++) { + var ncarry = carry >>> 26 + var rword = carry & 0x03ffffff + for (var j = Math.max(0, k - num1.length + 1), maxJ = Math.min(k, num2.length - 1); j <= maxJ; j++) { + var i = k - j + var a = num1.words[i] + var b = num2.words[j] + var r = a * b + rword + ncarry += (r / 0x04000000) | 0 + rword = r & 0x03ffffff + } + out.words[k] = rword + carry = ncarry + } + + if (carry !== 0) out.words[out.length++] = carry + + return out.strip() +} + +BN.umulTo10x10 = Math.imul ? optimized.umulTo10x10 : BN.umulTo + +BN.umulnTo = function (num, k, out) { + if (k === 0) { + out.words = [0] + out.length = 1 + return out + } + + for (var i = 0, carry = 0; i < num.length; ++i) { + var r = num.words[i] * k + carry + out.words[i] = r & 0x03ffffff + carry = (r / 0x04000000) | 0 + } + + if (carry > 0) { + out.words[i] = carry + out.length = num.length + 1 + } else { + out.length = num.length + } + + return out +} + +BN.prototype.umul = function (num) { + var out = new BN() + out.words = new Array(this.length + num.length) + + if (this.length === 10 && num.length === 10) { + return BN.umulTo10x10(this, num, out) + } else if (this.length === 1) { + return BN.umulnTo(num, this.words[0], out) + } else if (num.length === 1) { + return BN.umulnTo(this, num.words[0], out) + } else { + return BN.umulTo(this, num, out) + } +} + +BN.prototype.isplit = function (output) { + output.length = Math.min(this.length, 9) + for (var i = 0; i < output.length; ++i) output.words[i] = this.words[i] + + if (this.length <= 9) { + this.words[0] = 0 + this.length = 1 + return this + } + + // Shift by 9 limbs + var prev = this.words[9] + output.words[output.length++] = prev & 0x003fffff + + for (i = 10; i < this.length; ++i) { + var word = this.words[i] + this.words[i - 10] = ((word & 0x003fffff) << 4) | (prev >>> 22) + prev = word + } + prev >>>= 22 + this.words[i - 10] = prev + + if (prev === 0 && this.length > 10) { + this.length -= 10 + } else { + this.length -= 9 + } + + return this +} + +BN.prototype.fireduce = function () { + if (this.isOverflow()) this.isub(BN.n) + return this +} + +BN.prototype.ureduce = function () { + var num = this.clone().isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) + if (num.bitLengthGT256()) { + num = num.isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) + if (num.bitLengthGT256()) num = num.isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) + } + + return num.fireduce() +} + +BN.prototype.ishrn = function (n) { + var mask = (1 << n) - 1 + var m = 26 - n + + for (var i = this.length - 1, carry = 0; i >= 0; --i) { + var word = this.words[i] + this.words[i] = (carry << m) | (word >>> n) + carry = word & mask + } + + if (this.length > 1 && this.words[this.length - 1] === 0) this.length -= 1 + + return this +} + +BN.prototype.uinvm = function () { + var x = this.clone() + var y = BN.n.clone() + + // A * x + B * y = x + var A = BN.fromNumber(1) + var B = BN.fromNumber(0) + + // C * x + D * y = y + var C = BN.fromNumber(0) + var D = BN.fromNumber(1) + + while (x.isEven() && y.isEven()) { + for (var k = 1, m = 1; (x.words[0] & m) === 0 && (y.words[0] & m) === 0 && k < 26; ++k, m <<= 1); + x.ishrn(k) + y.ishrn(k) + } + + var yp = y.clone() + var xp = x.clone() + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.ishrn(i) + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp) + B.isub(xp) + } + + A.ishrn(1) + B.ishrn(1) + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.ishrn(j) + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp) + D.isub(xp) + } + + C.ishrn(1) + D.ishrn(1) + } + } + + if (x.ucmp(y) >= 0) { + x.isub(y) + A.isub(C) + B.isub(D) + } else { + y.isub(x) + C.isub(A) + D.isub(B) + } + } + + if (C.negative === 1) { + C.negative = 0 + var result = C.ureduce() + result.negative ^= 1 + return result.normSign().iadd(BN.n) + } else { + return C.ureduce() + } +} + +BN.prototype.imulK = function () { + this.words[this.length] = 0 + this.words[this.length + 1] = 0 + this.length += 2 + + for (var i = 0, lo = 0; i < this.length; ++i) { + var w = this.words[i] | 0 + lo += w * 0x3d1 + this.words[i] = lo & 0x03ffffff + lo = w * 0x40 + ((lo / 0x04000000) | 0) + } + + if (this.words[this.length - 1] === 0) { + this.length -= 1 + if (this.words[this.length - 1] === 0) this.length -= 1 + } + + return this +} + +BN.prototype.redIReduce = function () { + this.isplit(BN.tmp).imulK().iadd(BN.tmp) + if (this.bitLengthGT256()) this.isplit(BN.tmp).imulK().iadd(BN.tmp) + + var cmp = this.ucmp(BN.p) + if (cmp === 0) { + this.words[0] = 0 + this.length = 1 + } else if (cmp > 0) { + this.isub(BN.p) + } else { + this.strip() + } + + return this +} + +BN.prototype.redNeg = function () { + if (this.isZero()) return BN.fromNumber(0) + + return BN.p.sub(this) +} + +BN.prototype.redAdd = function (num) { + return this.clone().redIAdd(num) +} + +BN.prototype.redIAdd = function (num) { + this.iadd(num) + if (this.ucmp(BN.p) >= 0) this.isub(BN.p) + + return this +} + +BN.prototype.redIAdd7 = function () { + this.iuaddn(7) + if (this.ucmp(BN.p) >= 0) this.isub(BN.p) + + return this +} + +BN.prototype.redSub = function (num) { + return this.clone().redISub(num) +} + +BN.prototype.redISub = function (num) { + this.isub(num) + if (this.negative !== 0) this.iadd(BN.p) + + return this +} + +BN.prototype.redMul = function (num) { + return this.umul(num).redIReduce() +} + +BN.prototype.redSqr = function () { + return this.umul(this).redIReduce() +} + +BN.prototype.redSqrt = function () { + if (this.isZero()) return this.clone() + + var wv2 = this.redSqr() + var wv4 = wv2.redSqr() + var wv12 = wv4.redSqr().redMul(wv4) + var wv14 = wv12.redMul(wv2) + var wv15 = wv14.redMul(this) + + var out = wv15 + for (var i = 0; i < 54; ++i) out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv15) + out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv14) + for (i = 0; i < 5; ++i) out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv15) + out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv12) + out = out.redSqr().redSqr().redSqr().redSqr().redSqr().redSqr().redMul(wv12) + + if (out.redSqr().ucmp(this) === 0) { + return out + } else { + return null + } +} + +BN.prototype.redInvm = function () { + var a = this.clone() + var b = BN.p.clone() + + var x1 = BN.fromNumber(1) + var x2 = BN.fromNumber(0) + + while (a.gtOne() && b.gtOne()) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.ishrn(i) + while (i-- > 0) { + if (x1.isOdd()) x1.iadd(BN.p) + x1.ishrn(1) + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.ishrn(j) + while (j-- > 0) { + if (x2.isOdd()) x2.iadd(BN.p) + x2.ishrn(1) + } + } + + if (a.ucmp(b) >= 0) { + a.isub(b) + x1.isub(x2) + } else { + b.isub(a) + x2.isub(x1) + } + } + + var res + if (a.length === 1 && a.words[0] === 1) { + res = x1 + } else { + res = x2 + } + + if (res.negative !== 0) res.iadd(BN.p) + + if (res.negative !== 0) { + res.negative = 0 + return res.redIReduce().redNeg() + } else { + return res.redIReduce() + } +} + +BN.prototype.getNAF = function (w) { + var naf = [] + var ws = 1 << (w + 1) + var wsm1 = ws - 1 + var ws2 = ws >> 1 + + var k = this.clone() + while (!k.isZero()) { + for (var i = 0, m = 1; (k.words[0] & m) === 0 && i < 26; ++i, m <<= 1) naf.push(0) + + if (i !== 0) { + k.ishrn(i) + } else { + var mod = k.words[0] & wsm1 + if (mod >= ws2) { + naf.push(ws2 - mod) + k.iuaddn(mod - ws2).ishrn(1) + } else { + naf.push(mod) + k.words[0] -= mod + if (!k.isZero()) { + for (i = w - 1; i > 0; --i) naf.push(0) + k.ishrn(w) + } + } + } + } + + return naf +} + +BN.prototype.inspect = function () { + if (this.isZero()) return '0' + + var buffer = this.toBuffer().toString('hex') + for (var i = 0; buffer[i] === '0'; ++i); + return buffer.slice(i) +} + +BN.n = BN.fromBuffer(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', 'hex')) +BN.nh = BN.n.clone().ishrn(1) +BN.nc = BN.fromBuffer(Buffer.from('000000000000000000000000000000014551231950B75FC4402DA1732FC9BEBF', 'hex')) +BN.p = BN.fromBuffer(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F', 'hex')) +BN.psn = BN.p.sub(BN.n) +BN.tmp = new BN() +BN.tmp.words = new Array(10) + +// WTF?! it speed-up benchmark on ~20% +;(function () { + var x = BN.fromNumber(1) + x.words[3] = 0 +})() + +module.exports = BN + +},{"./optimized":1378,"safe-buffer":1371}],1378:[function(require,module,exports){ +'use strict' +exports.umulTo10x10 = function (num1, num2, out) { + var a = num1.words + var b = num2.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.length = 19 + /* k = 0 */ + lo = Math.imul(al0, bl0) + mid = Math.imul(al0, bh0) + mid += Math.imul(ah0, bl0) + hi = Math.imul(ah0, bh0) + var w0 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w0 >>> 26) + w0 &= 0x3ffffff + /* k = 1 */ + lo = Math.imul(al1, bl0) + mid = Math.imul(al1, bh0) + mid += Math.imul(ah1, bl0) + hi = Math.imul(ah1, bh0) + lo += Math.imul(al0, bl1) + mid += Math.imul(al0, bh1) + mid += Math.imul(ah0, bl1) + hi += Math.imul(ah0, bh1) + var w1 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w1 >>> 26) + w1 &= 0x3ffffff + /* k = 2 */ + lo = Math.imul(al2, bl0) + mid = Math.imul(al2, bh0) + mid += Math.imul(ah2, bl0) + hi = Math.imul(ah2, bh0) + lo += Math.imul(al1, bl1) + mid += Math.imul(al1, bh1) + mid += Math.imul(ah1, bl1) + hi += Math.imul(ah1, bh1) + lo += Math.imul(al0, bl2) + mid += Math.imul(al0, bh2) + mid += Math.imul(ah0, bl2) + hi += Math.imul(ah0, bh2) + var w2 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w2 >>> 26) + w2 &= 0x3ffffff + /* k = 3 */ + lo = Math.imul(al3, bl0) + mid = Math.imul(al3, bh0) + mid += Math.imul(ah3, bl0) + hi = Math.imul(ah3, bh0) + lo += Math.imul(al2, bl1) + mid += Math.imul(al2, bh1) + mid += Math.imul(ah2, bl1) + hi += Math.imul(ah2, bh1) + lo += Math.imul(al1, bl2) + mid += Math.imul(al1, bh2) + mid += Math.imul(ah1, bl2) + hi += Math.imul(ah1, bh2) + lo += Math.imul(al0, bl3) + mid += Math.imul(al0, bh3) + mid += Math.imul(ah0, bl3) + hi += Math.imul(ah0, bh3) + var w3 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w3 >>> 26) + w3 &= 0x3ffffff + /* k = 4 */ + lo = Math.imul(al4, bl0) + mid = Math.imul(al4, bh0) + mid += Math.imul(ah4, bl0) + hi = Math.imul(ah4, bh0) + lo += Math.imul(al3, bl1) + mid += Math.imul(al3, bh1) + mid += Math.imul(ah3, bl1) + hi += Math.imul(ah3, bh1) + lo += Math.imul(al2, bl2) + mid += Math.imul(al2, bh2) + mid += Math.imul(ah2, bl2) + hi += Math.imul(ah2, bh2) + lo += Math.imul(al1, bl3) + mid += Math.imul(al1, bh3) + mid += Math.imul(ah1, bl3) + hi += Math.imul(ah1, bh3) + lo += Math.imul(al0, bl4) + mid += Math.imul(al0, bh4) + mid += Math.imul(ah0, bl4) + hi += Math.imul(ah0, bh4) + var w4 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w4 >>> 26) + w4 &= 0x3ffffff + /* k = 5 */ + lo = Math.imul(al5, bl0) + mid = Math.imul(al5, bh0) + mid += Math.imul(ah5, bl0) + hi = Math.imul(ah5, bh0) + lo += Math.imul(al4, bl1) + mid += Math.imul(al4, bh1) + mid += Math.imul(ah4, bl1) + hi += Math.imul(ah4, bh1) + lo += Math.imul(al3, bl2) + mid += Math.imul(al3, bh2) + mid += Math.imul(ah3, bl2) + hi += Math.imul(ah3, bh2) + lo += Math.imul(al2, bl3) + mid += Math.imul(al2, bh3) + mid += Math.imul(ah2, bl3) + hi += Math.imul(ah2, bh3) + lo += Math.imul(al1, bl4) + mid += Math.imul(al1, bh4) + mid += Math.imul(ah1, bl4) + hi += Math.imul(ah1, bh4) + lo += Math.imul(al0, bl5) + mid += Math.imul(al0, bh5) + mid += Math.imul(ah0, bl5) + hi += Math.imul(ah0, bh5) + var w5 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w5 >>> 26) + w5 &= 0x3ffffff + /* k = 6 */ + lo = Math.imul(al6, bl0) + mid = Math.imul(al6, bh0) + mid += Math.imul(ah6, bl0) + hi = Math.imul(ah6, bh0) + lo += Math.imul(al5, bl1) + mid += Math.imul(al5, bh1) + mid += Math.imul(ah5, bl1) + hi += Math.imul(ah5, bh1) + lo += Math.imul(al4, bl2) + mid += Math.imul(al4, bh2) + mid += Math.imul(ah4, bl2) + hi += Math.imul(ah4, bh2) + lo += Math.imul(al3, bl3) + mid += Math.imul(al3, bh3) + mid += Math.imul(ah3, bl3) + hi += Math.imul(ah3, bh3) + lo += Math.imul(al2, bl4) + mid += Math.imul(al2, bh4) + mid += Math.imul(ah2, bl4) + hi += Math.imul(ah2, bh4) + lo += Math.imul(al1, bl5) + mid += Math.imul(al1, bh5) + mid += Math.imul(ah1, bl5) + hi += Math.imul(ah1, bh5) + lo += Math.imul(al0, bl6) + mid += Math.imul(al0, bh6) + mid += Math.imul(ah0, bl6) + hi += Math.imul(ah0, bh6) + var w6 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w6 >>> 26) + w6 &= 0x3ffffff + /* k = 7 */ + lo = Math.imul(al7, bl0) + mid = Math.imul(al7, bh0) + mid += Math.imul(ah7, bl0) + hi = Math.imul(ah7, bh0) + lo += Math.imul(al6, bl1) + mid += Math.imul(al6, bh1) + mid += Math.imul(ah6, bl1) + hi += Math.imul(ah6, bh1) + lo += Math.imul(al5, bl2) + mid += Math.imul(al5, bh2) + mid += Math.imul(ah5, bl2) + hi += Math.imul(ah5, bh2) + lo += Math.imul(al4, bl3) + mid += Math.imul(al4, bh3) + mid += Math.imul(ah4, bl3) + hi += Math.imul(ah4, bh3) + lo += Math.imul(al3, bl4) + mid += Math.imul(al3, bh4) + mid += Math.imul(ah3, bl4) + hi += Math.imul(ah3, bh4) + lo += Math.imul(al2, bl5) + mid += Math.imul(al2, bh5) + mid += Math.imul(ah2, bl5) + hi += Math.imul(ah2, bh5) + lo += Math.imul(al1, bl6) + mid += Math.imul(al1, bh6) + mid += Math.imul(ah1, bl6) + hi += Math.imul(ah1, bh6) + lo += Math.imul(al0, bl7) + mid += Math.imul(al0, bh7) + mid += Math.imul(ah0, bl7) + hi += Math.imul(ah0, bh7) + var w7 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w7 >>> 26) + w7 &= 0x3ffffff + /* k = 8 */ + lo = Math.imul(al8, bl0) + mid = Math.imul(al8, bh0) + mid += Math.imul(ah8, bl0) + hi = Math.imul(ah8, bh0) + lo += Math.imul(al7, bl1) + mid += Math.imul(al7, bh1) + mid += Math.imul(ah7, bl1) + hi += Math.imul(ah7, bh1) + lo += Math.imul(al6, bl2) + mid += Math.imul(al6, bh2) + mid += Math.imul(ah6, bl2) + hi += Math.imul(ah6, bh2) + lo += Math.imul(al5, bl3) + mid += Math.imul(al5, bh3) + mid += Math.imul(ah5, bl3) + hi += Math.imul(ah5, bh3) + lo += Math.imul(al4, bl4) + mid += Math.imul(al4, bh4) + mid += Math.imul(ah4, bl4) + hi += Math.imul(ah4, bh4) + lo += Math.imul(al3, bl5) + mid += Math.imul(al3, bh5) + mid += Math.imul(ah3, bl5) + hi += Math.imul(ah3, bh5) + lo += Math.imul(al2, bl6) + mid += Math.imul(al2, bh6) + mid += Math.imul(ah2, bl6) + hi += Math.imul(ah2, bh6) + lo += Math.imul(al1, bl7) + mid += Math.imul(al1, bh7) + mid += Math.imul(ah1, bl7) + hi += Math.imul(ah1, bh7) + lo += Math.imul(al0, bl8) + mid += Math.imul(al0, bh8) + mid += Math.imul(ah0, bl8) + hi += Math.imul(ah0, bh8) + var w8 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w8 >>> 26) + w8 &= 0x3ffffff + /* k = 9 */ + lo = Math.imul(al9, bl0) + mid = Math.imul(al9, bh0) + mid += Math.imul(ah9, bl0) + hi = Math.imul(ah9, bh0) + lo += Math.imul(al8, bl1) + mid += Math.imul(al8, bh1) + mid += Math.imul(ah8, bl1) + hi += Math.imul(ah8, bh1) + lo += Math.imul(al7, bl2) + mid += Math.imul(al7, bh2) + mid += Math.imul(ah7, bl2) + hi += Math.imul(ah7, bh2) + lo += Math.imul(al6, bl3) + mid += Math.imul(al6, bh3) + mid += Math.imul(ah6, bl3) + hi += Math.imul(ah6, bh3) + lo += Math.imul(al5, bl4) + mid += Math.imul(al5, bh4) + mid += Math.imul(ah5, bl4) + hi += Math.imul(ah5, bh4) + lo += Math.imul(al4, bl5) + mid += Math.imul(al4, bh5) + mid += Math.imul(ah4, bl5) + hi += Math.imul(ah4, bh5) + lo += Math.imul(al3, bl6) + mid += Math.imul(al3, bh6) + mid += Math.imul(ah3, bl6) + hi += Math.imul(ah3, bh6) + lo += Math.imul(al2, bl7) + mid += Math.imul(al2, bh7) + mid += Math.imul(ah2, bl7) + hi += Math.imul(ah2, bh7) + lo += Math.imul(al1, bl8) + mid += Math.imul(al1, bh8) + mid += Math.imul(ah1, bl8) + hi += Math.imul(ah1, bh8) + lo += Math.imul(al0, bl9) + mid += Math.imul(al0, bh9) + mid += Math.imul(ah0, bl9) + hi += Math.imul(ah0, bh9) + var w9 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w9 >>> 26) + w9 &= 0x3ffffff + /* k = 10 */ + lo = Math.imul(al9, bl1) + mid = Math.imul(al9, bh1) + mid += Math.imul(ah9, bl1) + hi = Math.imul(ah9, bh1) + lo += Math.imul(al8, bl2) + mid += Math.imul(al8, bh2) + mid += Math.imul(ah8, bl2) + hi += Math.imul(ah8, bh2) + lo += Math.imul(al7, bl3) + mid += Math.imul(al7, bh3) + mid += Math.imul(ah7, bl3) + hi += Math.imul(ah7, bh3) + lo += Math.imul(al6, bl4) + mid += Math.imul(al6, bh4) + mid += Math.imul(ah6, bl4) + hi += Math.imul(ah6, bh4) + lo += Math.imul(al5, bl5) + mid += Math.imul(al5, bh5) + mid += Math.imul(ah5, bl5) + hi += Math.imul(ah5, bh5) + lo += Math.imul(al4, bl6) + mid += Math.imul(al4, bh6) + mid += Math.imul(ah4, bl6) + hi += Math.imul(ah4, bh6) + lo += Math.imul(al3, bl7) + mid += Math.imul(al3, bh7) + mid += Math.imul(ah3, bl7) + hi += Math.imul(ah3, bh7) + lo += Math.imul(al2, bl8) + mid += Math.imul(al2, bh8) + mid += Math.imul(ah2, bl8) + hi += Math.imul(ah2, bh8) + lo += Math.imul(al1, bl9) + mid += Math.imul(al1, bh9) + mid += Math.imul(ah1, bl9) + hi += Math.imul(ah1, bh9) + var w10 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w10 >>> 26) + w10 &= 0x3ffffff + /* k = 11 */ + lo = Math.imul(al9, bl2) + mid = Math.imul(al9, bh2) + mid += Math.imul(ah9, bl2) + hi = Math.imul(ah9, bh2) + lo += Math.imul(al8, bl3) + mid += Math.imul(al8, bh3) + mid += Math.imul(ah8, bl3) + hi += Math.imul(ah8, bh3) + lo += Math.imul(al7, bl4) + mid += Math.imul(al7, bh4) + mid += Math.imul(ah7, bl4) + hi += Math.imul(ah7, bh4) + lo += Math.imul(al6, bl5) + mid += Math.imul(al6, bh5) + mid += Math.imul(ah6, bl5) + hi += Math.imul(ah6, bh5) + lo += Math.imul(al5, bl6) + mid += Math.imul(al5, bh6) + mid += Math.imul(ah5, bl6) + hi += Math.imul(ah5, bh6) + lo += Math.imul(al4, bl7) + mid += Math.imul(al4, bh7) + mid += Math.imul(ah4, bl7) + hi += Math.imul(ah4, bh7) + lo += Math.imul(al3, bl8) + mid += Math.imul(al3, bh8) + mid += Math.imul(ah3, bl8) + hi += Math.imul(ah3, bh8) + lo += Math.imul(al2, bl9) + mid += Math.imul(al2, bh9) + mid += Math.imul(ah2, bl9) + hi += Math.imul(ah2, bh9) + var w11 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w11 >>> 26) + w11 &= 0x3ffffff + /* k = 12 */ + lo = Math.imul(al9, bl3) + mid = Math.imul(al9, bh3) + mid += Math.imul(ah9, bl3) + hi = Math.imul(ah9, bh3) + lo += Math.imul(al8, bl4) + mid += Math.imul(al8, bh4) + mid += Math.imul(ah8, bl4) + hi += Math.imul(ah8, bh4) + lo += Math.imul(al7, bl5) + mid += Math.imul(al7, bh5) + mid += Math.imul(ah7, bl5) + hi += Math.imul(ah7, bh5) + lo += Math.imul(al6, bl6) + mid += Math.imul(al6, bh6) + mid += Math.imul(ah6, bl6) + hi += Math.imul(ah6, bh6) + lo += Math.imul(al5, bl7) + mid += Math.imul(al5, bh7) + mid += Math.imul(ah5, bl7) + hi += Math.imul(ah5, bh7) + lo += Math.imul(al4, bl8) + mid += Math.imul(al4, bh8) + mid += Math.imul(ah4, bl8) + hi += Math.imul(ah4, bh8) + lo += Math.imul(al3, bl9) + mid += Math.imul(al3, bh9) + mid += Math.imul(ah3, bl9) + hi += Math.imul(ah3, bh9) + var w12 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w12 >>> 26) + w12 &= 0x3ffffff + /* k = 13 */ + lo = Math.imul(al9, bl4) + mid = Math.imul(al9, bh4) + mid += Math.imul(ah9, bl4) + hi = Math.imul(ah9, bh4) + lo += Math.imul(al8, bl5) + mid += Math.imul(al8, bh5) + mid += Math.imul(ah8, bl5) + hi += Math.imul(ah8, bh5) + lo += Math.imul(al7, bl6) + mid += Math.imul(al7, bh6) + mid += Math.imul(ah7, bl6) + hi += Math.imul(ah7, bh6) + lo += Math.imul(al6, bl7) + mid += Math.imul(al6, bh7) + mid += Math.imul(ah6, bl7) + hi += Math.imul(ah6, bh7) + lo += Math.imul(al5, bl8) + mid += Math.imul(al5, bh8) + mid += Math.imul(ah5, bl8) + hi += Math.imul(ah5, bh8) + lo += Math.imul(al4, bl9) + mid += Math.imul(al4, bh9) + mid += Math.imul(ah4, bl9) + hi += Math.imul(ah4, bh9) + var w13 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w13 >>> 26) + w13 &= 0x3ffffff + /* k = 14 */ + lo = Math.imul(al9, bl5) + mid = Math.imul(al9, bh5) + mid += Math.imul(ah9, bl5) + hi = Math.imul(ah9, bh5) + lo += Math.imul(al8, bl6) + mid += Math.imul(al8, bh6) + mid += Math.imul(ah8, bl6) + hi += Math.imul(ah8, bh6) + lo += Math.imul(al7, bl7) + mid += Math.imul(al7, bh7) + mid += Math.imul(ah7, bl7) + hi += Math.imul(ah7, bh7) + lo += Math.imul(al6, bl8) + mid += Math.imul(al6, bh8) + mid += Math.imul(ah6, bl8) + hi += Math.imul(ah6, bh8) + lo += Math.imul(al5, bl9) + mid += Math.imul(al5, bh9) + mid += Math.imul(ah5, bl9) + hi += Math.imul(ah5, bh9) + var w14 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w14 >>> 26) + w14 &= 0x3ffffff + /* k = 15 */ + lo = Math.imul(al9, bl6) + mid = Math.imul(al9, bh6) + mid += Math.imul(ah9, bl6) + hi = Math.imul(ah9, bh6) + lo += Math.imul(al8, bl7) + mid += Math.imul(al8, bh7) + mid += Math.imul(ah8, bl7) + hi += Math.imul(ah8, bh7) + lo += Math.imul(al7, bl8) + mid += Math.imul(al7, bh8) + mid += Math.imul(ah7, bl8) + hi += Math.imul(ah7, bh8) + lo += Math.imul(al6, bl9) + mid += Math.imul(al6, bh9) + mid += Math.imul(ah6, bl9) + hi += Math.imul(ah6, bh9) + var w15 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w15 >>> 26) + w15 &= 0x3ffffff + /* k = 16 */ + lo = Math.imul(al9, bl7) + mid = Math.imul(al9, bh7) + mid += Math.imul(ah9, bl7) + hi = Math.imul(ah9, bh7) + lo += Math.imul(al8, bl8) + mid += Math.imul(al8, bh8) + mid += Math.imul(ah8, bl8) + hi += Math.imul(ah8, bh8) + lo += Math.imul(al7, bl9) + mid += Math.imul(al7, bh9) + mid += Math.imul(ah7, bl9) + hi += Math.imul(ah7, bh9) + var w16 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w16 >>> 26) + w16 &= 0x3ffffff + /* k = 17 */ + lo = Math.imul(al9, bl8) + mid = Math.imul(al9, bh8) + mid += Math.imul(ah9, bl8) + hi = Math.imul(ah9, bh8) + lo += Math.imul(al8, bl9) + mid += Math.imul(al8, bh9) + mid += Math.imul(ah8, bl9) + hi += Math.imul(ah8, bh9) + var w17 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w17 >>> 26) + w17 &= 0x3ffffff + /* k = 18 */ + lo = Math.imul(al9, bl9) + mid = Math.imul(al9, bh9) + mid += Math.imul(ah9, bl9) + hi = Math.imul(ah9, bh9) + var w18 = c + lo + ((mid & 0x1fff) << 13) + c = hi + (mid >>> 13) + (w18 >>> 26) + 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 +} + +},{}],1379:[function(require,module,exports){ +'use strict' +var BN = require('./bn') + +function ECJPoint (x, y, z) { + if (x === null && y === null && z === null) { + this.x = ECJPoint.one + this.y = ECJPoint.one + this.z = ECJPoint.zero + } else { + this.x = x + this.y = y + this.z = z + } + + this.zOne = this.z === ECJPoint.one +} + +ECJPoint.zero = BN.fromNumber(0) +ECJPoint.one = BN.fromNumber(1) + +ECJPoint.prototype.neg = function () { + if (this.inf) return this + + return new ECJPoint(this.x, this.y.redNeg(), this.z) +} + +ECJPoint.prototype.add = function (p) { + // O + P = P + if (this.inf) return p + + // P + O = P + if (p.inf) return this + + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-1998-cmo-2 + // 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 h = u1.redSub(u2) + var r = s1.redSub(s2) + if (h.isZero()) { + if (r.isZero()) return this.dbl() + return new ECJPoint(null, null, null) + } + + var h2 = h.redSqr() + var v = u1.redMul(h2) + var h3 = h2.redMul(h) + + 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) + + return new ECJPoint(nx, ny, nz) +} + +ECJPoint.prototype.mixedAdd = function (p) { + // O + P = P + if (this.inf) return p.toECJPoint() + + // P + O = P + if (p.inf) return this + + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-1998-cmo-2 + // with p.z = 1 + // 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) + + var h = u1.redSub(u2) + var r = s1.redSub(s2) + if (h.isZero()) { + if (r.isZero()) return this.dbl() + return new ECJPoint(null, null, null) + } + + var h2 = h.redSqr() + var v = u1.redMul(h2) + var h3 = h2.redMul(h) + + 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) + + return new ECJPoint(nx, ny, nz) +} + +ECJPoint.prototype.dbl = function () { + if (this.inf) return this + + var nx + var ny + var nz + + // Z = 1 + if (this.zOne) { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl + // 1M + 5S + 6A + 3*2 + 1*3 + 1*8 + + // 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 + var m = xx.redAdd(xx).redIAdd(xx) + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s) + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy).redIAdd(yyyy).redIAdd(yyyy) + + // 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 { + // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + // 2M + 5S + 6A + 3*2 + 1*3 + 1*8 + + // 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() + + // 8 * C + var c8 = c.redIAdd(c).redIAdd(c).redIAdd(c) + + // 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) + } + + return new ECJPoint(nx, ny, nz) +} + +ECJPoint.prototype.dblp = function (pow) { + if (pow === 0 || this.inf) return this + + var point = this + for (var i = 0; i < pow; i++) point = point.dbl() + + return point +} + +Object.defineProperty(ECJPoint.prototype, 'inf', { + enumerable: true, + get: function () { + return this.z.isZero() + } +}) + +module.exports = ECJPoint + +},{"./bn":1377}],1380:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var BN = require('./bn') +var ECJPoint = require('./ecjpoint') + +function ECPoint (x, y) { + if (x === null && y === null) { + this.x = this.y = null + this.inf = true + } else { + this.x = x + this.y = y + this.inf = false + } +} + +ECPoint.fromPublicKey = function (publicKey) { + var first = publicKey[0] + var x + var y + + if (publicKey.length === 33 && (first === 0x02 || first === 0x03)) { + x = BN.fromBuffer(publicKey.slice(1, 33)) + + // overflow + if (x.ucmp(BN.p) >= 0) return null + + // create from X + y = x.redSqr().redMul(x).redIAdd7().redSqrt() + if (y === null) return null + if ((first === 0x03) !== y.isOdd()) y = y.redNeg() + + return new ECPoint(x, y) + } + + if (publicKey.length === 65 && (first === 0x04 || first === 0x06 || first === 0x07)) { + x = BN.fromBuffer(publicKey.slice(1, 33)) + y = BN.fromBuffer(publicKey.slice(33, 65)) + + // overflow + if (x.ucmp(BN.p) >= 0 || y.ucmp(BN.p) >= 0) return null + + // is odd flag + if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null + + // x*x*x + 7 = y*y + if (x.redSqr().redMul(x).redIAdd7().ucmp(y.redSqr()) !== 0) return null + + return new ECPoint(x, y) + } + + return null +} + +ECPoint.prototype.toPublicKey = function (compressed) { + var x = this.x + var y = this.y + var publicKey + + if (compressed) { + publicKey = Buffer.alloc(33) + publicKey[0] = y.isOdd() ? 0x03 : 0x02 + x.toBuffer().copy(publicKey, 1) + } else { + publicKey = Buffer.alloc(65) + publicKey[0] = 0x04 + x.toBuffer().copy(publicKey, 1) + y.toBuffer().copy(publicKey, 33) + } + + return publicKey +} + +ECPoint.fromECJPoint = function (p) { + if (p.inf) return new ECPoint(null, null) + + var zinv = p.z.redInvm() + var zinv2 = zinv.redSqr() + var ax = p.x.redMul(zinv2) + var ay = p.y.redMul(zinv2).redMul(zinv) + + return new ECPoint(ax, ay) +} + +ECPoint.prototype.toECJPoint = function () { + if (this.inf) return new ECJPoint(null, null, null) + + return new ECJPoint(this.x, this.y, ECJPoint.one) +} + +ECPoint.prototype.neg = function () { + if (this.inf) return this + + return new ECPoint(this.x, this.y.redNeg()) +} + +ECPoint.prototype.add = function (p) { + // O + P = P + if (this.inf) return p + + // P + O = P + if (p.inf) return this + + if (this.x.ucmp(p.x) === 0) { + // P + P = 2P + if (this.y.ucmp(p.y) === 0) return this.dbl() + // P + (-P) = O + return new ECPoint(null, null) + } + + // s = (y - yp) / (x - xp) + // nx = s^2 - x - xp + // ny = s * (x - nx) - y + var s = this.y.redSub(p.y) + if (!s.isZero()) s = s.redMul(this.x.redSub(p.x).redInvm()) + + var nx = s.redSqr().redISub(this.x).redISub(p.x) + var ny = s.redMul(this.x.redSub(nx)).redISub(this.y) + return new ECPoint(nx, ny) +} + +ECPoint.prototype.dbl = function () { + if (this.inf) return this + + // 2P = O + var yy = this.y.redAdd(this.y) + if (yy.isZero()) return new ECPoint(null, null) + + // s = (3 * x^2) / (2 * y) + // nx = s^2 - 2*x + // ny = s * (x - nx) - y + var x2 = this.x.redSqr() + var s = x2.redAdd(x2).redIAdd(x2).redMul(yy.redInvm()) + + var nx = s.redSqr().redISub(this.x.redAdd(this.x)) + var ny = s.redMul(this.x.redSub(nx)).redISub(this.y) + return new ECPoint(nx, ny) +} + +ECPoint.prototype.mul = function (num) { + // Algorithm 3.36 Window NAF method for point multiplication + var nafPoints = this._getNAFPoints(4) + var points = nafPoints.points + + // Get NAF form + var naf = num.getNAF(nafPoints.wnd) + + // Add `this`*(N+1) for every w-NAF index + var acc = new ECJPoint(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 += 1 + acc = acc.dblp(k) + + if (i < 0) break + + // J +- P + var z = naf[i] + if (z > 0) { + acc = acc.mixedAdd(points[(z - 1) >> 1]) + } else { + acc = acc.mixedAdd(points[(-z - 1) >> 1].neg()) + } + } + + return ECPoint.fromECJPoint(acc) +} + +ECPoint.prototype._getNAFPoints1 = function () { + return { wnd: 1, points: [this] } +} + +ECPoint.prototype._getNAFPoints = function (wnd) { + var points = new Array((1 << wnd) - 1) + points[0] = this + var dbl = this.dbl() + for (var i = 1; i < points.length; ++i) points[i] = points[i - 1].add(dbl) + return { wnd: wnd, points: points } +} + +module.exports = ECPoint + +},{"./bn":1377,"./ecjpoint":1379,"safe-buffer":1371}],1381:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var BN = require('./bn') +var ECPoint = require('./ecpoint') +var ECJPoint = require('./ecjpoint') + +function ECPointG () { + this.x = BN.fromBuffer(Buffer.from('79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798', 'hex')) + this.y = BN.fromBuffer(Buffer.from('483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8', 'hex')) + this.inf = false + + this._precompute() +} + +ECPointG.prototype._precompute = function () { + var ecpoint = new ECPoint(this.x, this.y) + + var dstep = 4 + var points = new Array(1 + Math.ceil(257 / dstep)) + var acc = points[0] = ecpoint + for (var i = 1; i < points.length; ++i) { + for (var j = 0; j < dstep; j++) acc = acc.dbl() + points[i] = acc + } + + this.precomputed = { + naf: ecpoint._getNAFPoints(7), + doubles: { + step: dstep, + points: points, + negpoints: points.map(function (p) { return p.neg() }) + } + } +} + +ECPointG.prototype.mul = function (num) { + // Algorithm 3.42 Fixed-base NAF windowing method for point multiplication + var step = this.precomputed.doubles.step + var points = this.precomputed.doubles.points + var negpoints = this.precomputed.doubles.negpoints + + var naf = num.getNAF(1) + var I = ((1 << (step + 1)) - (step % 2 === 0 ? 2 : 1)) / 3 + + // Translate into more windowed form + var repr = [] + for (var j = 0; j < naf.length; j += step) { + var nafW = 0 + for (var k = j + step - 1; k >= j; k--) nafW = (nafW << 1) + naf[k] + repr.push(nafW) + } + + var a = new ECJPoint(null, null, null) + var b = new ECJPoint(null, null, null) + for (var i = I; i > 0; i--) { + for (var jj = 0; jj < repr.length; jj++) { + if (repr[jj] === i) { + b = b.mixedAdd(points[jj]) + } else if (repr[jj] === -i) { + b = b.mixedAdd(negpoints[jj]) + } + } + + a = a.add(b) + } + + return ECPoint.fromECJPoint(a) +} + +ECPointG.prototype.mulAdd = function (k1, p2, k2) { + var nafPointsP1 = this.precomputed.naf + var nafPointsP2 = p2._getNAFPoints1() + var wnd = [nafPointsP1.points, nafPointsP2.points] + var naf = [k1.getNAF(nafPointsP1.wnd), k2.getNAF(nafPointsP2.wnd)] + + var acc = new ECJPoint(null, null, null) + var tmp = [null, null] + for (var i = Math.max(naf[0].length, naf[1].length); i >= 0; i--) { + var k = 0 + + for (; i >= 0; ++k, --i) { + tmp[0] = naf[0][i] | 0 + tmp[1] = naf[1][i] | 0 + + if (tmp[0] !== 0 || tmp[1] !== 0) break + } + + if (i >= 0) k += 1 + acc = acc.dblp(k) + + if (i < 0) break + + for (var jj = 0; jj < 2; jj++) { + var z = tmp[jj] + var p + if (z === 0) { + continue + } else if (z > 0) { + p = wnd[jj][z >> 1] + } else if (z < 0) { + p = wnd[jj][-z >> 1].neg() + } + + // hack: ECPoint detection + if (p.z === undefined) { + acc = acc.mixedAdd(p) + } else { + acc = acc.add(p) + } + } + } + + return acc +} + +module.exports = new ECPointG() + +},{"./bn":1377,"./ecjpoint":1379,"./ecpoint":1380,"safe-buffer":1371}],1382:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var createHash = require('create-hash') +var HmacDRBG = require('drbg.js/hmac') +var messages = require('../messages.json') +var BN = require('./bn') +var ECPoint = require('./ecpoint') +var g = require('./ecpointg') + +exports.privateKeyVerify = function (privateKey) { + var bn = BN.fromBuffer(privateKey) + return !(bn.isOverflow() || bn.isZero()) +} + +exports.privateKeyExport = function (privateKey, compressed) { + var d = BN.fromBuffer(privateKey) + if (d.isOverflow() || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) + + return g.mul(d).toPublicKey(compressed) +} + +exports.privateKeyNegate = function (privateKey) { + var bn = BN.fromBuffer(privateKey) + if (bn.isZero()) return Buffer.alloc(32) + + if (bn.ucmp(BN.n) > 0) bn.isub(BN.n) + return BN.n.sub(bn).toBuffer() +} + +exports.privateKeyModInverse = function (privateKey) { + var bn = BN.fromBuffer(privateKey) + if (bn.isOverflow() || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) + + return bn.uinvm().toBuffer() +} + +exports.privateKeyTweakAdd = function (privateKey, tweak) { + var bn = BN.fromBuffer(tweak) + if (bn.isOverflow()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + bn.iadd(BN.fromBuffer(privateKey)) + if (bn.isOverflow()) bn.isub(BN.n) + if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + return bn.toBuffer() +} + +exports.privateKeyTweakMul = function (privateKey, tweak) { + var bn = BN.fromBuffer(tweak) + if (bn.isOverflow() || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) + + var d = BN.fromBuffer(privateKey) + return bn.umul(d).ureduce().toBuffer() +} + +exports.publicKeyCreate = function (privateKey, compressed) { + var d = BN.fromBuffer(privateKey) + if (d.isOverflow() || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) + + return g.mul(d).toPublicKey(compressed) +} + +exports.publicKeyConvert = function (publicKey, compressed) { + var point = ECPoint.fromPublicKey(publicKey) + if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + return point.toPublicKey(compressed) +} + +exports.publicKeyVerify = function (publicKey) { + return ECPoint.fromPublicKey(publicKey) !== null +} + +exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { + var point = ECPoint.fromPublicKey(publicKey) + if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + tweak = BN.fromBuffer(tweak) + if (tweak.isOverflow()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + var result = g.mul(tweak).add(point) + if (result.inf) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + return result.toPublicKey(compressed) +} + +exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { + var point = ECPoint.fromPublicKey(publicKey) + if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + tweak = BN.fromBuffer(tweak) + if (tweak.isOverflow() || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL) + + return point.mul(tweak).toPublicKey(compressed) +} + +exports.publicKeyCombine = function (publicKeys, compressed) { + var points = new Array(publicKeys.length) + for (var i = 0; i < publicKeys.length; ++i) { + points[i] = ECPoint.fromPublicKey(publicKeys[i]) + if (points[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + } + + var point = points[0] + for (var j = 1; j < points.length; ++j) point = point.add(points[j]) + if (point.inf) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL) + + return point.toPublicKey(compressed) +} + +exports.signatureNormalize = function (signature) { + var r = BN.fromBuffer(signature.slice(0, 32)) + var s = BN.fromBuffer(signature.slice(32, 64)) + if (r.isOverflow() || s.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + var result = Buffer.from(signature) + if (s.isHigh()) BN.n.sub(s).toBuffer().copy(result, 32) + + return result +} + +exports.signatureExport = function (signature) { + var r = signature.slice(0, 32) + var s = signature.slice(32, 64) + if (BN.fromBuffer(r).isOverflow() || BN.fromBuffer(s).isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + return { r: r, s: s } +} + +exports.signatureImport = function (sigObj) { + var r = BN.fromBuffer(sigObj.r) + if (r.isOverflow()) r = BN.fromNumber(0) + + var s = BN.fromBuffer(sigObj.s) + if (s.isOverflow()) s = BN.fromNumber(0) + + return Buffer.concat([r.toBuffer(), s.toBuffer()]) +} + +exports.sign = function (message, privateKey, noncefn, data) { + var d = BN.fromBuffer(privateKey) + if (d.isOverflow() || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL) + + if (noncefn === null) { + var drbg = new HmacDRBG('sha256', privateKey, message, data) + noncefn = function () { return drbg.generate(32) } + } + + var bnMessage = BN.fromBuffer(message) + for (var count = 0; ; ++count) { + var nonce = noncefn(message, privateKey, null, data, count) + if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL) + + var k = BN.fromBuffer(nonce) + if (k.isOverflow() || k.isZero()) continue + + var kp = g.mul(k) + var r = kp.x.fireduce() + if (r.isZero()) continue + + var s = k.uinvm().umul(r.umul(d).ureduce().iadd(bnMessage).fireduce()).ureduce() + if (s.isZero()) continue + + var recovery = (kp.x.ucmp(r) !== 0 ? 2 : 0) | (kp.y.isOdd() ? 1 : 0) + if (s.isHigh()) { + s = BN.n.sub(s) + recovery ^= 1 + } + + return { + signature: Buffer.concat([r.toBuffer(), s.toBuffer()]), + recovery: recovery + } + } +} + +exports.verify = function (message, signature, publicKey) { + var sigr = BN.fromBuffer(signature.slice(0, 32)) + var sigs = BN.fromBuffer(signature.slice(32, 64)) + if (sigr.isOverflow() || sigs.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + if (sigs.isHigh() || sigr.isZero() || sigs.isZero()) return false + + var pub = ECPoint.fromPublicKey(publicKey) + if (pub === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + var sinv = sigs.uinvm() + var u1 = sinv.umul(BN.fromBuffer(message)).ureduce() + var u2 = sinv.umul(sigr).ureduce() + var point = g.mulAdd(u1, pub, u2) + if (point.inf) return false + + // return ECPoint.fromECJPoint(point).x.fireduce().ucmp(sigr) === 0 + // Inversion-free + var z2 = point.z.redSqr() + if (sigr.redMul(z2).ucmp(point.x) === 0) return true + if (sigr.ucmp(BN.psn) >= 0) return false + + return sigr.iadd(BN.psn).redMul(z2).ucmp(point.x) === 0 +} + +exports.recover = function (message, signature, recovery, compressed) { + var sigr = BN.fromBuffer(signature.slice(0, 32)) + var sigs = BN.fromBuffer(signature.slice(32, 64)) + if (sigr.isOverflow() || sigs.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + do { + if (sigr.isZero() || sigs.isZero()) break + + var kpx = sigr + if (recovery >> 1) { + if (kpx.ucmp(BN.psn) >= 0) break + kpx = sigr.add(BN.n) + } + + var kpPublicKey = Buffer.concat([Buffer.from([0x02 + (recovery & 0x01)]), kpx.toBuffer()]) + var kp = ECPoint.fromPublicKey(kpPublicKey) + if (kp === null) break + + var rInv = sigr.uinvm() + var s1 = BN.n.sub(BN.fromBuffer(message)).umul(rInv).ureduce() + var s2 = sigs.umul(rInv).ureduce() + var point = ECPoint.fromECJPoint(g.mulAdd(s1, kp, s2)) + return point.toPublicKey(compressed) + } while (false) + + throw new Error(messages.ECDSA_RECOVER_FAIL) +} + +exports.ecdh = function (publicKey, privateKey) { + var shared = exports.ecdhUnsafe(publicKey, privateKey, true) + return createHash('sha256').update(shared).digest() +} + +exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { + var point = ECPoint.fromPublicKey(publicKey) + if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + var scalar = BN.fromBuffer(privateKey) + if (scalar.isOverflow() || scalar.isZero()) throw new Error(messages.ECDH_FAIL) + + return point.mul(scalar).toPublicKey(compressed) +} + +},{"../messages.json":1383,"./bn":1377,"./ecpoint":1380,"./ecpointg":1381,"create-hash":193,"drbg.js/hmac":234,"safe-buffer":1371}],1383:[function(require,module,exports){ +module.exports={ + "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", + "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", + "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid", + "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid", + "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid", + "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format", + "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format", + "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array", + "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element", + "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer", + "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid", + "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid", + "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again", + "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid", + "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid", + "ECDH_FAIL": "scalar was invalid (zero or overflow)", + "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer", + "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid", + "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature", + "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature", + "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format", + "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid", + "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature", + "MSG32_TYPE_INVALID": "message should be a Buffer", + "MSG32_LENGTH_INVALID": "message length is invalid", + "OPTIONS_TYPE_INVALID": "options should be an Object", + "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer", + "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid", + "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function", + "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number", + "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4", + "TWEAK_TYPE_INVALID": "tweak should be a Buffer", + "TWEAK_LENGTH_INVALID": "tweak length is invalid" +} + +},{}],1384:[function(require,module,exports){ +(function (setImmediate){ +'use strict'; +module.exports = typeof setImmediate === 'function' ? setImmediate : + function setImmediate() { + var args = [].slice.apply(arguments); + args.splice(1, 0, 0); + setTimeout.apply(null, args); + }; + +}).call(this,require("timers").setImmediate) +},{"timers":1500}],1385:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +},{"safe-buffer":1371}],1386:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha":1387,"./sha1":1388,"./sha224":1389,"./sha256":1390,"./sha384":1391,"./sha512":1392}],1387:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + +},{"./hash":1385,"inherits":317,"safe-buffer":1371}],1388:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + +},{"./hash":1385,"inherits":317,"safe-buffer":1371}],1389:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + +},{"./hash":1385,"./sha256":1390,"inherits":317,"safe-buffer":1371}],1390:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +},{"./hash":1385,"inherits":317,"safe-buffer":1371}],1391:[function(require,module,exports){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + +},{"./hash":1385,"./sha512":1392,"inherits":317,"safe-buffer":1371}],1392:[function(require,module,exports){ +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +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 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +},{"./hash":1385,"inherits":317,"safe-buffer":1371}],1393:[function(require,module,exports){ +'use strict'; +module.exports = require('./lib/index'); + +},{"./lib/index":1397}],1394:[function(require,module,exports){ +'use strict'; + +var randomFromSeed = require('./random/random-from-seed'); + +var ORIGINAL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-'; +var alphabet; +var previousSeed; + +var shuffled; + +function reset() { + shuffled = false; +} + +function setCharacters(_alphabet_) { + if (!_alphabet_) { + if (alphabet !== ORIGINAL) { + alphabet = ORIGINAL; + reset(); + } + return; + } + + if (_alphabet_ === alphabet) { + return; + } + + if (_alphabet_.length !== ORIGINAL.length) { + throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. You submitted ' + _alphabet_.length + ' characters: ' + _alphabet_); + } + + var unique = _alphabet_.split('').filter(function(item, ind, arr){ + return ind !== arr.lastIndexOf(item); + }); + + if (unique.length) { + throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. These characters were not unique: ' + unique.join(', ')); + } + + alphabet = _alphabet_; + reset(); +} + +function characters(_alphabet_) { + setCharacters(_alphabet_); + return alphabet; +} + +function setSeed(seed) { + randomFromSeed.seed(seed); + if (previousSeed !== seed) { + reset(); + previousSeed = seed; + } +} + +function shuffle() { + if (!alphabet) { + setCharacters(ORIGINAL); + } + + var sourceArray = alphabet.split(''); + var targetArray = []; + var r = randomFromSeed.nextValue(); + var characterIndex; + + while (sourceArray.length > 0) { + r = randomFromSeed.nextValue(); + characterIndex = Math.floor(r * sourceArray.length); + targetArray.push(sourceArray.splice(characterIndex, 1)[0]); + } + return targetArray.join(''); +} + +function getShuffled() { + if (shuffled) { + return shuffled; + } + shuffled = shuffle(); + return shuffled; +} + +/** + * lookup shuffled letter + * @param index + * @returns {string} + */ +function lookup(index) { + var alphabetShuffled = getShuffled(); + return alphabetShuffled[index]; +} + +function get () { + return alphabet || ORIGINAL; +} + +module.exports = { + get: get, + characters: characters, + seed: setSeed, + lookup: lookup, + shuffled: getShuffled +}; + +},{"./random/random-from-seed":1400}],1395:[function(require,module,exports){ +'use strict'; + +var generate = require('./generate'); +var alphabet = require('./alphabet'); + +// Ignore all milliseconds before a certain time to reduce the size of the date entropy without sacrificing uniqueness. +// This number should be updated every year or so to keep the generated id short. +// To regenerate `new Date() - 0` and bump the version. Always bump the version! +var REDUCE_TIME = 1567752802062; + +// don't change unless we change the algos or REDUCE_TIME +// must be an integer and less than 16 +var version = 7; + +// Counter is used when shortid is called multiple times in one second. +var counter; + +// Remember the last time shortid was called in case counter is needed. +var previousSeconds; + +/** + * Generate unique id + * Returns string id + */ +function build(clusterWorkerId) { + var str = ''; + + var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001); + + if (seconds === previousSeconds) { + counter++; + } else { + counter = 0; + previousSeconds = seconds; + } + + str = str + generate(version); + str = str + generate(clusterWorkerId); + if (counter > 0) { + str = str + generate(counter); + } + str = str + generate(seconds); + return str; +} + +module.exports = build; + +},{"./alphabet":1394,"./generate":1396}],1396:[function(require,module,exports){ +'use strict'; + +var alphabet = require('./alphabet'); +var random = require('./random/random-byte'); +var format = require('nanoid/format'); + +function generate(number) { + var loopCounter = 0; + var done; + + var str = ''; + + while (!done) { + str = str + format(random, alphabet.get(), 1); + done = number < (Math.pow(16, loopCounter + 1 ) ); + loopCounter++; + } + return str; +} + +module.exports = generate; + +},{"./alphabet":1394,"./random/random-byte":1399,"nanoid/format":1181}],1397:[function(require,module,exports){ +'use strict'; + +var alphabet = require('./alphabet'); +var build = require('./build'); +var isValid = require('./is-valid'); + +// if you are using cluster or multiple servers use this to make each instance +// has a unique value for worker +// Note: I don't know if this is automatically set when using third +// party cluster solutions such as pm2. +var clusterWorkerId = require('./util/cluster-worker-id') || 0; + +/** + * Set the seed. + * Highly recommended if you don't want people to try to figure out your id schema. + * exposed as shortid.seed(int) + * @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps. + */ +function seed(seedValue) { + alphabet.seed(seedValue); + return module.exports; +} + +/** + * Set the cluster worker or machine id + * exposed as shortid.worker(int) + * @param workerId worker must be positive integer. Number less than 16 is recommended. + * returns shortid module so it can be chained. + */ +function worker(workerId) { + clusterWorkerId = workerId; + return module.exports; +} + +/** + * + * sets new characters to use in the alphabet + * returns the shuffled alphabet + */ +function characters(newCharacters) { + if (newCharacters !== undefined) { + alphabet.characters(newCharacters); + } + + return alphabet.shuffled(); +} + +/** + * Generate unique id + * Returns string id + */ +function generate() { + return build(clusterWorkerId); +} + +// Export all other functions as properties of the generate function +module.exports = generate; +module.exports.generate = generate; +module.exports.seed = seed; +module.exports.worker = worker; +module.exports.characters = characters; +module.exports.isValid = isValid; + +},{"./alphabet":1394,"./build":1395,"./is-valid":1398,"./util/cluster-worker-id":1401}],1398:[function(require,module,exports){ +'use strict'; +var alphabet = require('./alphabet'); + +function isShortId(id) { + if (!id || typeof id !== 'string' || id.length < 6 ) { + return false; + } + + var nonAlphabetic = new RegExp('[^' + + alphabet.get().replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') + + ']'); + return !nonAlphabetic.test(id); +} + +module.exports = isShortId; + +},{"./alphabet":1394}],1399:[function(require,module,exports){ +'use strict'; + +var crypto = typeof window === 'object' && (window.crypto || window.msCrypto); // IE 11 uses window.msCrypto + +var randomByte; + +if (!crypto || !crypto.getRandomValues) { + randomByte = function(size) { + var bytes = []; + for (var i = 0; i < size; i++) { + bytes.push(Math.floor(Math.random() * 256)); + } + return bytes; + }; +} else { + randomByte = function(size) { + return crypto.getRandomValues(new Uint8Array(size)); + }; +} + +module.exports = randomByte; + +},{}],1400:[function(require,module,exports){ +'use strict'; + +// Found this seed-based random generator somewhere +// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu) + +var seed = 1; + +/** + * return a random number based on a seed + * @param seed + * @returns {number} + */ +function getNextValue() { + seed = (seed * 9301 + 49297) % 233280; + return seed/(233280.0); +} + +function setSeed(_seed_) { + seed = _seed_; +} + +module.exports = { + nextValue: getNextValue, + seed: setSeed +}; + +},{}],1401:[function(require,module,exports){ +'use strict'; + +module.exports = 0; + +},{}],1402:[function(require,module,exports){ +var varint = require('varint') +exports.encode = function encode (v, b, o) { + v = v >= 0 ? v*2 : v*-2 - 1 + var r = varint.encode(v, b, o) + encode.bytes = varint.encode.bytes + return r +} +exports.decode = function decode (b, o) { + var v = varint.decode(b, o) + decode.bytes = varint.decode.bytes + return v & 1 ? (v+1) / -2 : v / 2 +} + +exports.encodingLength = function (v) { + return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1) +} + +},{"varint":1521}],1403:[function(require,module,exports){ +(function (Buffer){ +var debug = require('debug')('simple-peer') +var getBrowserRTC = require('get-browser-rtc') +var randombytes = require('randombytes') +var stream = require('readable-stream') +var queueMicrotask = require('queue-microtask') // TODO: remove when Node 10 is not supported + +var MAX_BUFFERED_AMOUNT = 64 * 1024 +var ICECOMPLETE_TIMEOUT = 5 * 1000 +var CHANNEL_CLOSING_TIMEOUT = 5 * 1000 + +// HACK: Filter trickle lines when trickle is disabled #354 +function filterTrickle (sdp) { + return sdp.replace(/a=ice-options:trickle\s\n/g, '') +} + +function makeError (message, code) { + var err = new Error(message) + err.code = code + return err +} + +function warn (message) { + console.warn(message) +} + +/** + * WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods. + * Duplex stream. + * @param {Object} opts + */ +class Peer extends stream.Duplex { + constructor (opts) { + opts = Object.assign({ + allowHalfOpen: false + }, opts) + + super(opts) + + this._id = randombytes(4).toString('hex').slice(0, 7) + this._debug('new peer %o', opts) + + this.channelName = opts.initiator + ? opts.channelName || randombytes(20).toString('hex') + : null + + this.initiator = opts.initiator || false + this.channelConfig = opts.channelConfig || Peer.channelConfig + this.config = Object.assign({}, Peer.config, opts.config) + this.offerOptions = opts.offerOptions || {} + this.answerOptions = opts.answerOptions || {} + this.sdpTransform = opts.sdpTransform || (sdp => sdp) + this.streams = opts.streams || (opts.stream ? [opts.stream] : []) // support old "stream" option + this.trickle = opts.trickle !== undefined ? opts.trickle : true + this.allowHalfTrickle = opts.allowHalfTrickle !== undefined ? opts.allowHalfTrickle : false + this.iceCompleteTimeout = opts.iceCompleteTimeout || ICECOMPLETE_TIMEOUT + + this.destroyed = false + this._connected = false + + this.remoteAddress = undefined + this.remoteFamily = undefined + this.remotePort = undefined + this.localAddress = undefined + this.localFamily = undefined + this.localPort = undefined + + this._wrtc = (opts.wrtc && typeof opts.wrtc === 'object') + ? opts.wrtc + : getBrowserRTC() + + if (!this._wrtc) { + if (typeof window === 'undefined') { + throw makeError('No WebRTC support: Specify `opts.wrtc` option in this environment', 'ERR_WEBRTC_SUPPORT') + } else { + throw makeError('No WebRTC support: Not a supported browser', 'ERR_WEBRTC_SUPPORT') + } + } + + this._pcReady = false + this._channelReady = false + this._iceComplete = false // ice candidate trickle done (got null candidate) + this._iceCompleteTimer = null // send an offer/answer anyway after some timeout + this._channel = null + this._pendingCandidates = [] + + this._isNegotiating = !this.initiator // is this peer waiting for negotiation to complete? + this._batchedNegotiation = false // batch synchronous negotiations + this._queuedNegotiation = false // is there a queued negotiation request? + this._sendersAwaitingStable = [] + this._senderMap = new Map() + this._firstStable = true + this._closingInterval = null + + this._remoteTracks = [] + this._remoteStreams = [] + + this._chunk = null + this._cb = null + this._interval = null + + try { + this._pc = new (this._wrtc.RTCPeerConnection)(this.config) + } catch (err) { + queueMicrotask(() => this.destroy(makeError(err, 'ERR_PC_CONSTRUCTOR'))) + return + } + + // We prefer feature detection whenever possible, but sometimes that's not + // possible for certain implementations. + this._isReactNativeWebrtc = typeof this._pc._peerConnectionId === 'number' + + this._pc.oniceconnectionstatechange = () => { + this._onIceStateChange() + } + this._pc.onicegatheringstatechange = () => { + this._onIceStateChange() + } + this._pc.onsignalingstatechange = () => { + this._onSignalingStateChange() + } + this._pc.onicecandidate = event => { + this._onIceCandidate(event) + } + + // Other spec events, unused by this implementation: + // - onconnectionstatechange + // - onicecandidateerror + // - onfingerprintfailure + // - onnegotiationneeded + + if (this.initiator) { + this._setupData({ + channel: this._pc.createDataChannel(this.channelName, this.channelConfig) + }) + } else { + this._pc.ondatachannel = event => { + this._setupData(event) + } + } + + if (this.streams) { + this.streams.forEach(stream => { + this.addStream(stream) + }) + } + this._pc.ontrack = event => { + this._onTrack(event) + } + + if (this.initiator) { + this._needsNegotiation() + } + + this._onFinishBound = () => { + this._onFinish() + } + this.once('finish', this._onFinishBound) + } + + get bufferSize () { + return (this._channel && this._channel.bufferedAmount) || 0 + } + + // HACK: it's possible channel.readyState is "closing" before peer.destroy() fires + // https://bugs.chromium.org/p/chromium/issues/detail?id=882743 + get connected () { + return (this._connected && this._channel.readyState === 'open') + } + + address () { + return { port: this.localPort, family: this.localFamily, address: this.localAddress } + } + + signal (data) { + if (this.destroyed) throw makeError('cannot signal after peer is destroyed', 'ERR_SIGNALING') + if (typeof data === 'string') { + try { + data = JSON.parse(data) + } catch (err) { + data = {} + } + } + this._debug('signal()') + + if (data.renegotiate && this.initiator) { + this._debug('got request to renegotiate') + this._needsNegotiation() + } + if (data.transceiverRequest && this.initiator) { + this._debug('got request for transceiver') + this.addTransceiver(data.transceiverRequest.kind, data.transceiverRequest.init) + } + if (data.candidate) { + if (this._pc.localDescription && this._pc.localDescription.type && this._pc.remoteDescription && this._pc.remoteDescription.type) { + this._addIceCandidate(data.candidate) + } else { + this._pendingCandidates.push(data.candidate) + } + } + if (data.sdp) { + this._pc.setRemoteDescription(new (this._wrtc.RTCSessionDescription)(data)) + .then(() => { + if (this.destroyed) return + + this._pendingCandidates.forEach(candidate => { + this._addIceCandidate(candidate) + }) + this._pendingCandidates = [] + + if (this._pc.remoteDescription.type === 'offer') this._createAnswer() + }) + .catch(err => { + this.destroy(makeError(err, 'ERR_SET_REMOTE_DESCRIPTION')) + }) + } + if (!data.sdp && !data.candidate && !data.renegotiate && !data.transceiverRequest) { + this.destroy(makeError('signal() called with invalid signal data', 'ERR_SIGNALING')) + } + } + + _addIceCandidate (candidate) { + var iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate) + this._pc.addIceCandidate(iceCandidateObj) + .catch(err => { + if (!iceCandidateObj.address || iceCandidateObj.address.endsWith('.local')) { + warn('Ignoring unsupported ICE candidate.') + } else { + this.destroy(makeError(err, 'ERR_ADD_ICE_CANDIDATE')) + } + }) + } + + /** + * Send text/binary data to the remote peer. + * @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk + */ + send (chunk) { + this._channel.send(chunk) + } + + /** + * Add a Transceiver to the connection. + * @param {String} kind + * @param {Object} init + */ + addTransceiver (kind, init) { + this._debug('addTransceiver()') + + if (this.initiator) { + try { + this._pc.addTransceiver(kind, init) + this._needsNegotiation() + } catch (err) { + this.destroy(makeError(err, 'ERR_ADD_TRANSCEIVER')) + } + } else { + this.emit('signal', { // request initiator to renegotiate + transceiverRequest: { kind, init } + }) + } + } + + /** + * Add a MediaStream to the connection. + * @param {MediaStream} stream + */ + addStream (stream) { + this._debug('addStream()') + + stream.getTracks().forEach(track => { + this.addTrack(track, stream) + }) + } + + /** + * Add a MediaStreamTrack to the connection. + * @param {MediaStreamTrack} track + * @param {MediaStream} stream + */ + addTrack (track, stream) { + this._debug('addTrack()') + + var submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender + var sender = submap.get(stream) + if (!sender) { + sender = this._pc.addTrack(track, stream) + submap.set(stream, sender) + this._senderMap.set(track, submap) + this._needsNegotiation() + } else if (sender.removed) { + throw makeError('Track has been removed. You should enable/disable tracks that you want to re-add.', 'ERR_SENDER_REMOVED') + } else { + throw makeError('Track has already been added to that stream.', 'ERR_SENDER_ALREADY_ADDED') + } + } + + /** + * Replace a MediaStreamTrack by another in the connection. + * @param {MediaStreamTrack} oldTrack + * @param {MediaStreamTrack} newTrack + * @param {MediaStream} stream + */ + replaceTrack (oldTrack, newTrack, stream) { + this._debug('replaceTrack()') + + var submap = this._senderMap.get(oldTrack) + var sender = submap ? submap.get(stream) : null + if (!sender) { + throw makeError('Cannot replace track that was never added.', 'ERR_TRACK_NOT_ADDED') + } + if (newTrack) this._senderMap.set(newTrack, submap) + + if (sender.replaceTrack != null) { + sender.replaceTrack(newTrack) + } else { + this.destroy(makeError('replaceTrack is not supported in this browser', 'ERR_UNSUPPORTED_REPLACETRACK')) + } + } + + /** + * Remove a MediaStreamTrack from the connection. + * @param {MediaStreamTrack} track + * @param {MediaStream} stream + */ + removeTrack (track, stream) { + this._debug('removeSender()') + + var submap = this._senderMap.get(track) + var sender = submap ? submap.get(stream) : null + if (!sender) { + throw makeError('Cannot remove track that was never added.', 'ERR_TRACK_NOT_ADDED') + } + try { + sender.removed = true + this._pc.removeTrack(sender) + } catch (err) { + if (err.name === 'NS_ERROR_UNEXPECTED') { + this._sendersAwaitingStable.push(sender) // HACK: Firefox must wait until (signalingState === stable) https://bugzilla.mozilla.org/show_bug.cgi?id=1133874 + } else { + this.destroy(makeError(err, 'ERR_REMOVE_TRACK')) + } + } + this._needsNegotiation() + } + + /** + * Remove a MediaStream from the connection. + * @param {MediaStream} stream + */ + removeStream (stream) { + this._debug('removeSenders()') + + stream.getTracks().forEach(track => { + this.removeTrack(track, stream) + }) + } + + _needsNegotiation () { + this._debug('_needsNegotiation') + if (this._batchedNegotiation) return // batch synchronous renegotiations + this._batchedNegotiation = true + queueMicrotask(() => { + this._batchedNegotiation = false + this._debug('starting batched negotiation') + this.negotiate() + }) + } + + negotiate () { + if (this.initiator) { + if (this._isNegotiating) { + this._queuedNegotiation = true + this._debug('already negotiating, queueing') + } else { + this._debug('start negotiation') + setTimeout(() => { // HACK: Chrome crashes if we immediately call createOffer + this._createOffer() + }, 0) + } + } else { + if (!this._isNegotiating) { + this._debug('requesting negotiation from initiator') + this.emit('signal', { // request initiator to renegotiate + renegotiate: true + }) + } + } + this._isNegotiating = true + } + + // TODO: Delete this method once readable-stream is updated to contain a default + // implementation of destroy() that automatically calls _destroy() + // See: https://github.com/nodejs/readable-stream/issues/283 + destroy (err) { + this._destroy(err, () => {}) + } + + _destroy (err, cb) { + if (this.destroyed) return + + this._debug('destroy (error: %s)', err && (err.message || err)) + + this.readable = this.writable = false + + if (!this._readableState.ended) this.push(null) + if (!this._writableState.finished) this.end() + + this.destroyed = true + this._connected = false + this._pcReady = false + this._channelReady = false + this._remoteTracks = null + this._remoteStreams = null + this._senderMap = null + + clearInterval(this._closingInterval) + this._closingInterval = null + + clearInterval(this._interval) + this._interval = null + this._chunk = null + this._cb = null + + if (this._onFinishBound) this.removeListener('finish', this._onFinishBound) + this._onFinishBound = null + + if (this._channel) { + try { + this._channel.close() + } catch (err) {} + + this._channel.onmessage = null + this._channel.onopen = null + this._channel.onclose = null + this._channel.onerror = null + } + if (this._pc) { + try { + this._pc.close() + } catch (err) {} + + this._pc.oniceconnectionstatechange = null + this._pc.onicegatheringstatechange = null + this._pc.onsignalingstatechange = null + this._pc.onicecandidate = null + this._pc.ontrack = null + this._pc.ondatachannel = null + } + this._pc = null + this._channel = null + + if (err) this.emit('error', err) + this.emit('close') + cb() + } + + _setupData (event) { + if (!event.channel) { + // In some situations `pc.createDataChannel()` returns `undefined` (in wrtc), + // which is invalid behavior. Handle it gracefully. + // See: https://github.com/feross/simple-peer/issues/163 + return this.destroy(makeError('Data channel event is missing `channel` property', 'ERR_DATA_CHANNEL')) + } + + this._channel = event.channel + this._channel.binaryType = 'arraybuffer' + + if (typeof this._channel.bufferedAmountLowThreshold === 'number') { + this._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT + } + + this.channelName = this._channel.label + + this._channel.onmessage = event => { + this._onChannelMessage(event) + } + this._channel.onbufferedamountlow = () => { + this._onChannelBufferedAmountLow() + } + this._channel.onopen = () => { + this._onChannelOpen() + } + this._channel.onclose = () => { + this._onChannelClose() + } + this._channel.onerror = err => { + this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) + } + + // HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition + // https://bugs.chromium.org/p/chromium/issues/detail?id=882743 + var isClosing = false + this._closingInterval = setInterval(() => { // No "onclosing" event + if (this._channel && this._channel.readyState === 'closing') { + if (isClosing) this._onChannelClose() // closing timed out: equivalent to onclose firing + isClosing = true + } else { + isClosing = false + } + }, CHANNEL_CLOSING_TIMEOUT) + } + + _read () {} + + _write (chunk, encoding, cb) { + if (this.destroyed) return cb(makeError('cannot write after peer is destroyed', 'ERR_DATA_CHANNEL')) + + if (this._connected) { + try { + this.send(chunk) + } catch (err) { + return this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) + } + if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { + this._debug('start backpressure: bufferedAmount %d', this._channel.bufferedAmount) + this._cb = cb + } else { + cb(null) + } + } else { + this._debug('write before connect') + this._chunk = chunk + this._cb = cb + } + } + + // When stream finishes writing, close socket. Half open connections are not + // supported. + _onFinish () { + if (this.destroyed) return + + // Wait a bit before destroying so the socket flushes. + // TODO: is there a more reliable way to accomplish this? + const destroySoon = () => { + setTimeout(() => this.destroy(), 1000) + } + + if (this._connected) { + destroySoon() + } else { + this.once('connect', destroySoon) + } + } + + _startIceCompleteTimeout () { + if (this.destroyed) return + if (this._iceCompleteTimer) return + this._debug('started iceComplete timeout') + this._iceCompleteTimer = setTimeout(() => { + if (!this._iceComplete) { + this._iceComplete = true + this._debug('iceComplete timeout completed') + this.emit('iceTimeout') + this.emit('_iceComplete') + } + }, this.iceCompleteTimeout) + } + + _createOffer () { + if (this.destroyed) return + + this._pc.createOffer(this.offerOptions) + .then(offer => { + if (this.destroyed) return + if (!this.trickle && !this.allowHalfTrickle) offer.sdp = filterTrickle(offer.sdp) + offer.sdp = this.sdpTransform(offer.sdp) + + const sendOffer = () => { + if (this.destroyed) return + var signal = this._pc.localDescription || offer + this._debug('signal') + this.emit('signal', { + type: signal.type, + sdp: signal.sdp + }) + } + + const onSuccess = () => { + this._debug('createOffer success') + if (this.destroyed) return + if (this.trickle || this._iceComplete) sendOffer() + else this.once('_iceComplete', sendOffer) // wait for candidates + } + + const onError = err => { + this.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION')) + } + + this._pc.setLocalDescription(offer) + .then(onSuccess) + .catch(onError) + }) + .catch(err => { + this.destroy(makeError(err, 'ERR_CREATE_OFFER')) + }) + } + + _requestMissingTransceivers () { + if (this._pc.getTransceivers) { + this._pc.getTransceivers().forEach(transceiver => { + if (!transceiver.mid && transceiver.sender.track && !transceiver.requested) { + transceiver.requested = true // HACK: Safari returns negotiated transceivers with a null mid + this.addTransceiver(transceiver.sender.track.kind) + } + }) + } + } + + _createAnswer () { + if (this.destroyed) return + + this._pc.createAnswer(this.answerOptions) + .then(answer => { + if (this.destroyed) return + if (!this.trickle && !this.allowHalfTrickle) answer.sdp = filterTrickle(answer.sdp) + answer.sdp = this.sdpTransform(answer.sdp) + + const sendAnswer = () => { + if (this.destroyed) return + var signal = this._pc.localDescription || answer + this._debug('signal') + this.emit('signal', { + type: signal.type, + sdp: signal.sdp + }) + if (!this.initiator) this._requestMissingTransceivers() + } + + const onSuccess = () => { + if (this.destroyed) return + if (this.trickle || this._iceComplete) sendAnswer() + else this.once('_iceComplete', sendAnswer) + } + + const onError = err => { + this.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION')) + } + + this._pc.setLocalDescription(answer) + .then(onSuccess) + .catch(onError) + }) + .catch(err => { + this.destroy(makeError(err, 'ERR_CREATE_ANSWER')) + }) + } + + _onIceStateChange () { + if (this.destroyed) return + var iceConnectionState = this._pc.iceConnectionState + var iceGatheringState = this._pc.iceGatheringState + + this._debug( + 'iceStateChange (connection: %s) (gathering: %s)', + iceConnectionState, + iceGatheringState + ) + this.emit('iceStateChange', iceConnectionState, iceGatheringState) + + if (iceConnectionState === 'connected' || iceConnectionState === 'completed') { + this._pcReady = true + this._maybeReady() + } + if (iceConnectionState === 'failed') { + this.destroy(makeError('Ice connection failed.', 'ERR_ICE_CONNECTION_FAILURE')) + } + if (iceConnectionState === 'closed') { + this.destroy(makeError('Ice connection closed.', 'ERR_ICE_CONNECTION_CLOSED')) + } + } + + getStats (cb) { + // statreports can come with a value array instead of properties + const flattenValues = report => { + if (Object.prototype.toString.call(report.values) === '[object Array]') { + report.values.forEach(value => { + Object.assign(report, value) + }) + } + return report + } + + // Promise-based getStats() (standard) + if (this._pc.getStats.length === 0) { + this._pc.getStats() + .then(res => { + var reports = [] + res.forEach(report => { + reports.push(flattenValues(report)) + }) + cb(null, reports) + }, err => cb(err)) + + // Two-parameter callback-based getStats() (deprecated, former standard) + } else if (this._isReactNativeWebrtc) { + this._pc.getStats(null, res => { + var reports = [] + res.forEach(report => { + reports.push(flattenValues(report)) + }) + cb(null, reports) + }, err => cb(err)) + + // Single-parameter callback-based getStats() (non-standard) + } else if (this._pc.getStats.length > 0) { + this._pc.getStats(res => { + // If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed + if (this.destroyed) return + + var reports = [] + res.result().forEach(result => { + var report = {} + result.names().forEach(name => { + report[name] = result.stat(name) + }) + report.id = result.id + report.type = result.type + report.timestamp = result.timestamp + reports.push(flattenValues(report)) + }) + cb(null, reports) + }, err => cb(err)) + + // Unknown browser, skip getStats() since it's anyone's guess which style of + // getStats() they implement. + } else { + cb(null, []) + } + } + + _maybeReady () { + this._debug('maybeReady pc %s channel %s', this._pcReady, this._channelReady) + if (this._connected || this._connecting || !this._pcReady || !this._channelReady) return + + this._connecting = true + + // HACK: We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339 + const findCandidatePair = () => { + if (this.destroyed) return + + this.getStats((err, items) => { + if (this.destroyed) return + + // Treat getStats error as non-fatal. It's not essential. + if (err) items = [] + + var remoteCandidates = {} + var localCandidates = {} + var candidatePairs = {} + var foundSelectedCandidatePair = false + + items.forEach(item => { + // TODO: Once all browsers support the hyphenated stats report types, remove + // the non-hypenated ones + if (item.type === 'remotecandidate' || item.type === 'remote-candidate') { + remoteCandidates[item.id] = item + } + if (item.type === 'localcandidate' || item.type === 'local-candidate') { + localCandidates[item.id] = item + } + if (item.type === 'candidatepair' || item.type === 'candidate-pair') { + candidatePairs[item.id] = item + } + }) + + const setSelectedCandidatePair = selectedCandidatePair => { + foundSelectedCandidatePair = true + + var local = localCandidates[selectedCandidatePair.localCandidateId] + + if (local && (local.ip || local.address)) { + // Spec + this.localAddress = local.ip || local.address + this.localPort = Number(local.port) + } else if (local && local.ipAddress) { + // Firefox + this.localAddress = local.ipAddress + this.localPort = Number(local.portNumber) + } else if (typeof selectedCandidatePair.googLocalAddress === 'string') { + // TODO: remove this once Chrome 58 is released + local = selectedCandidatePair.googLocalAddress.split(':') + this.localAddress = local[0] + this.localPort = Number(local[1]) + } + if (this.localAddress) { + this.localFamily = this.localAddress.includes(':') ? 'IPv6' : 'IPv4' + } + + var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId] + + if (remote && (remote.ip || remote.address)) { + // Spec + this.remoteAddress = remote.ip || remote.address + this.remotePort = Number(remote.port) + } else if (remote && remote.ipAddress) { + // Firefox + this.remoteAddress = remote.ipAddress + this.remotePort = Number(remote.portNumber) + } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') { + // TODO: remove this once Chrome 58 is released + remote = selectedCandidatePair.googRemoteAddress.split(':') + this.remoteAddress = remote[0] + this.remotePort = Number(remote[1]) + } + if (this.remoteAddress) { + this.remoteFamily = this.remoteAddress.includes(':') ? 'IPv6' : 'IPv4' + } + + this._debug( + 'connect local: %s:%s remote: %s:%s', + this.localAddress, this.localPort, this.remoteAddress, this.remotePort + ) + } + + items.forEach(item => { + // Spec-compliant + if (item.type === 'transport' && item.selectedCandidatePairId) { + setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]) + } + + // Old implementations + if ( + (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') || + ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected) + ) { + setSelectedCandidatePair(item) + } + }) + + // Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates + // But wait until at least 1 candidate pair is available + if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) { + setTimeout(findCandidatePair, 100) + return + } else { + this._connecting = false + this._connected = true + } + + if (this._chunk) { + try { + this.send(this._chunk) + } catch (err) { + return this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) + } + this._chunk = null + this._debug('sent chunk from "write before connect"') + + var cb = this._cb + this._cb = null + cb(null) + } + + // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported, + // fallback to using setInterval to implement backpressure. + if (typeof this._channel.bufferedAmountLowThreshold !== 'number') { + this._interval = setInterval(() => this._onInterval(), 150) + if (this._interval.unref) this._interval.unref() + } + + this._debug('connect') + this.emit('connect') + }) + } + findCandidatePair() + } + + _onInterval () { + if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { + return + } + this._onChannelBufferedAmountLow() + } + + _onSignalingStateChange () { + if (this.destroyed) return + + if (this._pc.signalingState === 'stable' && !this._firstStable) { + this._isNegotiating = false + + // HACK: Firefox doesn't yet support removing tracks when signalingState !== 'stable' + this._debug('flushing sender queue', this._sendersAwaitingStable) + this._sendersAwaitingStable.forEach(sender => { + this._pc.removeTrack(sender) + this._queuedNegotiation = true + }) + this._sendersAwaitingStable = [] + + if (this._queuedNegotiation) { + this._debug('flushing negotiation queue') + this._queuedNegotiation = false + this._needsNegotiation() // negotiate again + } + + this._debug('negotiate') + this.emit('negotiate') + } + this._firstStable = false + + this._debug('signalingStateChange %s', this._pc.signalingState) + this.emit('signalingStateChange', this._pc.signalingState) + } + + _onIceCandidate (event) { + if (this.destroyed) return + if (event.candidate && this.trickle) { + this.emit('signal', { + candidate: { + candidate: event.candidate.candidate, + sdpMLineIndex: event.candidate.sdpMLineIndex, + sdpMid: event.candidate.sdpMid + } + }) + } else if (!event.candidate && !this._iceComplete) { + this._iceComplete = true + this.emit('_iceComplete') + } + // as soon as we've received one valid candidate start timeout + if (event.candidate) { + this._startIceCompleteTimeout() + } + } + + _onChannelMessage (event) { + if (this.destroyed) return + var data = event.data + if (data instanceof ArrayBuffer) data = Buffer.from(data) + this.push(data) + } + + _onChannelBufferedAmountLow () { + if (this.destroyed || !this._cb) return + this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount) + var cb = this._cb + this._cb = null + cb(null) + } + + _onChannelOpen () { + if (this._connected || this.destroyed) return + this._debug('on channel open') + this._channelReady = true + this._maybeReady() + } + + _onChannelClose () { + if (this.destroyed) return + this._debug('on channel close') + this.destroy() + } + + _onTrack (event) { + if (this.destroyed) return + + event.streams.forEach(eventStream => { + this._debug('on track') + this.emit('track', event.track, eventStream) + + this._remoteTracks.push({ + track: event.track, + stream: eventStream + }) + + if (this._remoteStreams.some(remoteStream => { + return remoteStream.id === eventStream.id + })) return // Only fire one 'stream' event, even though there may be multiple tracks per stream + + this._remoteStreams.push(eventStream) + queueMicrotask(() => { + this.emit('stream', eventStream) // ensure all tracks have been added + }) + }) + } + + _debug () { + var args = [].slice.call(arguments) + args[0] = '[' + this._id + '] ' + args[0] + debug.apply(null, args) + } +} + +Peer.WEBRTC_SUPPORT = !!getBrowserRTC() + +/** + * Expose peer and data channel config for overriding all Peer + * instances. Otherwise, just set opts.config or opts.channelConfig + * when constructing a Peer. + */ +Peer.config = { + iceServers: [ + { + urls: 'stun:stun.l.google.com:19302' + }, + { + urls: 'stun:global.stun.twilio.com:3478?transport=udp' + } + ], + sdpSemantics: 'unified-plan' +} + +Peer.channelConfig = {} + +module.exports = Peer + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"debug":1404,"get-browser-rtc":280,"queue-microtask":1362,"randombytes":1366,"readable-stream":1420}],1404:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":1405,"_process":1258,"dup":208}],1405:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],1406:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],1407:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],1408:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":1410,"./_stream_writable":1412,"_process":1258,"dup":38,"inherits":317}],1409:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":1411,"dup":39,"inherits":317}],1410:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":1406,"../experimentalWarning":1407,"./_stream_duplex":1408,"./internal/streams/async_iterator":1413,"./internal/streams/buffer_list":1414,"./internal/streams/destroy":1415,"./internal/streams/state":1418,"./internal/streams/stream":1419,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":1422,"util":146}],1411:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":1406,"./_stream_duplex":1408,"dup":41,"inherits":317}],1412:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":1406,"./_stream_duplex":1408,"./internal/streams/destroy":1415,"./internal/streams/state":1418,"./internal/streams/stream":1419,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],1413:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":1416,"_process":1258,"dup":43}],1414:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],1415:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],1416:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":1406,"dup":46}],1417:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":1406,"./end-of-stream":1416,"dup":47}],1418:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":1406,"dup":48}],1419:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],1420:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":1408,"./lib/_stream_passthrough.js":1409,"./lib/_stream_readable.js":1410,"./lib/_stream_transform.js":1411,"./lib/_stream_writable.js":1412,"./lib/internal/streams/end-of-stream.js":1416,"./lib/internal/streams/pipeline.js":1417,"dup":50}],1421:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],1422:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":1421}],1423:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var url = require('./url'); +var parser = require('socket.io-parser'); +var Manager = require('./manager'); +var debug = require('debug')('socket.io-client'); + +/** + * Module exports. + */ + +module.exports = exports = lookup; + +/** + * Managers cache. + */ + +var cache = exports.managers = {}; + +/** + * Looks up an existing `Manager` for multiplexing. + * If the user summons: + * + * `io('http://localhost/a');` + * `io('http://localhost/b');` + * + * We reuse the existing instance based on same scheme/port/host, + * and we initialize sockets for each namespace. + * + * @api public + */ + +function lookup (uri, opts) { + if (typeof uri === 'object') { + opts = uri; + uri = undefined; + } + + opts = opts || {}; + + var parsed = url(uri); + var source = parsed.source; + var id = parsed.id; + var path = parsed.path; + var sameNamespace = cache[id] && path in cache[id].nsps; + var newConnection = opts.forceNew || opts['force new connection'] || + false === opts.multiplex || sameNamespace; + + var io; + + if (newConnection) { + debug('ignoring socket cache for %s', source); + io = Manager(source, opts); + } else { + if (!cache[id]) { + debug('new io instance for %s', source); + cache[id] = Manager(source, opts); + } + io = cache[id]; + } + if (parsed.query && !opts.query) { + opts.query = parsed.query; + } + return io.socket(parsed.path, opts); +} + +/** + * Protocol version. + * + * @api public + */ + +exports.protocol = parser.protocol; + +/** + * `connect`. + * + * @param {String} uri + * @api public + */ + +exports.connect = lookup; + +/** + * Expose constructors for standalone build. + * + * @api public + */ + +exports.Manager = require('./manager'); +exports.Socket = require('./socket'); + +},{"./manager":1424,"./socket":1426,"./url":1427,"debug":1428,"socket.io-parser":1432}],1424:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var eio = require('engine.io-client'); +var Socket = require('./socket'); +var Emitter = require('component-emitter'); +var parser = require('socket.io-parser'); +var on = require('./on'); +var bind = require('component-bind'); +var debug = require('debug')('socket.io-client:manager'); +var indexOf = require('indexof'); +var Backoff = require('backo2'); + +/** + * IE6+ hasOwnProperty + */ + +var has = Object.prototype.hasOwnProperty; + +/** + * Module exports + */ + +module.exports = Manager; + +/** + * `Manager` constructor. + * + * @param {String} engine instance or engine uri/opts + * @param {Object} options + * @api public + */ + +function Manager (uri, opts) { + if (!(this instanceof Manager)) return new Manager(uri, opts); + if (uri && ('object' === typeof uri)) { + opts = uri; + uri = undefined; + } + opts = opts || {}; + + opts.path = opts.path || '/socket.io'; + this.nsps = {}; + this.subs = []; + this.opts = opts; + this.reconnection(opts.reconnection !== false); + this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); + this.reconnectionDelay(opts.reconnectionDelay || 1000); + this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); + this.randomizationFactor(opts.randomizationFactor || 0.5); + this.backoff = new Backoff({ + min: this.reconnectionDelay(), + max: this.reconnectionDelayMax(), + jitter: this.randomizationFactor() + }); + this.timeout(null == opts.timeout ? 20000 : opts.timeout); + this.readyState = 'closed'; + this.uri = uri; + this.connecting = []; + this.lastPing = null; + this.encoding = false; + this.packetBuffer = []; + var _parser = opts.parser || parser; + this.encoder = new _parser.Encoder(); + this.decoder = new _parser.Decoder(); + this.autoConnect = opts.autoConnect !== false; + if (this.autoConnect) this.open(); +} + +/** + * Propagate given event to sockets and emit on `this` + * + * @api private + */ + +Manager.prototype.emitAll = function () { + this.emit.apply(this, arguments); + for (var nsp in this.nsps) { + if (has.call(this.nsps, nsp)) { + this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); + } + } +}; + +/** + * Update `socket.id` of all sockets + * + * @api private + */ + +Manager.prototype.updateSocketIds = function () { + for (var nsp in this.nsps) { + if (has.call(this.nsps, nsp)) { + this.nsps[nsp].id = this.generateId(nsp); + } + } +}; + +/** + * generate `socket.id` for the given `nsp` + * + * @param {String} nsp + * @return {String} + * @api private + */ + +Manager.prototype.generateId = function (nsp) { + return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id; +}; + +/** + * Mix in `Emitter`. + */ + +Emitter(Manager.prototype); + +/** + * Sets the `reconnection` config. + * + * @param {Boolean} true/false if it should automatically reconnect + * @return {Manager} self or value + * @api public + */ + +Manager.prototype.reconnection = function (v) { + if (!arguments.length) return this._reconnection; + this._reconnection = !!v; + return this; +}; + +/** + * Sets the reconnection attempts config. + * + * @param {Number} max reconnection attempts before giving up + * @return {Manager} self or value + * @api public + */ + +Manager.prototype.reconnectionAttempts = function (v) { + if (!arguments.length) return this._reconnectionAttempts; + this._reconnectionAttempts = v; + return this; +}; + +/** + * Sets the delay between reconnections. + * + * @param {Number} delay + * @return {Manager} self or value + * @api public + */ + +Manager.prototype.reconnectionDelay = function (v) { + if (!arguments.length) return this._reconnectionDelay; + this._reconnectionDelay = v; + this.backoff && this.backoff.setMin(v); + return this; +}; + +Manager.prototype.randomizationFactor = function (v) { + if (!arguments.length) return this._randomizationFactor; + this._randomizationFactor = v; + this.backoff && this.backoff.setJitter(v); + return this; +}; + +/** + * Sets the maximum delay between reconnections. + * + * @param {Number} delay + * @return {Manager} self or value + * @api public + */ + +Manager.prototype.reconnectionDelayMax = function (v) { + if (!arguments.length) return this._reconnectionDelayMax; + this._reconnectionDelayMax = v; + this.backoff && this.backoff.setMax(v); + return this; +}; + +/** + * Sets the connection timeout. `false` to disable + * + * @return {Manager} self or value + * @api public + */ + +Manager.prototype.timeout = function (v) { + if (!arguments.length) return this._timeout; + this._timeout = v; + return this; +}; + +/** + * Starts trying to reconnect if reconnection is enabled and we have not + * started reconnecting yet + * + * @api private + */ + +Manager.prototype.maybeReconnectOnOpen = function () { + // Only try to reconnect if it's the first time we're connecting + if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { + // keeps reconnection from firing twice for the same reconnection loop + this.reconnect(); + } +}; + +/** + * Sets the current transport `socket`. + * + * @param {Function} optional, callback + * @return {Manager} self + * @api public + */ + +Manager.prototype.open = +Manager.prototype.connect = function (fn, opts) { + debug('readyState %s', this.readyState); + if (~this.readyState.indexOf('open')) return this; + + debug('opening %s', this.uri); + this.engine = eio(this.uri, this.opts); + var socket = this.engine; + var self = this; + this.readyState = 'opening'; + this.skipReconnect = false; + + // emit `open` + var openSub = on(socket, 'open', function () { + self.onopen(); + fn && fn(); + }); + + // emit `connect_error` + var errorSub = on(socket, 'error', function (data) { + debug('connect_error'); + self.cleanup(); + self.readyState = 'closed'; + self.emitAll('connect_error', data); + if (fn) { + var err = new Error('Connection error'); + err.data = data; + fn(err); + } else { + // Only do this if there is no fn to handle the error + self.maybeReconnectOnOpen(); + } + }); + + // emit `connect_timeout` + if (false !== this._timeout) { + var timeout = this._timeout; + debug('connect attempt will timeout after %d', timeout); + + // set timer + var timer = setTimeout(function () { + debug('connect attempt timed out after %d', timeout); + openSub.destroy(); + socket.close(); + socket.emit('error', 'timeout'); + self.emitAll('connect_timeout', timeout); + }, timeout); + + this.subs.push({ + destroy: function () { + clearTimeout(timer); + } + }); + } + + this.subs.push(openSub); + this.subs.push(errorSub); + + return this; +}; + +/** + * Called upon transport open. + * + * @api private + */ + +Manager.prototype.onopen = function () { + debug('open'); + + // clear old subs + this.cleanup(); + + // mark as open + this.readyState = 'open'; + this.emit('open'); + + // add new subs + var socket = this.engine; + this.subs.push(on(socket, 'data', bind(this, 'ondata'))); + this.subs.push(on(socket, 'ping', bind(this, 'onping'))); + this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); + this.subs.push(on(socket, 'error', bind(this, 'onerror'))); + this.subs.push(on(socket, 'close', bind(this, 'onclose'))); + this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); +}; + +/** + * Called upon a ping. + * + * @api private + */ + +Manager.prototype.onping = function () { + this.lastPing = new Date(); + this.emitAll('ping'); +}; + +/** + * Called upon a packet. + * + * @api private + */ + +Manager.prototype.onpong = function () { + this.emitAll('pong', new Date() - this.lastPing); +}; + +/** + * Called with data. + * + * @api private + */ + +Manager.prototype.ondata = function (data) { + this.decoder.add(data); +}; + +/** + * Called when parser fully decodes a packet. + * + * @api private + */ + +Manager.prototype.ondecoded = function (packet) { + this.emit('packet', packet); +}; + +/** + * Called upon socket error. + * + * @api private + */ + +Manager.prototype.onerror = function (err) { + debug('error', err); + this.emitAll('error', err); +}; + +/** + * Creates a new socket for the given `nsp`. + * + * @return {Socket} + * @api public + */ + +Manager.prototype.socket = function (nsp, opts) { + var socket = this.nsps[nsp]; + if (!socket) { + socket = new Socket(this, nsp, opts); + this.nsps[nsp] = socket; + var self = this; + socket.on('connecting', onConnecting); + socket.on('connect', function () { + socket.id = self.generateId(nsp); + }); + + if (this.autoConnect) { + // manually call here since connecting event is fired before listening + onConnecting(); + } + } + + function onConnecting () { + if (!~indexOf(self.connecting, socket)) { + self.connecting.push(socket); + } + } + + return socket; +}; + +/** + * Called upon a socket close. + * + * @param {Socket} socket + */ + +Manager.prototype.destroy = function (socket) { + var index = indexOf(this.connecting, socket); + if (~index) this.connecting.splice(index, 1); + if (this.connecting.length) return; + + this.close(); +}; + +/** + * Writes a packet. + * + * @param {Object} packet + * @api private + */ + +Manager.prototype.packet = function (packet) { + debug('writing packet %j', packet); + var self = this; + if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; + + if (!self.encoding) { + // encode, then write to engine with result + self.encoding = true; + this.encoder.encode(packet, function (encodedPackets) { + for (var i = 0; i < encodedPackets.length; i++) { + self.engine.write(encodedPackets[i], packet.options); + } + self.encoding = false; + self.processPacketQueue(); + }); + } else { // add packet to the queue + self.packetBuffer.push(packet); + } +}; + +/** + * If packet buffer is non-empty, begins encoding the + * next packet in line. + * + * @api private + */ + +Manager.prototype.processPacketQueue = function () { + if (this.packetBuffer.length > 0 && !this.encoding) { + var pack = this.packetBuffer.shift(); + this.packet(pack); + } +}; + +/** + * Clean up transport subscriptions and packet buffer. + * + * @api private + */ + +Manager.prototype.cleanup = function () { + debug('cleanup'); + + var subsLength = this.subs.length; + for (var i = 0; i < subsLength; i++) { + var sub = this.subs.shift(); + sub.destroy(); + } + + this.packetBuffer = []; + this.encoding = false; + this.lastPing = null; + + this.decoder.destroy(); +}; + +/** + * Close the current socket. + * + * @api private + */ + +Manager.prototype.close = +Manager.prototype.disconnect = function () { + debug('disconnect'); + this.skipReconnect = true; + this.reconnecting = false; + if ('opening' === this.readyState) { + // `onclose` will not fire because + // an open event never happened + this.cleanup(); + } + this.backoff.reset(); + this.readyState = 'closed'; + if (this.engine) this.engine.close(); +}; + +/** + * Called upon engine close. + * + * @api private + */ + +Manager.prototype.onclose = function (reason) { + debug('onclose'); + + this.cleanup(); + this.backoff.reset(); + this.readyState = 'closed'; + this.emit('close', reason); + + if (this._reconnection && !this.skipReconnect) { + this.reconnect(); + } +}; + +/** + * Attempt a reconnection. + * + * @api private + */ + +Manager.prototype.reconnect = function () { + if (this.reconnecting || this.skipReconnect) return this; + + var self = this; + + if (this.backoff.attempts >= this._reconnectionAttempts) { + debug('reconnect failed'); + this.backoff.reset(); + this.emitAll('reconnect_failed'); + this.reconnecting = false; + } else { + var delay = this.backoff.duration(); + debug('will wait %dms before reconnect attempt', delay); + + this.reconnecting = true; + var timer = setTimeout(function () { + if (self.skipReconnect) return; + + debug('attempting reconnect'); + self.emitAll('reconnect_attempt', self.backoff.attempts); + self.emitAll('reconnecting', self.backoff.attempts); + + // check again for the case socket closed in above events + if (self.skipReconnect) return; + + self.open(function (err) { + if (err) { + debug('reconnect attempt error'); + self.reconnecting = false; + self.reconnect(); + self.emitAll('reconnect_error', err.data); + } else { + debug('reconnect success'); + self.onreconnect(); + } + }); + }, delay); + + this.subs.push({ + destroy: function () { + clearTimeout(timer); + } + }); + } +}; + +/** + * Called upon successful reconnect. + * + * @api private + */ + +Manager.prototype.onreconnect = function () { + var attempt = this.backoff.attempts; + this.reconnecting = false; + this.backoff.reset(); + this.updateSocketIds(); + this.emitAll('reconnect', attempt); +}; + +},{"./on":1425,"./socket":1426,"backo2":104,"component-bind":188,"component-emitter":189,"debug":1428,"engine.io-client":254,"indexof":316,"socket.io-parser":1432}],1425:[function(require,module,exports){ + +/** + * Module exports. + */ + +module.exports = on; + +/** + * Helper for subscriptions. + * + * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` + * @param {String} event name + * @param {Function} callback + * @api public + */ + +function on (obj, ev, fn) { + obj.on(ev, fn); + return { + destroy: function () { + obj.removeListener(ev, fn); + } + }; +} + +},{}],1426:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var parser = require('socket.io-parser'); +var Emitter = require('component-emitter'); +var toArray = require('to-array'); +var on = require('./on'); +var bind = require('component-bind'); +var debug = require('debug')('socket.io-client:socket'); +var parseqs = require('parseqs'); +var hasBin = require('has-binary2'); + +/** + * Module exports. + */ + +module.exports = exports = Socket; + +/** + * Internal events (blacklisted). + * These events can't be emitted by the user. + * + * @api private + */ + +var events = { + connect: 1, + connect_error: 1, + connect_timeout: 1, + connecting: 1, + disconnect: 1, + error: 1, + reconnect: 1, + reconnect_attempt: 1, + reconnect_failed: 1, + reconnect_error: 1, + reconnecting: 1, + ping: 1, + pong: 1 +}; + +/** + * Shortcut to `Emitter#emit`. + */ + +var emit = Emitter.prototype.emit; + +/** + * `Socket` constructor. + * + * @api public + */ + +function Socket (io, nsp, opts) { + this.io = io; + this.nsp = nsp; + this.json = this; // compat + this.ids = 0; + this.acks = {}; + this.receiveBuffer = []; + this.sendBuffer = []; + this.connected = false; + this.disconnected = true; + this.flags = {}; + if (opts && opts.query) { + this.query = opts.query; + } + if (this.io.autoConnect) this.open(); +} + +/** + * Mix in `Emitter`. + */ + +Emitter(Socket.prototype); + +/** + * Subscribe to open, close and packet events + * + * @api private + */ + +Socket.prototype.subEvents = function () { + if (this.subs) return; + + var io = this.io; + this.subs = [ + on(io, 'open', bind(this, 'onopen')), + on(io, 'packet', bind(this, 'onpacket')), + on(io, 'close', bind(this, 'onclose')) + ]; +}; + +/** + * "Opens" the socket. + * + * @api public + */ + +Socket.prototype.open = +Socket.prototype.connect = function () { + if (this.connected) return this; + + this.subEvents(); + this.io.open(); // ensure open + if ('open' === this.io.readyState) this.onopen(); + this.emit('connecting'); + return this; +}; + +/** + * Sends a `message` event. + * + * @return {Socket} self + * @api public + */ + +Socket.prototype.send = function () { + var args = toArray(arguments); + args.unshift('message'); + this.emit.apply(this, args); + return this; +}; + +/** + * Override `emit`. + * If the event is in `events`, it's emitted normally. + * + * @param {String} event name + * @return {Socket} self + * @api public + */ + +Socket.prototype.emit = function (ev) { + if (events.hasOwnProperty(ev)) { + emit.apply(this, arguments); + return this; + } + + var args = toArray(arguments); + var packet = { + type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT, + data: args + }; + + packet.options = {}; + packet.options.compress = !this.flags || false !== this.flags.compress; + + // event ack callback + if ('function' === typeof args[args.length - 1]) { + debug('emitting packet with ack id %d', this.ids); + this.acks[this.ids] = args.pop(); + packet.id = this.ids++; + } + + if (this.connected) { + this.packet(packet); + } else { + this.sendBuffer.push(packet); + } + + this.flags = {}; + + return this; +}; + +/** + * Sends a packet. + * + * @param {Object} packet + * @api private + */ + +Socket.prototype.packet = function (packet) { + packet.nsp = this.nsp; + this.io.packet(packet); +}; + +/** + * Called upon engine `open`. + * + * @api private + */ + +Socket.prototype.onopen = function () { + debug('transport is open - connecting'); + + // write connect packet if necessary + if ('/' !== this.nsp) { + if (this.query) { + var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query; + debug('sending connect packet with query %s', query); + this.packet({type: parser.CONNECT, query: query}); + } else { + this.packet({type: parser.CONNECT}); + } + } +}; + +/** + * Called upon engine `close`. + * + * @param {String} reason + * @api private + */ + +Socket.prototype.onclose = function (reason) { + debug('close (%s)', reason); + this.connected = false; + this.disconnected = true; + delete this.id; + this.emit('disconnect', reason); +}; + +/** + * Called with socket packet. + * + * @param {Object} packet + * @api private + */ + +Socket.prototype.onpacket = function (packet) { + var sameNamespace = packet.nsp === this.nsp; + var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/'; + + if (!sameNamespace && !rootNamespaceError) return; + + switch (packet.type) { + case parser.CONNECT: + this.onconnect(); + break; + + case parser.EVENT: + this.onevent(packet); + break; + + case parser.BINARY_EVENT: + this.onevent(packet); + break; + + case parser.ACK: + this.onack(packet); + break; + + case parser.BINARY_ACK: + this.onack(packet); + break; + + case parser.DISCONNECT: + this.ondisconnect(); + break; + + case parser.ERROR: + this.emit('error', packet.data); + break; + } +}; + +/** + * Called upon a server event. + * + * @param {Object} packet + * @api private + */ + +Socket.prototype.onevent = function (packet) { + var args = packet.data || []; + debug('emitting event %j', args); + + if (null != packet.id) { + debug('attaching ack callback to event'); + args.push(this.ack(packet.id)); + } + + if (this.connected) { + emit.apply(this, args); + } else { + this.receiveBuffer.push(args); + } +}; + +/** + * Produces an ack callback to emit with an event. + * + * @api private + */ + +Socket.prototype.ack = function (id) { + var self = this; + var sent = false; + return function () { + // prevent double callbacks + if (sent) return; + sent = true; + var args = toArray(arguments); + debug('sending ack %j', args); + + self.packet({ + type: hasBin(args) ? parser.BINARY_ACK : parser.ACK, + id: id, + data: args + }); + }; +}; + +/** + * Called upon a server acknowlegement. + * + * @param {Object} packet + * @api private + */ + +Socket.prototype.onack = function (packet) { + var ack = this.acks[packet.id]; + if ('function' === typeof ack) { + debug('calling ack %s with %j', packet.id, packet.data); + ack.apply(this, packet.data); + delete this.acks[packet.id]; + } else { + debug('bad ack %s', packet.id); + } +}; + +/** + * Called upon server connect. + * + * @api private + */ + +Socket.prototype.onconnect = function () { + this.connected = true; + this.disconnected = false; + this.emit('connect'); + this.emitBuffered(); +}; + +/** + * Emit buffered events (received and emitted). + * + * @api private + */ + +Socket.prototype.emitBuffered = function () { + var i; + for (i = 0; i < this.receiveBuffer.length; i++) { + emit.apply(this, this.receiveBuffer[i]); + } + this.receiveBuffer = []; + + for (i = 0; i < this.sendBuffer.length; i++) { + this.packet(this.sendBuffer[i]); + } + this.sendBuffer = []; +}; + +/** + * Called upon server disconnect. + * + * @api private + */ + +Socket.prototype.ondisconnect = function () { + debug('server disconnect (%s)', this.nsp); + this.destroy(); + this.onclose('io server disconnect'); +}; + +/** + * Called upon forced client/server side disconnections, + * this method ensures the manager stops tracking us and + * that reconnections don't get triggered for this. + * + * @api private. + */ + +Socket.prototype.destroy = function () { + if (this.subs) { + // clean subscriptions to avoid reconnections + for (var i = 0; i < this.subs.length; i++) { + this.subs[i].destroy(); + } + this.subs = null; + } + + this.io.destroy(this); +}; + +/** + * Disconnects the socket manually. + * + * @return {Socket} self + * @api public + */ + +Socket.prototype.close = +Socket.prototype.disconnect = function () { + if (this.connected) { + debug('performing disconnect (%s)', this.nsp); + this.packet({ type: parser.DISCONNECT }); + } + + // remove socket from pool + this.destroy(); + + if (this.connected) { + // fire events + this.onclose('io client disconnect'); + } + return this; +}; + +/** + * Sets the compress flag. + * + * @param {Boolean} if `true`, compresses the sending data + * @return {Socket} self + * @api public + */ + +Socket.prototype.compress = function (compress) { + this.flags.compress = compress; + return this; +}; + +/** + * Sets the binary flag + * + * @param {Boolean} whether the emitted data contains binary + * @return {Socket} self + * @api public + */ + +Socket.prototype.binary = function (binary) { + this.flags.binary = binary; + return this; +}; + +},{"./on":1425,"component-bind":188,"component-emitter":189,"debug":1428,"has-binary2":290,"parseqs":1244,"socket.io-parser":1432,"to-array":1502}],1427:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var parseuri = require('parseuri'); +var debug = require('debug')('socket.io-client:url'); + +/** + * Module exports. + */ + +module.exports = url; + +/** + * URL parser. + * + * @param {String} url + * @param {Object} An object meant to mimic window.location. + * Defaults to window.location. + * @api public + */ + +function url (uri, loc) { + var obj = uri; + + // default to window.location + loc = loc || (typeof location !== 'undefined' && location); + if (null == uri) uri = loc.protocol + '//' + loc.host; + + // relative path support + if ('string' === typeof uri) { + if ('/' === uri.charAt(0)) { + if ('/' === uri.charAt(1)) { + uri = loc.protocol + uri; + } else { + uri = loc.host + uri; + } + } + + if (!/^(https?|wss?):\/\//.test(uri)) { + debug('protocol-less url %s', uri); + if ('undefined' !== typeof loc) { + uri = loc.protocol + '//' + uri; + } else { + uri = 'https://' + uri; + } + } + + // parse + debug('parse %s', uri); + obj = parseuri(uri); + } + + // make sure we treat `localhost:80` and `localhost` equally + if (!obj.port) { + if (/^(http|ws)$/.test(obj.protocol)) { + obj.port = '80'; + } else if (/^(http|ws)s$/.test(obj.protocol)) { + obj.port = '443'; + } + } + + obj.path = obj.path || '/'; + + var ipv6 = obj.host.indexOf(':') !== -1; + var host = ipv6 ? '[' + obj.host + ']' : obj.host; + + // define unique id + obj.id = obj.protocol + '://' + host + ':' + obj.port; + // define href + obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port)); + + return obj; +} + +},{"debug":1428,"parseuri":1245}],1428:[function(require,module,exports){ +arguments[4][208][0].apply(exports,arguments) +},{"./common":1429,"_process":1258,"dup":208}],1429:[function(require,module,exports){ +arguments[4][209][0].apply(exports,arguments) +},{"dup":209,"ms":1136}],1430:[function(require,module,exports){ +arguments[4][291][0].apply(exports,arguments) +},{"dup":291}],1431:[function(require,module,exports){ +/*global Blob,File*/ + +/** + * Module requirements + */ + +var isArray = require('isarray'); +var isBuf = require('./is-buffer'); +var toString = Object.prototype.toString; +var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'); +var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'); + +/** + * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. + * Anything with blobs or files should be fed through removeBlobs before coming + * here. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @api public + */ + +exports.deconstructPacket = function(packet) { + var buffers = []; + var packetData = packet.data; + var pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + return {packet: pack, buffers: buffers}; +}; + +function _deconstructPacket(data, buffers) { + if (!data) return data; + + if (isBuf(data)) { + var placeholder = { _placeholder: true, num: buffers.length }; + buffers.push(data); + return placeholder; + } else if (isArray(data)) { + var newData = new Array(data.length); + for (var i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + return newData; + } else if (typeof data === 'object' && !(data instanceof Date)) { + var newData = {}; + for (var key in data) { + newData[key] = _deconstructPacket(data[key], buffers); + } + return newData; + } + return data; +} + +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @api public + */ + +exports.reconstructPacket = function(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + return packet; +}; + +function _reconstructPacket(data, buffers) { + if (!data) return data; + + if (data && data._placeholder) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } else if (isArray(data)) { + for (var i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } else if (typeof data === 'object') { + for (var key in data) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + + return data; +} + +/** + * Asynchronously removes Blobs or Files from data via + * FileReader's readAsArrayBuffer method. Used before encoding + * data as msgpack. Calls callback with the blobless data. + * + * @param {Object} data + * @param {Function} callback + * @api private + */ + +exports.removeBlobs = function(data, callback) { + function _removeBlobs(obj, curKey, containingObject) { + if (!obj) return obj; + + // convert any blob + if ((withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File)) { + pendingBlobs++; + + // async filereader + var fileReader = new FileReader(); + fileReader.onload = function() { // this.result == arraybuffer + if (containingObject) { + containingObject[curKey] = this.result; + } + else { + bloblessData = this.result; + } + + // if nothing pending its callback time + if(! --pendingBlobs) { + callback(bloblessData); + } + }; + + fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer + } else if (isArray(obj)) { // handle array + for (var i = 0; i < obj.length; i++) { + _removeBlobs(obj[i], i, obj); + } + } else if (typeof obj === 'object' && !isBuf(obj)) { // and object + for (var key in obj) { + _removeBlobs(obj[key], key, obj); + } + } + } + + var pendingBlobs = 0; + var bloblessData = data; + _removeBlobs(bloblessData); + if (!pendingBlobs) { + callback(bloblessData); + } +}; + +},{"./is-buffer":1433,"isarray":1430}],1432:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var debug = require('debug')('socket.io-parser'); +var Emitter = require('component-emitter'); +var binary = require('./binary'); +var isArray = require('isarray'); +var isBuf = require('./is-buffer'); + +/** + * Protocol version. + * + * @api public + */ + +exports.protocol = 4; + +/** + * Packet types. + * + * @api public + */ + +exports.types = [ + 'CONNECT', + 'DISCONNECT', + 'EVENT', + 'ACK', + 'ERROR', + 'BINARY_EVENT', + 'BINARY_ACK' +]; + +/** + * Packet type `connect`. + * + * @api public + */ + +exports.CONNECT = 0; + +/** + * Packet type `disconnect`. + * + * @api public + */ + +exports.DISCONNECT = 1; + +/** + * Packet type `event`. + * + * @api public + */ + +exports.EVENT = 2; + +/** + * Packet type `ack`. + * + * @api public + */ + +exports.ACK = 3; + +/** + * Packet type `error`. + * + * @api public + */ + +exports.ERROR = 4; + +/** + * Packet type 'binary event' + * + * @api public + */ + +exports.BINARY_EVENT = 5; + +/** + * Packet type `binary ack`. For acks with binary arguments. + * + * @api public + */ + +exports.BINARY_ACK = 6; + +/** + * Encoder constructor. + * + * @api public + */ + +exports.Encoder = Encoder; + +/** + * Decoder constructor. + * + * @api public + */ + +exports.Decoder = Decoder; + +/** + * A socket.io Encoder instance + * + * @api public + */ + +function Encoder() {} + +var ERROR_PACKET = exports.ERROR + '"encode error"'; + +/** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + * @param {Function} callback - function to handle encodings (likely engine.write) + * @return Calls callback with Array of encodings + * @api public + */ + +Encoder.prototype.encode = function(obj, callback){ + debug('encoding packet %j', obj); + + if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { + encodeAsBinary(obj, callback); + } else { + var encoding = encodeAsString(obj); + callback([encoding]); + } +}; + +/** + * Encode packet as string. + * + * @param {Object} packet + * @return {String} encoded + * @api private + */ + +function encodeAsString(obj) { + + // first is type + var str = '' + obj.type; + + // attachments if we have them + if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { + str += obj.attachments + '-'; + } + + // if we have a namespace other than `/` + // we append it followed by a comma `,` + if (obj.nsp && '/' !== obj.nsp) { + str += obj.nsp + ','; + } + + // immediately followed by the id + if (null != obj.id) { + str += obj.id; + } + + // json data + if (null != obj.data) { + var payload = tryStringify(obj.data); + if (payload !== false) { + str += payload; + } else { + return ERROR_PACKET; + } + } + + debug('encoded %j as %s', obj, str); + return str; +} + +function tryStringify(str) { + try { + return JSON.stringify(str); + } catch(e){ + return false; + } +} + +/** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + * + * @param {Object} packet + * @return {Buffer} encoded + * @api private + */ + +function encodeAsBinary(obj, callback) { + + function writeEncoding(bloblessData) { + var deconstruction = binary.deconstructPacket(bloblessData); + var pack = encodeAsString(deconstruction.packet); + var buffers = deconstruction.buffers; + + buffers.unshift(pack); // add packet info to beginning of data list + callback(buffers); // write all the buffers + } + + binary.removeBlobs(obj, writeEncoding); +} + +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + * @api public + */ + +function Decoder() { + this.reconstructor = null; +} + +/** + * Mix in `Emitter` with Decoder. + */ + +Emitter(Decoder.prototype); + +/** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + * @return {Object} packet + * @api public + */ + +Decoder.prototype.add = function(obj) { + var packet; + if (typeof obj === 'string') { + packet = decodeString(obj); + if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); + + // no attachments, labeled binary but no binary data to follow + if (this.reconstructor.reconPack.attachments === 0) { + this.emit('decoded', packet); + } + } else { // non-binary full packet + this.emit('decoded', packet); + } + } else if (isBuf(obj) || obj.base64) { // raw binary data + if (!this.reconstructor) { + throw new Error('got binary data when not reconstructing a packet'); + } else { + packet = this.reconstructor.takeBinaryData(obj); + if (packet) { // received final buffer + this.reconstructor = null; + this.emit('decoded', packet); + } + } + } else { + throw new Error('Unknown type: ' + obj); + } +}; + +/** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + * @api private + */ + +function decodeString(str) { + var i = 0; + // look up type + var p = { + type: Number(str.charAt(0)) + }; + + if (null == exports.types[p.type]) { + return error('unknown packet type ' + p.type); + } + + // look up attachments if type binary + if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { + var buf = ''; + while (str.charAt(++i) !== '-') { + buf += str.charAt(i); + if (i == str.length) break; + } + if (buf != Number(buf) || str.charAt(i) !== '-') { + throw new Error('Illegal attachments'); + } + p.attachments = Number(buf); + } + + // look up namespace (if any) + if ('/' === str.charAt(i + 1)) { + p.nsp = ''; + while (++i) { + var c = str.charAt(i); + if (',' === c) break; + p.nsp += c; + if (i === str.length) break; + } + } else { + p.nsp = '/'; + } + + // look up id + var next = str.charAt(i + 1); + if ('' !== next && Number(next) == next) { + p.id = ''; + while (++i) { + var c = str.charAt(i); + if (null == c || Number(c) != c) { + --i; + break; + } + p.id += str.charAt(i); + if (i === str.length) break; + } + p.id = Number(p.id); + } + + // look up json data + if (str.charAt(++i)) { + var payload = tryParse(str.substr(i)); + var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload)); + if (isPayloadValid) { + p.data = payload; + } else { + return error('invalid payload'); + } + } + + debug('decoded %s as %j', str, p); + return p; +} + +function tryParse(str) { + try { + return JSON.parse(str); + } catch(e){ + return false; + } +} + +/** + * Deallocates a parser's resources + * + * @api public + */ + +Decoder.prototype.destroy = function() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } +}; + +/** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + * @api private + */ + +function BinaryReconstructor(packet) { + this.reconPack = packet; + this.buffers = []; +} + +/** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + * @api private + */ + +BinaryReconstructor.prototype.takeBinaryData = function(binData) { + this.buffers.push(binData); + if (this.buffers.length === this.reconPack.attachments) { // done with buffer list + var packet = binary.reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + return null; +}; + +/** + * Cleans up binary packet reconstruction variables. + * + * @api private + */ + +BinaryReconstructor.prototype.finishedReconstruction = function() { + this.reconPack = null; + this.buffers = []; +}; + +function error(msg) { + return { + type: exports.ERROR, + data: 'parser error: ' + msg + }; +} + +},{"./binary":1431,"./is-buffer":1433,"component-emitter":189,"debug":1434,"isarray":1430}],1433:[function(require,module,exports){ +(function (Buffer){ + +module.exports = isBuf; + +var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function'; +var withNativeArrayBuffer = typeof ArrayBuffer === 'function'; + +var isView = function (obj) { + return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer); +}; + +/** + * Returns true if obj is a buffer or an arraybuffer. + * + * @api private + */ + +function isBuf(obj) { + return (withNativeBuffer && Buffer.isBuffer(obj)) || + (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))); +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181}],1434:[function(require,module,exports){ +(function (process){ +/** + * 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. + */ + +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' +]; + +/** + * 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 + */ + +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; + } + + // 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. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } }; -module.exports = randomHex; +/** + * Colorize log arguments if enabled. + * + * @api public + */ -},{"./crypto.js":1555}],1557:[function(require,module,exports){ +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 + 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; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * 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); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +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 + */ + +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; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +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) {} +} + +}).call(this,require('_process')) +},{"./debug":1435,"_process":1258}],1435:[function(require,module,exports){ + +/** + * 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'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * The currently active debug mode names, and names to skip. + */ + +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". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + 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]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + 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; + + // 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]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // 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); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // 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); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +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 + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + 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 + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +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; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":1436}],1436:[function(require,module,exports){ +arguments[4][676][0].apply(exports,arguments) +},{"dup":676}],1437:[function(require,module,exports){ +(function (Buffer){ +'use strict' + +// socket.io-pull-stream +const Queue = require('data-queue') +const uuid = require('uuid') +const pull = require('pull-stream') +const sioname = (type, name) => 'socket.io-pull-stream.' + type + (name ? '.' + name : '') +const debug = require('debug') +const _log = debug('socket.io-pull-stream') + +function doCodec (codec, data) { + if (data == null) return data + try { + return codec(data) + } catch (e) { + console.error('Codec Error') + console.error(e) + return false + } +} + +const codecs = { + hex: { + encode: v => v.toString('hex'), + decode: v => Buffer.from(v, 'hex') + }, + plain: { + encode: v => v, + decode: v => v + }, + buffer: { // always do Buffer.from because browsers + encode: v => Buffer.from(v), + decode: v => Buffer.from(v) + } +} + +function getCodec (c) { + if (!c) c = 'plain' + if (typeof c === 'object') return c + const co = codecs[c] + if (!co) throw new Error('Invalid codec ' + c) + return co +} + +function SIOSource (sio, id, opt) { + const q = Queue() + const log = sio.sioplog.bind(sio.sioplog, 'source(' + id + ')') + const codec = getCodec(opt.codec).decode + log('create source') + sio.emit(sioname('accept', id)) + + function unlisten () { + sio.removeAllListeners(sioname('error', id)) + sio.removeAllListeners(sioname('queue', id)) + } + + sio.on(sioname('error', id), err => { + if (err === true) log('finish') + else log('error') + unlisten() + q.append({end: err}) + }) + sio.on(sioname('queue', id), data => { + log('queue data') + q.append({data: doCodec(codec, data)}) + }) + sio.once('disconnect', () => { + unlisten() + q.append({end: true}) + }) + return function (end, cb) { + log('reading') + if (end) return cb(end) + q.get((err, data) => { + if (err) return cb(err) + if (data.end) { + q.error(data.end) + return cb(data.end) + } + return cb(null, data.data) + }) + } +} + +function SIOSink (sio, id, opt) { + const q = Queue() + const log = sio.sioplog.bind(sio.sioplog, ' sink(' + id + ')') + const codec = getCodec(opt.codec).encode + let ended + log('create sink') + sio.once(sioname('accept', id), () => { + log('start transmission') + + function loop () { + q.get((_, val) => { + let {data, err} = val || {} + if (_) err = _ + log('send', err && err === true ? 'finish' : err ? 'error' : data ? 'data' : '') + if (err && !_) q.error(err) + if (err) return sio.emit(sioname('error', id), err) + if (data) sio.emit(sioname('queue', id), doCodec(codec, data)) + loop() + }) + } + loop() + }) + + function doErr (end) { + q.append({err: end}) + ended = end + } + + sio.once('disconnect', () => doErr(true)) + + return function (read) { + read(null, function next (end, data) { + if (end) return doErr(end) + if (ended) return read(ended, next) + q.append({data}) + read(null, next) + }) + } +} + +module.exports = function SIOPullStream (sio, opt) { + if (sio.createSink) return + sio.sioplog = sio.id ? _log.bind(_log, '[' + sio.id + ']') : _log + sio.createSink = (id, _) => { + if (!id) id = uuid() + const sink = SIOSink(sio, id, opt || _) + sink.id = id + return sink + } + sio.createSource = (id, _) => { + const source = SIOSource(sio, id, opt || _) + source.id = id + return source + } + sio.createProxy = (id, tsio, _) => { + pull( + sio.createSource(id, _), + tsio.createSink(id, _) + ) + } +} + +}).call(this,require("buffer").Buffer) +},{"buffer":181,"data-queue":198,"debug":213,"pull-stream":1311,"uuid":1513}],1438:[function(require,module,exports){ +'use strict'; +const isPlainObj = require('is-plain-obj'); + +module.exports = (obj, opts) => { + if (!isPlainObj(obj)) { + throw new TypeError('Expected a plain object'); + } + + opts = opts || {}; + + // DEPRECATED + if (typeof opts === 'function') { + throw new TypeError('Specify the compare function as an option instead'); + } + + const deep = opts.deep; + const seenInput = []; + const seenOutput = []; + + const sortKeys = x => { + const seenIndex = seenInput.indexOf(x); + + if (seenIndex !== -1) { + return seenOutput[seenIndex]; + } + + const ret = {}; + const keys = Object.keys(x).sort(opts.compare); + + seenInput.push(x); + seenOutput.push(ret); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = x[key]; + + if (deep && Array.isArray(val)) { + const retArr = []; + + for (let j = 0; j < val.length; j++) { + retArr[j] = isPlainObj(val[j]) ? sortKeys(val[j]) : val[j]; + } + + ret[key] = retArr; + continue; + } + + ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val; + } + + return ret; + }; + + return sortKeys(obj); +}; + +},{"is-plain-obj":615}],1439:[function(require,module,exports){ +'use strict' + +// JS treats subjects of bitwise operators as SIGNED 32 bit numbers, +// which means the maximum amount of bits we can store inside each byte +// is 7.. +const BITS_PER_BYTE = 7 + +module.exports = class SparseArray { + constructor () { + this._bitArrays = [] + this._data = [] + this._length = 0 + this._changedLength = false + this._changedData = false + } + + set (index, value) { + let pos = this._internalPositionFor(index, false) + if (value === undefined) { + // unsetting + if (pos !== -1) { + // remove item from bit array and array itself + this._unsetInternalPos(pos) + this._unsetBit(index) + this._changedLength = true + this._changedData = true + } + } else { + let needsSort = false + if (pos === -1) { + pos = this._data.length + this._setBit(index) + this._changedData = true + } else { + needsSort = true + } + this._setInternalPos(pos, index, value, needsSort) + this._changedLength = true + } + } + + unset (index) { + this.set(index, undefined) + } + + get (index) { + this._sortData() + const pos = this._internalPositionFor(index, true) + if (pos === -1) { + return undefined + } + return this._data[pos][1] + } + + push (value) { + this.set(this.length, value) + return this.length + } + + get length () { + this._sortData() + if (this._changedLength) { + const last = this._data[this._data.length - 1] + this._length = last ? last[0] + 1 : 0 + this._changedLength = false + } + return this._length + } + + forEach (iterator) { + let i = 0 + while(i < this.length) { + iterator(this.get(i), i, this) + i++ + } + } + + map (iterator) { + let i = 0 + let mapped = new Array(this.length) + while(i < this.length) { + mapped[i] = iterator(this.get(i), i, this) + i++ + } + return mapped + } + + reduce (reducer, initialValue) { + let i = 0 + let acc = initialValue + while(i < this.length) { + const value = this.get(i) + acc = reducer(acc, value, i) + i++ + } + return acc + } + + find (finder) { + let i = 0, found, last + while ((i < this.length) && !found) { + last = this.get(i) + found = finder(last) + i++ + } + return found ? last : undefined + } + + _internalPositionFor (index, noCreate) { + const bytePos = this._bytePosFor(index, noCreate) + if (bytePos >= this._bitArrays.length) { + return -1 + } + const byte = this._bitArrays[bytePos] + const bitPos = index - bytePos * BITS_PER_BYTE + const exists = (byte & (1 << bitPos)) > 0 + if (!exists) { + return -1 + } + const previousPopCount = this._bitArrays.slice(0, bytePos).reduce(popCountReduce, 0) + + const mask = ~(0xffffffff << (bitPos + 1)) + const bytePopCount = popCount(byte & mask) + const arrayPos = previousPopCount + bytePopCount - 1 + return arrayPos + } + + _bytePosFor (index, noCreate) { + const bytePos = Math.floor(index / BITS_PER_BYTE) + const targetLength = bytePos + 1 + while (!noCreate && this._bitArrays.length < targetLength) { + this._bitArrays.push(0) + } + return bytePos + } + + _setBit (index) { + const bytePos = this._bytePosFor(index, false) + this._bitArrays[bytePos] |= (1 << (index - (bytePos * BITS_PER_BYTE))) + } + + _unsetBit(index) { + const bytePos = this._bytePosFor(index, false) + this._bitArrays[bytePos] &= ~(1 << (index - (bytePos * BITS_PER_BYTE))) + } + + _setInternalPos(pos, index, value, needsSort) { + const data =this._data + const elem = [index, value] + if (needsSort) { + this._sortData() + data[pos] = elem + } else { + // new element. just shove it into the array + // but be nice about where we shove it + // in order to make sorting it later easier + if (data.length) { + if (data[data.length - 1][0] >= index) { + data.push(elem) + } else if (data[0][0] <= index) { + data.unshift(elem) + } else { + const randomIndex = Math.round(data.length / 2) + this._data = data.slice(0, randomIndex).concat(elem).concat(data.slice(randomIndex)) + } + } else { + this._data.push(elem) + } + this._changedData = true + this._changedLength = true + } + } + + _unsetInternalPos (pos) { + this._data.splice(pos, 1) + } + + _sortData () { + if (this._changedData) { + this._data.sort(sortInternal) + } + + this._changedData = false + } + + bitField () { + const bytes = [] + let pendingBitsForResultingByte = 8 + let pendingBitsForNewByte = 0 + let resultingByte = 0 + let newByte + const pending = this._bitArrays.slice() + while (pending.length || pendingBitsForNewByte) { + if (pendingBitsForNewByte === 0) { + newByte = pending.shift() + pendingBitsForNewByte = 7 + } + + const usingBits = Math.min(pendingBitsForNewByte, pendingBitsForResultingByte) + const mask = ~(0b11111111 << usingBits) + const masked = newByte & mask + resultingByte |= masked << (8 - pendingBitsForResultingByte) + newByte = newByte >>> usingBits + pendingBitsForNewByte -= usingBits + pendingBitsForResultingByte -= usingBits + + if (!pendingBitsForResultingByte || (!pendingBitsForNewByte && !pending.length)) { + bytes.push(resultingByte) + resultingByte = 0 + pendingBitsForResultingByte = 8 + } + } + + // remove trailing zeroes + for(var i = bytes.length - 1; i > 0; i--) { + const value = bytes[i] + if (value === 0) { + bytes.pop() + } else { + break + } + } + + return bytes + } + + compactArray () { + this._sortData() + return this._data.map(valueOnly) + } +} + +function popCountReduce (count, byte) { + return count + popCount(byte) +} + +function popCount(_v) { + let v = _v + v = v - ((v >> 1) & 0x55555555) // reuse input as temporary + v = (v & 0x33333333) + ((v >> 2) & 0x33333333) // temp + return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24 +} + +function sortInternal (a, b) { + return a[0] - b[0] +} + +function valueOnly (elem) { + return elem[1] +} +},{}],1440:[function(require,module,exports){ +/* +Copyright (c) 2014-2018, Matteo Collina + +Permission to use, copy, modify, and/or 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. +*/ + +'use strict' + +const { Transform } = require('readable-stream') +const { StringDecoder } = require('string_decoder') +const kLast = Symbol('last') +const kDecoder = Symbol('decoder') + +function transform (chunk, enc, cb) { + var list + if (this.overflow) { // Line buffer is full. Skip to start of next line. + var buf = this[kDecoder].write(chunk) + list = buf.split(this.matcher) + + if (list.length === 1) return cb() // Line ending not found. Discard entire chunk. + + // Line ending found. Discard trailing fragment of previous line and reset overflow state. + list.shift() + this.overflow = false + } else { + this[kLast] += this[kDecoder].write(chunk) + list = this[kLast].split(this.matcher) + } + + this[kLast] = list.pop() + + for (var i = 0; i < list.length; i++) { + push(this, this.mapper(list[i])) + } + + this.overflow = this[kLast].length > this.maxLength + if (this.overflow && !this.skipOverflow) return cb(new Error('maximum buffer reached')) + + cb() +} + +function flush (cb) { + // forward any gibberish left in there + this[kLast] += this[kDecoder].end() + + if (this[kLast]) { + push(this, this.mapper(this[kLast])) + } + + cb() +} + +function push (self, val) { + if (val !== undefined) { + self.push(val) + } +} + +function noop (incoming) { + return incoming +} + +function split (matcher, mapper, options) { + // Set defaults for any arguments not supplied. + matcher = matcher || /\r?\n/ + mapper = mapper || noop + options = options || {} + + // Test arguments explicitly. + switch (arguments.length) { + case 1: + // If mapper is only argument. + if (typeof matcher === 'function') { + mapper = matcher + matcher = /\r?\n/ + // If options is only argument. + } else if (typeof matcher === 'object' && !(matcher instanceof RegExp)) { + options = matcher + matcher = /\r?\n/ + } + break + + case 2: + // If mapper and options are arguments. + if (typeof matcher === 'function') { + options = mapper + mapper = matcher + matcher = /\r?\n/ + // If matcher and options are arguments. + } else if (typeof mapper === 'object') { + options = mapper + mapper = noop + } + } + + options = Object.assign({}, options) + options.transform = transform + options.flush = flush + options.readableObjectMode = true + + const stream = new Transform(options) + + stream[kLast] = '' + stream[kDecoder] = new StringDecoder('utf8') + stream.matcher = matcher + stream.mapper = mapper + stream.maxLength = options.maxLength + stream.skipOverflow = options.skipOverflow + stream.overflow = false + + return stream +} + +module.exports = split + +},{"readable-stream":1455,"string_decoder":175}],1441:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],1442:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],1443:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":1445,"./_stream_writable":1447,"_process":1258,"dup":38,"inherits":317}],1444:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":1446,"dup":39,"inherits":317}],1445:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":1441,"../experimentalWarning":1442,"./_stream_duplex":1443,"./internal/streams/async_iterator":1448,"./internal/streams/buffer_list":1449,"./internal/streams/destroy":1450,"./internal/streams/state":1453,"./internal/streams/stream":1454,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":1457,"util":146}],1446:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":1441,"./_stream_duplex":1443,"dup":41,"inherits":317}],1447:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":1441,"./_stream_duplex":1443,"./internal/streams/destroy":1450,"./internal/streams/state":1453,"./internal/streams/stream":1454,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],1448:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":1451,"_process":1258,"dup":43}],1449:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],1450:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],1451:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":1441,"dup":46}],1452:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":1441,"./end-of-stream":1451,"dup":47}],1453:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":1441,"dup":48}],1454:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],1455:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":1443,"./lib/_stream_passthrough.js":1444,"./lib/_stream_readable.js":1445,"./lib/_stream_transform.js":1446,"./lib/_stream_writable.js":1447,"./lib/internal/streams/end-of-stream.js":1451,"./lib/internal/streams/pipeline.js":1452,"dup":50}],1456:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],1457:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":1456}],1458:[function(require,module,exports){ +//! stable.js 0.1.8, https://github.com/Two-Screen/stable +//! © 2018 Angry Bytes and contributors. MIT licensed. + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.stable = factory()); +}(this, (function () { 'use strict'; + + // A stable array sort, because `Array#sort()` is not guaranteed stable. + // This is an implementation of merge sort, without recursion. + + var stable = function (arr, comp) { + return exec(arr.slice(), comp) + }; + + stable.inplace = function (arr, comp) { + var result = exec(arr, comp); + + // This simply copies back if the result isn't in the original array, + // which happens on an odd number of passes. + if (result !== arr) { + pass(result, null, arr.length, arr); + } + + return arr + }; + + // Execute the sort using the input array and a second buffer as work space. + // Returns one of those two, containing the final result. + function exec(arr, comp) { + if (typeof(comp) !== 'function') { + comp = function (a, b) { + return String(a).localeCompare(b) + }; + } + + // Short-circuit when there's nothing to sort. + var len = arr.length; + if (len <= 1) { + return arr + } + + // Rather than dividing input, simply iterate chunks of 1, 2, 4, 8, etc. + // Chunks are the size of the left or right hand in merge sort. + // Stop when the left-hand covers all of the array. + var buffer = new Array(len); + for (var chk = 1; chk < len; chk *= 2) { + pass(arr, comp, chk, buffer); + + var tmp = arr; + arr = buffer; + buffer = tmp; + } + + return arr + } + + // Run a single pass with the given chunk size. + var pass = function (arr, comp, chk, result) { + var len = arr.length; + var i = 0; + // Step size / double chunk size. + var dbl = chk * 2; + // Bounds of the left and right chunks. + var l, r, e; + // Iterators over the left and right chunk. + var li, ri; + + // Iterate over pairs of chunks. + for (l = 0; l < len; l += dbl) { + r = l + chk; + e = r + chk; + if (r > len) r = len; + if (e > len) e = len; + + // Iterate both chunks in parallel. + li = l; + ri = r; + while (true) { + // Compare the chunks. + if (li < r && ri < e) { + // This works for a regular `sort()` compatible comparator, + // but also for a simple comparator like: `a > b` + if (comp(arr[li], arr[ri]) <= 0) { + result[i++] = arr[li++]; + } + else { + result[i++] = arr[ri++]; + } + } + // Nothing to compare, just flush what's left. + else if (li < r) { + result[i++] = arr[li++]; + } + else if (ri < e) { + result[i++] = arr[ri++]; + } + // Both iterators are at the chunk ends. + else { + break + } + } + } + }; + + return stable; + +}))); + +},{}],1459:[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. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":272,"inherits":317,"readable-stream/duplex.js":1461,"readable-stream/passthrough.js":1470,"readable-stream/readable.js":1471,"readable-stream/transform.js":1472,"readable-stream/writable.js":1473}],1460:[function(require,module,exports){ +arguments[4][291][0].apply(exports,arguments) +},{"dup":291}],1461:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); -},{"./lib/_stream_duplex.js":1558}],1558:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":1462}],1462:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -202403,7 +159327,7 @@ Duplex.prototype._destroy = function (err, cb) { pna.nextTick(cb, err); }; -},{"./_stream_readable":1560,"./_stream_writable":1562,"core-util-is":230,"inherits":453,"process-nextick-args":1437}],1559:[function(require,module,exports){ +},{"./_stream_readable":1464,"./_stream_writable":1466,"core-util-is":191,"inherits":317,"process-nextick-args":1257}],1463:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -202451,7 +159375,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":1561,"core-util-is":230,"inherits":453}],1560:[function(require,module,exports){ +},{"./_stream_transform":1465,"core-util-is":191,"inherits":317}],1464:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -203473,7 +160397,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./_stream_duplex":1558,"./internal/streams/BufferList":1563,"./internal/streams/destroy":1564,"./internal/streams/stream":1565,"_process":1438,"core-util-is":230,"events":370,"inherits":453,"isarray":780,"process-nextick-args":1437,"safe-buffer":1566,"string_decoder/":1567,"util":182}],1561:[function(require,module,exports){ +},{"./_stream_duplex":1462,"./internal/streams/BufferList":1467,"./internal/streams/destroy":1468,"./internal/streams/stream":1469,"_process":1258,"core-util-is":191,"events":272,"inherits":317,"isarray":1460,"process-nextick-args":1257,"safe-buffer":1371,"string_decoder/":1474,"util":146}],1465:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -203688,7 +160612,7 @@ function done(stream, er, data) { return stream.push(null); } -},{"./_stream_duplex":1558,"core-util-is":230,"inherits":453}],1562:[function(require,module,exports){ +},{"./_stream_duplex":1462,"core-util-is":191,"inherits":317}],1466:[function(require,module,exports){ (function (process,global,setImmediate){ // Copyright Joyent, Inc. and other Node contributors. // @@ -204378,7 +161302,7 @@ Writable.prototype._destroy = function (err, cb) { cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"./_stream_duplex":1558,"./internal/streams/destroy":1564,"./internal/streams/stream":1565,"_process":1438,"core-util-is":230,"inherits":453,"process-nextick-args":1437,"safe-buffer":1566,"timers":1749,"util-deprecate":1773}],1563:[function(require,module,exports){ +},{"./_stream_duplex":1462,"./internal/streams/destroy":1468,"./internal/streams/stream":1469,"_process":1258,"core-util-is":191,"inherits":317,"process-nextick-args":1257,"safe-buffer":1371,"timers":1500,"util-deprecate":1510}],1467:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } @@ -204458,7 +161382,7 @@ if (util && util.inspect && util.inspect.custom) { return this.constructor.name + ' ' + obj; }; } -},{"safe-buffer":1566,"util":182}],1564:[function(require,module,exports){ +},{"safe-buffer":1371,"util":146}],1468:[function(require,module,exports){ 'use strict'; /**/ @@ -204533,373 +161457,12 @@ module.exports = { destroy: destroy, undestroy: undestroy }; -},{"process-nextick-args":1437}],1565:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],1566:[function(require,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -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) -} - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -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) - } else { - buf.fill(fill) - } - } 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":217}],1567:[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'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":1566}],1568:[function(require,module,exports){ +},{"process-nextick-args":1257}],1469:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],1470:[function(require,module,exports){ module.exports = require('./readable').PassThrough -},{"./readable":1569}],1569:[function(require,module,exports){ +},{"./readable":1471}],1471:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -204908,20801 +161471,15 @@ exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); -},{"./lib/_stream_duplex.js":1558,"./lib/_stream_passthrough.js":1559,"./lib/_stream_readable.js":1560,"./lib/_stream_transform.js":1561,"./lib/_stream_writable.js":1562}],1570:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":1462,"./lib/_stream_passthrough.js":1463,"./lib/_stream_readable.js":1464,"./lib/_stream_transform.js":1465,"./lib/_stream_writable.js":1466}],1472:[function(require,module,exports){ module.exports = require('./readable').Transform -},{"./readable":1569}],1571:[function(require,module,exports){ +},{"./readable":1471}],1473:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); -},{"./lib/_stream_writable.js":1562}],1572:[function(require,module,exports){ -// Copyright 2010-2012 Mikeal Rogers -// -// 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. - -'use strict' - -var extend = require('extend') -var cookies = require('./lib/cookies') -var helpers = require('./lib/helpers') - -var paramsHaveRequestBody = helpers.paramsHaveRequestBody - -// organize params for patch, post, put, head, del -function initParams (uri, options, callback) { - if (typeof options === 'function') { - callback = options - } - - var params = {} - if (typeof options === 'object') { - extend(params, options, {uri: uri}) - } else if (typeof uri === 'string') { - extend(params, {uri: uri}) - } else { - extend(params, uri) - } - - params.callback = callback || params.callback - return params -} - -function request (uri, options, callback) { - if (typeof uri === 'undefined') { - throw new Error('undefined is not a valid uri or options object.') - } - - var params = initParams(uri, options, callback) - - if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { - throw new Error('HTTP HEAD requests MUST NOT include a request body.') - } - - return new request.Request(params) -} - -function verbFunc (verb) { - var method = verb.toUpperCase() - return function (uri, options, callback) { - var params = initParams(uri, options, callback) - params.method = method - return request(params, params.callback) - } -} - -// define like this to please codeintel/intellisense IDEs -request.get = verbFunc('get') -request.head = verbFunc('head') -request.options = verbFunc('options') -request.post = verbFunc('post') -request.put = verbFunc('put') -request.patch = verbFunc('patch') -request.del = verbFunc('delete') -request['delete'] = verbFunc('delete') - -request.jar = function (store) { - return cookies.jar(store) -} - -request.cookie = function (str) { - return cookies.parse(str) -} - -function wrapRequestMethod (method, options, requester, verb) { - return function (uri, opts, callback) { - var params = initParams(uri, opts, callback) - - var target = {} - extend(true, target, options, params) - - target.pool = params.pool || options.pool - - if (verb) { - target.method = verb.toUpperCase() - } - - if (typeof requester === 'function') { - method = requester - } - - return method(target, target.callback) - } -} - -request.defaults = function (options, requester) { - var self = this - - options = options || {} - - if (typeof options === 'function') { - requester = options - options = {} - } - - var defaults = wrapRequestMethod(self, options, requester) - - var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'] - verbs.forEach(function (verb) { - defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) - }) - - defaults.cookie = wrapRequestMethod(self.cookie, options, requester) - defaults.jar = self.jar - defaults.defaults = self.defaults - return defaults -} - -request.forever = function (agentOptions, optionsArg) { - var options = {} - if (optionsArg) { - extend(options, optionsArg) - } - if (agentOptions) { - options.agentOptions = agentOptions - } - - options.forever = true - return request.defaults(options) -} - -// Exports - -module.exports = request -request.Request = require('./request') -request.initParams = initParams - -// Backwards compatibility for request.debug -Object.defineProperty(request, 'debug', { - enumerable: true, - get: function () { - return request.Request.debug - }, - set: function (debug) { - request.Request.debug = debug - } -}) - -},{"./lib/cookies":1574,"./lib/helpers":1578,"./request":1589,"extend":373}],1573:[function(require,module,exports){ -'use strict' - -var caseless = require('caseless') -var uuid = require('uuid/v4') -var helpers = require('./helpers') - -var md5 = helpers.md5 -var toBase64 = helpers.toBase64 - -function Auth (request) { - // define all public properties here - this.request = request - this.hasAuth = false - this.sentAuth = false - this.bearerToken = null - this.user = null - this.pass = null -} - -Auth.prototype.basic = function (user, pass, sendImmediately) { - var self = this - if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { - self.request.emit('error', new Error('auth() received invalid user or password')) - } - self.user = user - self.pass = pass - self.hasAuth = true - var header = user + ':' + (pass || '') - if (sendImmediately || typeof sendImmediately === 'undefined') { - var authHeader = 'Basic ' + toBase64(header) - self.sentAuth = true - return authHeader - } -} - -Auth.prototype.bearer = function (bearer, sendImmediately) { - var self = this - self.bearerToken = bearer - self.hasAuth = true - if (sendImmediately || typeof sendImmediately === 'undefined') { - if (typeof bearer === 'function') { - bearer = bearer() - } - var authHeader = 'Bearer ' + (bearer || '') - self.sentAuth = true - return authHeader - } -} - -Auth.prototype.digest = function (method, path, authHeader) { - // TODO: More complete implementation of RFC 2617. - // - handle challenge.domain - // - support qop="auth-int" only - // - handle Authentication-Info (not necessarily?) - // - check challenge.stale (not necessarily?) - // - increase nc (not necessarily?) - // For reference: - // http://tools.ietf.org/html/rfc2617#section-3 - // https://github.com/bagder/curl/blob/master/lib/http_digest.c - - var self = this - - var challenge = {} - var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi - for (;;) { - var match = re.exec(authHeader) - if (!match) { - break - } - challenge[match[1]] = match[2] || match[3] - } - - /** - * RFC 2617: handle both MD5 and MD5-sess algorithms. - * - * If the algorithm directive's value is "MD5" or unspecified, then HA1 is - * HA1=MD5(username:realm:password) - * If the algorithm directive's value is "MD5-sess", then HA1 is - * HA1=MD5(MD5(username:realm:password):nonce:cnonce) - */ - var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) { - var ha1 = md5(user + ':' + realm + ':' + pass) - if (algorithm && algorithm.toLowerCase() === 'md5-sess') { - return md5(ha1 + ':' + nonce + ':' + cnonce) - } else { - return ha1 - } - } - - var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' - var nc = qop && '00000001' - var cnonce = qop && uuid().replace(/-/g, '') - var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce) - var ha2 = md5(method + ':' + path) - var digestResponse = qop - ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) - : md5(ha1 + ':' + challenge.nonce + ':' + ha2) - var authValues = { - username: self.user, - realm: challenge.realm, - nonce: challenge.nonce, - uri: path, - qop: qop, - response: digestResponse, - nc: nc, - cnonce: cnonce, - algorithm: challenge.algorithm, - opaque: challenge.opaque - } - - authHeader = [] - for (var k in authValues) { - if (authValues[k]) { - if (k === 'qop' || k === 'nc' || k === 'algorithm') { - authHeader.push(k + '=' + authValues[k]) - } else { - authHeader.push(k + '="' + authValues[k] + '"') - } - } - } - authHeader = 'Digest ' + authHeader.join(', ') - self.sentAuth = true - return authHeader -} - -Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { - var self = this - var request = self.request - - var authHeader - if (bearer === undefined && user === undefined) { - self.request.emit('error', new Error('no auth mechanism defined')) - } else if (bearer !== undefined) { - authHeader = self.bearer(bearer, sendImmediately) - } else { - authHeader = self.basic(user, pass, sendImmediately) - } - if (authHeader) { - request.setHeader('authorization', authHeader) - } -} - -Auth.prototype.onResponse = function (response) { - var self = this - var request = self.request - - if (!self.hasAuth || self.sentAuth) { return null } - - var c = caseless(response.headers) - - var authHeader = c.get('www-authenticate') - var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() - request.debug('reauth', authVerb) - - switch (authVerb) { - case 'basic': - return self.basic(self.user, self.pass, true) - - case 'bearer': - return self.bearer(self.bearerToken, true) - - case 'digest': - return self.digest(request.method, request.path, authHeader) - } -} - -exports.Auth = Auth - -},{"./helpers":1578,"caseless":220,"uuid/v4":1781}],1574:[function(require,module,exports){ -'use strict' - -var tough = require('tough-cookie') - -var Cookie = tough.Cookie -var CookieJar = tough.CookieJar - -exports.parse = function (str) { - if (str && str.uri) { - str = str.uri - } - if (typeof str !== 'string') { - throw new Error('The cookie function only accepts STRING as param') - } - return Cookie.parse(str, {loose: true}) -} - -// Adapt the sometimes-Async api of tough.CookieJar to our requirements -function RequestJar (store) { - var self = this - self._jar = new CookieJar(store, {looseMode: true}) -} -RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) { - var self = this - return self._jar.setCookieSync(cookieOrStr, uri, options || {}) -} -RequestJar.prototype.getCookieString = function (uri) { - var self = this - return self._jar.getCookieStringSync(uri) -} -RequestJar.prototype.getCookies = function (uri) { - var self = this - return self._jar.getCookiesSync(uri) -} - -exports.jar = function (store) { - return new RequestJar(store) -} - -},{"tough-cookie":1752}],1575:[function(require,module,exports){ -(function (process){ -'use strict' - -function formatHostname (hostname) { - // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' - return hostname.replace(/^\.*/, '.').toLowerCase() -} - -function parseNoProxyZone (zone) { - zone = zone.trim().toLowerCase() - - var zoneParts = zone.split(':', 2) - var zoneHost = formatHostname(zoneParts[0]) - var zonePort = zoneParts[1] - var hasPort = zone.indexOf(':') > -1 - - return {hostname: zoneHost, port: zonePort, hasPort: hasPort} -} - -function uriInNoProxy (uri, noProxy) { - var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') - var hostname = formatHostname(uri.hostname) - var noProxyList = noProxy.split(',') - - // iterate through the noProxyList until it finds a match. - return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) { - var isMatchedAt = hostname.indexOf(noProxyZone.hostname) - var hostnameMatched = ( - isMatchedAt > -1 && - (isMatchedAt === hostname.length - noProxyZone.hostname.length) - ) - - if (noProxyZone.hasPort) { - return (port === noProxyZone.port) && hostnameMatched - } - - return hostnameMatched - }) -} - -function getProxyFromURI (uri) { - // Decide the proper request proxy to use based on the request URI object and the - // environmental variables (NO_PROXY, HTTP_PROXY, etc.) - // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html) - - var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' - - // if the noProxy is a wildcard then return null - - if (noProxy === '*') { - return null - } - - // if the noProxy is not empty and the uri is found return null - - if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { - return null - } - - // Check for HTTP or HTTPS Proxy in environment Else default to null - - if (uri.protocol === 'http:') { - return process.env.HTTP_PROXY || - process.env.http_proxy || null - } - - if (uri.protocol === 'https:') { - return process.env.HTTPS_PROXY || - process.env.https_proxy || - process.env.HTTP_PROXY || - process.env.http_proxy || null - } - - // if none of that works, return null - // (What uri protocol are you using then?) - - return null -} - -module.exports = getProxyFromURI - -}).call(this,require('_process')) -},{"_process":1438}],1576:[function(require,module,exports){ -'use strict' - -var fs = require('fs') -var qs = require('querystring') -var validate = require('har-validator') -var extend = require('extend') - -function Har (request) { - this.request = request -} - -Har.prototype.reducer = function (obj, pair) { - // new property ? - if (obj[pair.name] === undefined) { - obj[pair.name] = pair.value - return obj - } - - // existing? convert to array - var arr = [ - obj[pair.name], - pair.value - ] - - obj[pair.name] = arr - - return obj -} - -Har.prototype.prep = function (data) { - // construct utility properties - data.queryObj = {} - data.headersObj = {} - data.postData.jsonObj = false - data.postData.paramsObj = false - - // construct query objects - if (data.queryString && data.queryString.length) { - data.queryObj = data.queryString.reduce(this.reducer, {}) - } - - // construct headers objects - if (data.headers && data.headers.length) { - // loweCase header keys - data.headersObj = data.headers.reduceRight(function (headers, header) { - headers[header.name] = header.value - return headers - }, {}) - } - - // construct Cookie header - if (data.cookies && data.cookies.length) { - var cookies = data.cookies.map(function (cookie) { - return cookie.name + '=' + cookie.value - }) - - if (cookies.length) { - data.headersObj.cookie = cookies.join('; ') - } - } - - // prep body - function some (arr) { - return arr.some(function (type) { - return data.postData.mimeType.indexOf(type) === 0 - }) - } - - if (some([ - 'multipart/mixed', - 'multipart/related', - 'multipart/form-data', - 'multipart/alternative'])) { - // reset values - data.postData.mimeType = 'multipart/form-data' - } else if (some([ - 'application/x-www-form-urlencoded'])) { - if (!data.postData.params) { - data.postData.text = '' - } else { - data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) - - // always overwrite - data.postData.text = qs.stringify(data.postData.paramsObj) - } - } else if (some([ - 'text/json', - 'text/x-json', - 'application/json', - 'application/x-json'])) { - data.postData.mimeType = 'application/json' - - if (data.postData.text) { - try { - data.postData.jsonObj = JSON.parse(data.postData.text) - } catch (e) { - this.request.debug(e) - - // force back to text/plain - data.postData.mimeType = 'text/plain' - } - } - } - - return data -} - -Har.prototype.options = function (options) { - // skip if no har property defined - if (!options.har) { - return options - } - - var har = {} - extend(har, options.har) - - // only process the first entry - if (har.log && har.log.entries) { - har = har.log.entries[0] - } - - // add optional properties to make validation successful - har.url = har.url || options.url || options.uri || options.baseUrl || '/' - har.httpVersion = har.httpVersion || 'HTTP/1.1' - har.queryString = har.queryString || [] - har.headers = har.headers || [] - har.cookies = har.cookies || [] - har.postData = har.postData || {} - har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' - - har.bodySize = 0 - har.headersSize = 0 - har.postData.size = 0 - - if (!validate.request(har)) { - return options - } - - // clean up and get some utility properties - var req = this.prep(har) - - // construct new options - if (req.url) { - options.url = req.url - } - - if (req.method) { - options.method = req.method - } - - if (Object.keys(req.queryObj).length) { - options.qs = req.queryObj - } - - if (Object.keys(req.headersObj).length) { - options.headers = req.headersObj - } - - function test (type) { - return req.postData.mimeType.indexOf(type) === 0 - } - if (test('application/x-www-form-urlencoded')) { - options.form = req.postData.paramsObj - } else if (test('application/json')) { - if (req.postData.jsonObj) { - options.body = req.postData.jsonObj - options.json = true - } - } else if (test('multipart/form-data')) { - options.formData = {} - - req.postData.params.forEach(function (param) { - var attachment = {} - - if (!param.fileName && !param.fileName && !param.contentType) { - options.formData[param.name] = param.value - return - } - - // attempt to read from disk! - if (param.fileName && !param.value) { - attachment.value = fs.createReadStream(param.fileName) - } else if (param.value) { - attachment.value = param.value - } - - if (param.fileName) { - attachment.options = { - filename: param.fileName, - contentType: param.contentType ? param.contentType : null - } - } - - options.formData[param.name] = attachment - }) - } else { - if (req.postData.text) { - options.body = req.postData.text - } - } - - return options -} - -exports.Har = Har - -},{"extend":373,"fs":212,"har-validator":418,"querystring":1547}],1577:[function(require,module,exports){ -'use strict' - -var crypto = require('crypto') - -function randomString (size) { - var bits = (size + 1) * 6 - var buffer = crypto.randomBytes(Math.ceil(bits / 8)) - var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') - return string.slice(0, size) -} - -function calculatePayloadHash (payload, algorithm, contentType) { - var hash = crypto.createHash(algorithm) - hash.update('hawk.1.payload\n') - hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n') - hash.update(payload || '') - hash.update('\n') - return hash.digest('base64') -} - -exports.calculateMac = function (credentials, opts) { - var normalized = 'hawk.1.header\n' + - opts.ts + '\n' + - opts.nonce + '\n' + - (opts.method || '').toUpperCase() + '\n' + - opts.resource + '\n' + - opts.host.toLowerCase() + '\n' + - opts.port + '\n' + - (opts.hash || '') + '\n' - - if (opts.ext) { - normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n') - } - - normalized = normalized + '\n' - - if (opts.app) { - normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n' - } - - var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized) - var digest = hmac.digest('base64') - return digest -} - -exports.header = function (uri, method, opts) { - var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000) - var credentials = opts.credentials - if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) { - return '' - } - - if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) { - return '' - } - - var artifacts = { - ts: timestamp, - nonce: opts.nonce || randomString(6), - method: method, - resource: uri.pathname + (uri.search || ''), - host: uri.hostname, - port: uri.port || (uri.protocol === 'http:' ? 80 : 443), - hash: opts.hash, - ext: opts.ext, - app: opts.app, - dlg: opts.dlg - } - - if (!artifacts.hash && (opts.payload || opts.payload === '')) { - artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType) - } - - var mac = exports.calculateMac(credentials, artifacts) - - var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '' - var header = 'Hawk id="' + credentials.id + - '", ts="' + artifacts.ts + - '", nonce="' + artifacts.nonce + - (artifacts.hash ? '", hash="' + artifacts.hash : '') + - (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') + - '", mac="' + mac + '"' - - if (artifacts.app) { - header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"' - } - - return header -} - -},{"crypto":236}],1578:[function(require,module,exports){ -(function (process,setImmediate){ -'use strict' - -var jsonSafeStringify = require('json-stringify-safe') -var crypto = require('crypto') -var Buffer = require('safe-buffer').Buffer - -var defer = typeof setImmediate === 'undefined' - ? process.nextTick - : setImmediate - -function paramsHaveRequestBody (params) { - return ( - params.body || - params.requestBodyStream || - (params.json && typeof params.json !== 'boolean') || - params.multipart - ) -} - -function safeStringify (obj, replacer) { - var ret - try { - ret = JSON.stringify(obj, replacer) - } catch (e) { - ret = jsonSafeStringify(obj, replacer) - } - return ret -} - -function md5 (str) { - return crypto.createHash('md5').update(str).digest('hex') -} - -function isReadStream (rs) { - return rs.readable && rs.path && rs.mode -} - -function toBase64 (str) { - return Buffer.from(str || '', 'utf8').toString('base64') -} - -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] - }) - return o -} - -function version () { - var numbers = process.version.replace('v', '').split('.') - return { - major: parseInt(numbers[0], 10), - minor: parseInt(numbers[1], 10), - patch: parseInt(numbers[2], 10) - } -} - -exports.paramsHaveRequestBody = paramsHaveRequestBody -exports.safeStringify = safeStringify -exports.md5 = md5 -exports.isReadStream = isReadStream -exports.toBase64 = toBase64 -exports.copy = copy -exports.version = version -exports.defer = defer - -}).call(this,require('_process'),require("timers").setImmediate) -},{"_process":1438,"crypto":236,"json-stringify-safe":828,"safe-buffer":1593,"timers":1749}],1579:[function(require,module,exports){ -'use strict' - -var uuid = require('uuid/v4') -var CombinedStream = require('combined-stream') -var isstream = require('isstream') -var Buffer = require('safe-buffer').Buffer - -function Multipart (request) { - this.request = request - this.boundary = uuid() - this.chunked = false - this.body = null -} - -Multipart.prototype.isChunked = function (options) { - var self = this - var chunked = false - var parts = options.data || options - - if (!parts.forEach) { - self.request.emit('error', new Error('Argument error, options.multipart.')) - } - - if (options.chunked !== undefined) { - chunked = options.chunked - } - - if (self.request.getHeader('transfer-encoding') === 'chunked') { - chunked = true - } - - if (!chunked) { - parts.forEach(function (part) { - if (typeof part.body === 'undefined') { - self.request.emit('error', new Error('Body attribute missing in multipart.')) - } - if (isstream(part.body)) { - chunked = true - } - }) - } - - return chunked -} - -Multipart.prototype.setHeaders = function (chunked) { - var self = this - - if (chunked && !self.request.hasHeader('transfer-encoding')) { - self.request.setHeader('transfer-encoding', 'chunked') - } - - var header = self.request.getHeader('content-type') - - if (!header || header.indexOf('multipart') === -1) { - self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) - } else { - if (header.indexOf('boundary') !== -1) { - self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') - } else { - self.request.setHeader('content-type', header + '; boundary=' + self.boundary) - } - } -} - -Multipart.prototype.build = function (parts, chunked) { - var self = this - var body = chunked ? new CombinedStream() : [] - - function add (part) { - if (typeof part === 'number') { - part = part.toString() - } - return chunked ? body.append(part) : body.push(Buffer.from(part)) - } - - if (self.request.preambleCRLF) { - add('\r\n') - } - - parts.forEach(function (part) { - var preamble = '--' + self.boundary + '\r\n' - Object.keys(part).forEach(function (key) { - if (key === 'body') { return } - preamble += key + ': ' + part[key] + '\r\n' - }) - preamble += '\r\n' - add(preamble) - add(part.body) - add('\r\n') - }) - add('--' + self.boundary + '--') - - if (self.request.postambleCRLF) { - add('\r\n') - } - - return body -} - -Multipart.prototype.onRequest = function (options) { - var self = this - - var chunked = self.isChunked(options) - var parts = options.data || options - - self.setHeaders(chunked) - self.chunked = chunked - self.body = self.build(parts, chunked) -} - -exports.Multipart = Multipart - -},{"combined-stream":225,"isstream":805,"safe-buffer":1593,"uuid/v4":1781}],1580:[function(require,module,exports){ -'use strict' - -var url = require('url') -var qs = require('qs') -var caseless = require('caseless') -var uuid = require('uuid/v4') -var oauth = require('oauth-sign') -var crypto = require('crypto') -var Buffer = require('safe-buffer').Buffer - -function OAuth (request) { - this.request = request - this.params = null -} - -OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { - var oa = {} - for (var i in _oauth) { - oa['oauth_' + i] = _oauth[i] - } - if (!oa.oauth_version) { - oa.oauth_version = '1.0' - } - if (!oa.oauth_timestamp) { - oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString() - } - if (!oa.oauth_nonce) { - oa.oauth_nonce = uuid().replace(/-/g, '') - } - if (!oa.oauth_signature_method) { - oa.oauth_signature_method = 'HMAC-SHA1' - } - - var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase - delete oa.oauth_consumer_secret - delete oa.oauth_private_key - - var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase - delete oa.oauth_token_secret - - var realm = oa.oauth_realm - delete oa.oauth_realm - delete oa.oauth_transport_method - - var baseurl = uri.protocol + '//' + uri.host + uri.pathname - var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) - - oa.oauth_signature = oauth.sign( - oa.oauth_signature_method, - method, - baseurl, - params, - consumer_secret_or_private_key, // eslint-disable-line camelcase - token_secret // eslint-disable-line camelcase - ) - - if (realm) { - oa.realm = realm - } - - return oa -} - -OAuth.prototype.buildBodyHash = function (_oauth, body) { - if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { - this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + - ' signature_method not supported with body_hash signing.')) - } - - var shasum = crypto.createHash('sha1') - shasum.update(body || '') - var sha1 = shasum.digest('hex') - - return Buffer.from(sha1, 'hex').toString('base64') -} - -OAuth.prototype.concatParams = function (oa, sep, wrap) { - wrap = wrap || '' - - var params = Object.keys(oa).filter(function (i) { - return i !== 'realm' && i !== 'oauth_signature' - }).sort() - - if (oa.realm) { - params.splice(0, 0, 'realm') - } - params.push('oauth_signature') - - return params.map(function (i) { - return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap - }).join(sep) -} - -OAuth.prototype.onRequest = function (_oauth) { - var self = this - self.params = _oauth - - var uri = self.request.uri || {} - var method = self.request.method || '' - var headers = caseless(self.request.headers) - var body = self.request.body || '' - var qsLib = self.request.qsLib || qs - - var form - var query - var contentType = headers.get('content-type') || '' - var formContentType = 'application/x-www-form-urlencoded' - var transport = _oauth.transport_method || 'header' - - if (contentType.slice(0, formContentType.length) === formContentType) { - contentType = formContentType - form = body - } - if (uri.query) { - query = uri.query - } - if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { - self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + - 'and content-type ' + formContentType)) - } - - if (!form && typeof _oauth.body_hash === 'boolean') { - _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) - } - - var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) - - switch (transport) { - case 'header': - self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) - break - - case 'query': - var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&') - self.request.uri = url.parse(href) - self.request.path = self.request.uri.path - break - - case 'body': - self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') - break - - default: - self.request.emit('error', new Error('oauth: transport_method invalid')) - } -} - -exports.OAuth = OAuth - -},{"caseless":220,"crypto":236,"oauth-sign":1387,"qs":1585,"safe-buffer":1593,"url":1769,"uuid/v4":1781}],1581:[function(require,module,exports){ -'use strict' - -var qs = require('qs') -var querystring = require('querystring') - -function Querystring (request) { - this.request = request - this.lib = null - this.useQuerystring = null - this.parseOptions = null - this.stringifyOptions = null -} - -Querystring.prototype.init = function (options) { - if (this.lib) { return } - - this.useQuerystring = options.useQuerystring - this.lib = (this.useQuerystring ? querystring : qs) - - this.parseOptions = options.qsParseOptions || {} - this.stringifyOptions = options.qsStringifyOptions || {} -} - -Querystring.prototype.stringify = function (obj) { - return (this.useQuerystring) - ? this.rfc3986(this.lib.stringify(obj, - this.stringifyOptions.sep || null, - this.stringifyOptions.eq || null, - this.stringifyOptions)) - : this.lib.stringify(obj, this.stringifyOptions) -} - -Querystring.prototype.parse = function (str) { - return (this.useQuerystring) - ? this.lib.parse(str, - this.parseOptions.sep || null, - this.parseOptions.eq || null, - this.parseOptions) - : this.lib.parse(str, this.parseOptions) -} - -Querystring.prototype.rfc3986 = function (str) { - return str.replace(/[!'()*]/g, function (c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase() - }) -} - -Querystring.prototype.unescape = querystring.unescape - -exports.Querystring = Querystring - -},{"qs":1585,"querystring":1547}],1582:[function(require,module,exports){ -'use strict' - -var url = require('url') -var isUrl = /^https?:/ - -function Redirect (request) { - this.request = request - this.followRedirect = true - this.followRedirects = true - this.followAllRedirects = false - this.followOriginalHttpMethod = false - this.allowRedirect = function () { return true } - this.maxRedirects = 10 - this.redirects = [] - this.redirectsFollowed = 0 - this.removeRefererHeader = false -} - -Redirect.prototype.onRequest = function (options) { - var self = this - - if (options.maxRedirects !== undefined) { - self.maxRedirects = options.maxRedirects - } - if (typeof options.followRedirect === 'function') { - self.allowRedirect = options.followRedirect - } - if (options.followRedirect !== undefined) { - self.followRedirects = !!options.followRedirect - } - if (options.followAllRedirects !== undefined) { - self.followAllRedirects = options.followAllRedirects - } - if (self.followRedirects || self.followAllRedirects) { - self.redirects = self.redirects || [] - } - if (options.removeRefererHeader !== undefined) { - self.removeRefererHeader = options.removeRefererHeader - } - if (options.followOriginalHttpMethod !== undefined) { - self.followOriginalHttpMethod = options.followOriginalHttpMethod - } -} - -Redirect.prototype.redirectTo = function (response) { - var self = this - var request = self.request - - var redirectTo = null - if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { - var location = response.caseless.get('location') - request.debug('redirect', location) - - if (self.followAllRedirects) { - redirectTo = location - } else if (self.followRedirects) { - switch (request.method) { - case 'PATCH': - case 'PUT': - case 'POST': - case 'DELETE': - // Do not follow redirects - break - default: - redirectTo = location - break - } - } - } else if (response.statusCode === 401) { - var authHeader = request._auth.onResponse(response) - if (authHeader) { - request.setHeader('authorization', authHeader) - redirectTo = request.uri - } - } - return redirectTo -} - -Redirect.prototype.onResponse = function (response) { - var self = this - var request = self.request - - var redirectTo = self.redirectTo(response) - if (!redirectTo || !self.allowRedirect.call(request, response)) { - return false - } - - request.debug('redirect to', redirectTo) - - // ignore any potential response body. it cannot possibly be useful - // to us at this point. - // response.resume should be defined, but check anyway before calling. Workaround for browserify. - if (response.resume) { - response.resume() - } - - if (self.redirectsFollowed >= self.maxRedirects) { - request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) - return false - } - self.redirectsFollowed += 1 - - if (!isUrl.test(redirectTo)) { - redirectTo = url.resolve(request.uri.href, redirectTo) - } - - var uriPrev = request.uri - request.uri = url.parse(redirectTo) - - // handle the case where we change protocol from https to http or vice versa - if (request.uri.protocol !== uriPrev.protocol) { - delete request.agent - } - - self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo }) - - if (self.followAllRedirects && request.method !== 'HEAD' && - response.statusCode !== 401 && response.statusCode !== 307) { - request.method = self.followOriginalHttpMethod ? request.method : 'GET' - } - // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 - delete request.src - delete request.req - delete request._started - if (response.statusCode !== 401 && response.statusCode !== 307) { - // Remove parameters from the previous response, unless this is the second request - // for a server that requires digest authentication. - delete request.body - delete request._form - if (request.headers) { - request.removeHeader('host') - request.removeHeader('content-type') - request.removeHeader('content-length') - if (request.uri.hostname !== request.originalHost.split(':')[0]) { - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of curl: - // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 - request.removeHeader('authorization') - } - } - } - - if (!self.removeRefererHeader) { - request.setHeader('referer', uriPrev.href) - } - - request.emit('redirect') - - request.init() - - return true -} - -exports.Redirect = Redirect - -},{"url":1769}],1583:[function(require,module,exports){ -'use strict' - -var url = require('url') -var tunnel = require('tunnel-agent') - -var defaultProxyHeaderWhiteList = [ - 'accept', - 'accept-charset', - 'accept-encoding', - 'accept-language', - 'accept-ranges', - 'cache-control', - 'content-encoding', - 'content-language', - 'content-location', - 'content-md5', - 'content-range', - 'content-type', - 'connection', - 'date', - 'expect', - 'max-forwards', - 'pragma', - 'referer', - 'te', - 'user-agent', - 'via' -] - -var defaultProxyHeaderExclusiveList = [ - 'proxy-authorization' -] - -function constructProxyHost (uriObject) { - var port = uriObject.port - var protocol = uriObject.protocol - var proxyHost = uriObject.hostname + ':' - - if (port) { - proxyHost += port - } else if (protocol === 'https:') { - proxyHost += '443' - } else { - proxyHost += '80' - } - - return proxyHost -} - -function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) { - var whiteList = proxyHeaderWhiteList - .reduce(function (set, header) { - set[header.toLowerCase()] = true - return set - }, {}) - - return Object.keys(headers) - .filter(function (header) { - return whiteList[header.toLowerCase()] - }) - .reduce(function (set, header) { - set[header] = headers[header] - return set - }, {}) -} - -function constructTunnelOptions (request, proxyHeaders) { - var proxy = request.proxy - - var tunnelOptions = { - proxy: { - host: proxy.hostname, - port: +proxy.port, - proxyAuth: proxy.auth, - headers: proxyHeaders - }, - headers: request.headers, - ca: request.ca, - cert: request.cert, - key: request.key, - passphrase: request.passphrase, - pfx: request.pfx, - ciphers: request.ciphers, - rejectUnauthorized: request.rejectUnauthorized, - secureOptions: request.secureOptions, - secureProtocol: request.secureProtocol - } - - return tunnelOptions -} - -function constructTunnelFnName (uri, proxy) { - var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') - var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') - return [uriProtocol, proxyProtocol].join('Over') -} - -function getTunnelFn (request) { - var uri = request.uri - var proxy = request.proxy - var tunnelFnName = constructTunnelFnName(uri, proxy) - return tunnel[tunnelFnName] -} - -function Tunnel (request) { - this.request = request - this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList - this.proxyHeaderExclusiveList = [] - if (typeof request.tunnel !== 'undefined') { - this.tunnelOverride = request.tunnel - } -} - -Tunnel.prototype.isEnabled = function () { - var self = this - var request = self.request - // Tunnel HTTPS by default. Allow the user to override this setting. - - // If self.tunnelOverride is set (the user specified a value), use it. - if (typeof self.tunnelOverride !== 'undefined') { - return self.tunnelOverride - } - - // If the destination is HTTPS, tunnel. - if (request.uri.protocol === 'https:') { - return true - } - - // Otherwise, do not use tunnel. - return false -} - -Tunnel.prototype.setup = function (options) { - var self = this - var request = self.request - - options = options || {} - - if (typeof request.proxy === 'string') { - request.proxy = url.parse(request.proxy) - } - - if (!request.proxy || !request.tunnel) { - return false - } - - // Setup Proxy Header Exclusive List and White List - if (options.proxyHeaderWhiteList) { - self.proxyHeaderWhiteList = options.proxyHeaderWhiteList - } - if (options.proxyHeaderExclusiveList) { - self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList - } - - var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) - var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) - - // Setup Proxy Headers and Proxy Headers Host - // Only send the Proxy White Listed Header names - var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList) - proxyHeaders.host = constructProxyHost(request.uri) - - proxyHeaderExclusiveList.forEach(request.removeHeader, request) - - // Set Agent from Tunnel Data - var tunnelFn = getTunnelFn(request) - var tunnelOptions = constructTunnelOptions(request, proxyHeaders) - request.agent = tunnelFn(tunnelOptions) - - return true -} - -Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList -Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList -exports.Tunnel = Tunnel - -},{"tunnel-agent":1761,"url":1769}],1584:[function(require,module,exports){ -arguments[4][1539][0].apply(exports,arguments) -},{"dup":1539}],1585:[function(require,module,exports){ -arguments[4][1540][0].apply(exports,arguments) -},{"./formats":1584,"./parse":1586,"./stringify":1587,"dup":1540}],1586:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); - -var has = Object.prototype.hasOwnProperty; - -var defaults = { - allowDots: false, - allowPrototypes: false, - arrayLimit: 20, - decoder: utils.decode, - delimiter: '&', - depth: 5, - parameterLimit: 1000, - plainObjects: false, - strictNullHandling: false -}; - -var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; - var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; - var parts = cleanStr.split(options.delimiter, limit); - - for (var i = 0; i < parts.length; ++i) { - var part = parts[i]; - - var bracketEqualsPos = part.indexOf(']='); - var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; - - var key, val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder); - val = options.strictNullHandling ? null : ''; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder); - val = options.decoder(part.slice(pos + 1), defaults.decoder); - } - if (has.call(obj, key)) { - obj[key] = [].concat(obj[key]).concat(val); - } else { - obj[key] = val; - } - } - - return obj; -}; - -var parseObject = function (chain, val, options) { - var leaf = val; - - for (var i = chain.length - 1; i >= 0; --i) { - var obj; - var root = chain[i]; - - if (root === '[]') { - obj = []; - obj = obj.concat(leaf); - } else { - obj = options.plainObjects ? Object.create(null) : {}; - var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; - var index = parseInt(cleanRoot, 10); - if ( - !isNaN(index) - && root !== cleanRoot - && String(index) === cleanRoot - && index >= 0 - && (options.parseArrays && index <= options.arrayLimit) - ) { - obj = []; - obj[index] = leaf; - } else { - obj[cleanRoot] = leaf; - } - } - - leaf = obj; - } - - return leaf; -}; - -var parseKeys = function parseQueryStringKeys(givenKey, val, options) { - if (!givenKey) { - return; - } - - // Transform dot notation to bracket notation - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; - - // The regex chunks - - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - - // Get the parent - - var segment = brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - - // Stash the parent if it exists - - var keys = []; - if (parent) { - // If we aren't using plain objects, optionally prefix keys - // that would overwrite object prototype properties - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; - } - } - - keys.push(parent); - } - - // Loop through children appending to the array until we hit depth - - var i = 0; - while ((segment = child.exec(key)) !== null && i < options.depth) { - i += 1; - if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { - if (!options.allowPrototypes) { - return; - } - } - keys.push(segment[1]); - } - - // If there's a remainder, just add whatever is left - - if (segment) { - keys.push('[' + key.slice(segment.index) + ']'); - } - - return parseObject(keys, val, options); -}; - -module.exports = function (str, opts) { - var options = opts ? utils.assign({}, opts) : {}; - - if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { - throw new TypeError('Decoder has to be a function.'); - } - - options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; - options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; - options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; - options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; - options.parseArrays = options.parseArrays !== false; - options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; - options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; - options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; - options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; - options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; - options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - - if (str === '' || str === null || typeof str === 'undefined') { - return options.plainObjects ? Object.create(null) : {}; - } - - var tempObj = typeof str === 'string' ? parseValues(str, options) : str; - var obj = options.plainObjects ? Object.create(null) : {}; - - // Iterate over the keys and setup the new object - - var keys = Object.keys(tempObj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newObj = parseKeys(key, tempObj[key], options); - obj = utils.merge(obj, newObj, options); - } - - return utils.compact(obj); -}; - -},{"./utils":1588}],1587:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var formats = require('./formats'); - -var arrayPrefixGenerators = { - brackets: function brackets(prefix) { // eslint-disable-line func-name-matching - return prefix + '[]'; - }, - indices: function indices(prefix, key) { // eslint-disable-line func-name-matching - return prefix + '[' + key + ']'; - }, - repeat: function repeat(prefix) { // eslint-disable-line func-name-matching - return prefix; - } -}; - -var toISO = Date.prototype.toISOString; - -var defaults = { - delimiter: '&', - encode: true, - encoder: utils.encode, - encodeValuesOnly: false, - serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching - return toISO.call(date); - }, - skipNulls: false, - strictNullHandling: false -}; - -var stringify = function stringify( // eslint-disable-line func-name-matching - object, - prefix, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly -) { - var obj = object; - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); - } else if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; - } - - obj = ''; - } - - if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { - if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); - return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; - } - return [formatter(prefix) + '=' + formatter(String(obj))]; - } - - var values = []; - - if (typeof obj === 'undefined') { - return values; - } - - var objKeys; - if (Array.isArray(filter)) { - objKeys = filter; - } else { - var keys = Object.keys(obj); - objKeys = sort ? keys.sort(sort) : keys; - } - - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; - } - - if (Array.isArray(obj)) { - values = values.concat(stringify( - obj[key], - generateArrayPrefix(prefix, key), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } else { - values = values.concat(stringify( - obj[key], - prefix + (allowDots ? '.' + key : '[' + key + ']'), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } - } - - return values; -}; - -module.exports = function (object, opts) { - var obj = object; - var options = opts ? utils.assign({}, opts) : {}; - - if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - - var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; - var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; - var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; - var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; - var sort = typeof options.sort === 'function' ? options.sort : null; - var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; - var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; - var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; - if (typeof options.format === 'undefined') { - options.format = formats['default']; - } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { - throw new TypeError('Unknown format option provided.'); - } - var formatter = formats.formatters[options.format]; - var objKeys; - var filter; - - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } else if (Array.isArray(options.filter)) { - filter = options.filter; - objKeys = filter; - } - - var keys = []; - - if (typeof obj !== 'object' || obj === null) { - return ''; - } - - var arrayFormat; - if (options.arrayFormat in arrayPrefixGenerators) { - arrayFormat = options.arrayFormat; - } else if ('indices' in options) { - arrayFormat = options.indices ? 'indices' : 'repeat'; - } else { - arrayFormat = 'indices'; - } - - var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; - - if (!objKeys) { - objKeys = Object.keys(obj); - } - - if (sort) { - objKeys.sort(sort); - } - - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; - } - - keys = keys.concat(stringify( - obj[key], - key, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encode ? encoder : null, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } - - var joined = keys.join(delimiter); - var prefix = options.addQueryPrefix === true ? '?' : ''; - - return joined.length > 0 ? prefix + joined : ''; -}; - -},{"./formats":1584,"./utils":1588}],1588:[function(require,module,exports){ -'use strict'; - -var has = Object.prototype.hasOwnProperty; - -var hexTable = (function () { - var array = []; - for (var i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } - - return array; -}()); - -var compactQueue = function compactQueue(queue) { - var obj; - - while (queue.length) { - var item = queue.pop(); - obj = item.obj[item.prop]; - - if (Array.isArray(obj)) { - var compacted = []; - - for (var j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } - - item.obj[item.prop] = compacted; - } - } - - return obj; -}; - -var arrayToObject = function arrayToObject(source, options) { - var obj = options && options.plainObjects ? Object.create(null) : {}; - for (var i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } - - return obj; -}; - -var merge = function merge(target, source, options) { - if (!source) { - return target; - } - - if (typeof source !== 'object') { - if (Array.isArray(target)) { - target.push(source); - } else if (typeof target === 'object') { - if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } - - return target; - } - - if (typeof target !== 'object') { - return [target].concat(source); - } - - var mergeTarget = target; - if (Array.isArray(target) && !Array.isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - - if (Array.isArray(target) && Array.isArray(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - if (target[i] && typeof target[i] === 'object') { - target[i] = merge(target[i], item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; - } - - return Object.keys(source).reduce(function (acc, key) { - var value = source[key]; - - if (has.call(acc, key)) { - acc[key] = merge(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); -}; - -var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -}; - -var decode = function (str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (e) { - return str; - } -}; - -var encode = function encode(str) { - // This code was originally written by Brian White (mscdex) for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } - - var string = typeof str === 'string' ? str : String(str); - - var out = ''; - for (var i = 0; i < string.length; ++i) { - var c = string.charCodeAt(i); - - if ( - c === 0x2D // - - || c === 0x2E // . - || c === 0x5F // _ - || c === 0x7E // ~ - || (c >= 0x30 && c <= 0x39) // 0-9 - || (c >= 0x41 && c <= 0x5A) // a-z - || (c >= 0x61 && c <= 0x7A) // A-Z - ) { - out += string.charAt(i); - continue; - } - - if (c < 0x80) { - out = out + hexTable[c]; - continue; - } - - if (c < 0x800) { - out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } - - if (c < 0xD800 || c >= 0xE000) { - out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } - - i += 1; - c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); - out += hexTable[0xF0 | (c >> 18)] - + hexTable[0x80 | ((c >> 12) & 0x3F)] - + hexTable[0x80 | ((c >> 6) & 0x3F)] - + hexTable[0x80 | (c & 0x3F)]; - } - - return out; -}; - -var compact = function compact(value) { - var queue = [{ obj: { o: value }, prop: 'o' }]; - var refs = []; - - for (var i = 0; i < queue.length; ++i) { - var item = queue[i]; - var obj = item.obj[item.prop]; - - var keys = Object.keys(obj); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - var val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } - } - - return compactQueue(queue); -}; - -var isRegExp = function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -}; - -var isBuffer = function isBuffer(obj) { - if (obj === null || typeof obj === 'undefined') { - return false; - } - - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -}; - -module.exports = { - arrayToObject: arrayToObject, - assign: assign, - compact: compact, - decode: decode, - encode: encode, - isBuffer: isBuffer, - isRegExp: isRegExp, - merge: merge -}; - -},{}],1589:[function(require,module,exports){ -(function (process){ -'use strict' - -var http = require('http') -var https = require('https') -var url = require('url') -var util = require('util') -var stream = require('stream') -var zlib = require('zlib') -var aws2 = require('aws-sign2') -var aws4 = require('aws4') -var httpSignature = require('http-signature') -var mime = require('mime-types') -var caseless = require('caseless') -var ForeverAgent = require('forever-agent') -var FormData = require('form-data') -var extend = require('extend') -var isstream = require('isstream') -var isTypedArray = require('is-typedarray').strict -var helpers = require('./lib/helpers') -var cookies = require('./lib/cookies') -var getProxyFromURI = require('./lib/getProxyFromURI') -var Querystring = require('./lib/querystring').Querystring -var Har = require('./lib/har').Har -var Auth = require('./lib/auth').Auth -var OAuth = require('./lib/oauth').OAuth -var hawk = require('./lib/hawk') -var Multipart = require('./lib/multipart').Multipart -var Redirect = require('./lib/redirect').Redirect -var Tunnel = require('./lib/tunnel').Tunnel -var now = require('performance-now') -var Buffer = require('safe-buffer').Buffer - -var safeStringify = helpers.safeStringify -var isReadStream = helpers.isReadStream -var toBase64 = helpers.toBase64 -var defer = helpers.defer -var copy = helpers.copy -var version = helpers.version -var globalCookieJar = cookies.jar() - -var globalPool = {} - -function filterForNonReserved (reserved, options) { - // Filter out properties that are not reserved. - // Reserved values are passed in at call site. - - var object = {} - for (var i in options) { - var notReserved = (reserved.indexOf(i) === -1) - if (notReserved) { - object[i] = options[i] - } - } - return object -} - -function filterOutReservedFunctions (reserved, options) { - // Filter out properties that are functions and are reserved. - // Reserved values are passed in at call site. - - var object = {} - for (var i in options) { - var isReserved = !(reserved.indexOf(i) === -1) - var isFunction = (typeof options[i] === 'function') - if (!(isReserved && isFunction)) { - object[i] = options[i] - } - } - return object -} - -// Return a simpler request object to allow serialization -function requestToJSON () { - var self = this - return { - uri: self.uri, - method: self.method, - headers: self.headers - } -} - -// Return a simpler response object to allow serialization -function responseToJSON () { - var self = this - return { - statusCode: self.statusCode, - body: self.body, - headers: self.headers, - request: requestToJSON.call(self.request) - } -} - -function Request (options) { - // if given the method property in options, set property explicitMethod to true - - // extend the Request instance with any non-reserved properties - // remove any reserved functions from the options object - // set Request instance to be readable and writable - // call init - - var self = this - - // start with HAR, then override with additional options - if (options.har) { - self._har = new Har(self) - options = self._har.options(options) - } - - stream.Stream.call(self) - var reserved = Object.keys(Request.prototype) - var nonReserved = filterForNonReserved(reserved, options) - - extend(self, nonReserved) - options = filterOutReservedFunctions(reserved, options) - - self.readable = true - self.writable = true - if (options.method) { - self.explicitMethod = true - } - self._qs = new Querystring(self) - self._auth = new Auth(self) - self._oauth = new OAuth(self) - self._multipart = new Multipart(self) - self._redirect = new Redirect(self) - self._tunnel = new Tunnel(self) - self.init(options) -} - -util.inherits(Request, stream.Stream) - -// Debugging -Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) -function debug () { - if (Request.debug) { - console.error('REQUEST %s', util.format.apply(util, arguments)) - } -} -Request.prototype.debug = debug - -Request.prototype.init = function (options) { - // init() contains all the code to setup the request object. - // the actual outgoing request is not started until start() is called - // this function is called from both the constructor and on redirect. - var self = this - if (!options) { - options = {} - } - self.headers = self.headers ? copy(self.headers) : {} - - // Delete headers with value undefined since they break - // ClientRequest.OutgoingMessage.setHeader in node 0.12 - for (var headerName in self.headers) { - if (typeof self.headers[headerName] === 'undefined') { - delete self.headers[headerName] - } - } - - caseless.httpify(self, self.headers) - - if (!self.method) { - self.method = options.method || 'GET' - } - if (!self.localAddress) { - self.localAddress = options.localAddress - } - - self._qs.init(options) - - debug(options) - if (!self.pool && self.pool !== false) { - self.pool = globalPool - } - self.dests = self.dests || [] - self.__isRequestRequest = true - - // Protect against double callback - if (!self._callback && self.callback) { - self._callback = self.callback - self.callback = function () { - if (self._callbackCalled) { - return // Print a warning maybe? - } - self._callbackCalled = true - self._callback.apply(self, arguments) - } - self.on('error', self.callback.bind()) - self.on('complete', self.callback.bind(self, null)) - } - - // People use this property instead all the time, so support it - if (!self.uri && self.url) { - self.uri = self.url - delete self.url - } - - // If there's a baseUrl, then use it as the base URL (i.e. uri must be - // specified as a relative path and is appended to baseUrl). - if (self.baseUrl) { - if (typeof self.baseUrl !== 'string') { - return self.emit('error', new Error('options.baseUrl must be a string')) - } - - if (typeof self.uri !== 'string') { - return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) - } - - if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { - return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) - } - - // Handle all cases to make sure that there's only one slash between - // baseUrl and uri. - var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 - var uriStartsWithSlash = self.uri.indexOf('/') === 0 - - if (baseUrlEndsWithSlash && uriStartsWithSlash) { - self.uri = self.baseUrl + self.uri.slice(1) - } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { - self.uri = self.baseUrl + self.uri - } else if (self.uri === '') { - self.uri = self.baseUrl - } else { - self.uri = self.baseUrl + '/' + self.uri - } - delete self.baseUrl - } - - // A URI is needed by this point, emit error if we haven't been able to get one - if (!self.uri) { - return self.emit('error', new Error('options.uri is a required argument')) - } - - // If a string URI/URL was given, parse it into a URL object - if (typeof self.uri === 'string') { - self.uri = url.parse(self.uri) - } - - // Some URL objects are not from a URL parsed string and need href added - if (!self.uri.href) { - self.uri.href = url.format(self.uri) - } - - // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme - if (self.uri.protocol === 'unix:') { - return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) - } - - // Support Unix Sockets - if (self.uri.host === 'unix') { - self.enableUnixSocket() - } - - if (self.strictSSL === false) { - self.rejectUnauthorized = false - } - - if (!self.uri.pathname) { self.uri.pathname = '/' } - - if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { - // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar - // Detect and reject it as soon as possible - var faultyUri = url.format(self.uri) - var message = 'Invalid URI "' + faultyUri + '"' - if (Object.keys(options).length === 0) { - // No option ? This can be the sign of a redirect - // As this is a case where the user cannot do anything (they didn't call request directly with this URL) - // they should be warned that it can be caused by a redirection (can save some hair) - message += '. This can be caused by a crappy redirection.' - } - // This error was fatal - self.abort() - return self.emit('error', new Error(message)) - } - - if (!self.hasOwnProperty('proxy')) { - self.proxy = getProxyFromURI(self.uri) - } - - self.tunnel = self._tunnel.isEnabled() - if (self.proxy) { - self._tunnel.setup(options) - } - - self._redirect.onRequest(options) - - self.setHost = false - if (!self.hasHeader('host')) { - var hostHeaderName = self.originalHostHeaderName || 'host' - self.setHeader(hostHeaderName, self.uri.host) - // Drop :port suffix from Host header if known protocol. - if (self.uri.port) { - if ((self.uri.port === '80' && self.uri.protocol === 'http:') || - (self.uri.port === '443' && self.uri.protocol === 'https:')) { - self.setHeader(hostHeaderName, self.uri.hostname) - } - } - self.setHost = true - } - - self.jar(self._jar || options.jar) - - if (!self.uri.port) { - if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 } - } - - if (self.proxy && !self.tunnel) { - self.port = self.proxy.port - self.host = self.proxy.hostname - } else { - self.port = self.uri.port - self.host = self.uri.hostname - } - - if (options.form) { - self.form(options.form) - } - - if (options.formData) { - var formData = options.formData - var requestForm = self.form() - var appendFormValue = function (key, value) { - if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) { - requestForm.append(key, value.value, value.options) - } else { - requestForm.append(key, value) - } - } - for (var formKey in formData) { - if (formData.hasOwnProperty(formKey)) { - var formValue = formData[formKey] - if (formValue instanceof Array) { - for (var j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]) - } - } else { - appendFormValue(formKey, formValue) - } - } - } - } - - if (options.qs) { - self.qs(options.qs) - } - - if (self.uri.path) { - self.path = self.uri.path - } else { - self.path = self.uri.pathname + (self.uri.search || '') - } - - if (self.path.length === 0) { - self.path = '/' - } - - // Auth must happen last in case signing is dependent on other headers - if (options.aws) { - self.aws(options.aws) - } - - if (options.hawk) { - self.hawk(options.hawk) - } - - if (options.httpSignature) { - self.httpSignature(options.httpSignature) - } - - if (options.auth) { - if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { - options.auth.user = options.auth.username - } - if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { - options.auth.pass = options.auth.password - } - - self.auth( - options.auth.user, - options.auth.pass, - options.auth.sendImmediately, - options.auth.bearer - ) - } - - if (self.gzip && !self.hasHeader('accept-encoding')) { - self.setHeader('accept-encoding', 'gzip, deflate') - } - - if (self.uri.auth && !self.hasHeader('authorization')) { - var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) }) - self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) - } - - if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { - var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) }) - var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) - self.setHeader('proxy-authorization', authHeader) - } - - if (self.proxy && !self.tunnel) { - self.path = (self.uri.protocol + '//' + self.uri.host + self.path) - } - - if (options.json) { - self.json(options.json) - } - if (options.multipart) { - self.multipart(options.multipart) - } - - if (options.time) { - self.timing = true - - // NOTE: elapsedTime is deprecated in favor of .timings - self.elapsedTime = self.elapsedTime || 0 - } - - function setContentLength () { - if (isTypedArray(self.body)) { - self.body = Buffer.from(self.body) - } - - if (!self.hasHeader('content-length')) { - var length - if (typeof self.body === 'string') { - length = Buffer.byteLength(self.body) - } else if (Array.isArray(self.body)) { - length = self.body.reduce(function (a, b) { return a + b.length }, 0) - } else { - length = self.body.length - } - - if (length) { - self.setHeader('content-length', length) - } else { - self.emit('error', new Error('Argument error, options.body.')) - } - } - } - if (self.body && !isstream(self.body)) { - setContentLength() - } - - if (options.oauth) { - self.oauth(options.oauth) - } else if (self._oauth.params && self.hasHeader('authorization')) { - self.oauth(self._oauth.params) - } - - var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol - var defaultModules = {'http:': http, 'https:': https} - var httpModules = self.httpModules || {} - - self.httpModule = httpModules[protocol] || defaultModules[protocol] - - if (!self.httpModule) { - return self.emit('error', new Error('Invalid protocol: ' + protocol)) - } - - if (options.ca) { - self.ca = options.ca - } - - if (!self.agent) { - if (options.agentOptions) { - self.agentOptions = options.agentOptions - } - - if (options.agentClass) { - self.agentClass = options.agentClass - } else if (options.forever) { - var v = version() - // use ForeverAgent in node 0.10- only - if (v.major === 0 && v.minor <= 10) { - self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL - } else { - self.agentClass = self.httpModule.Agent - self.agentOptions = self.agentOptions || {} - self.agentOptions.keepAlive = true - } - } else { - self.agentClass = self.httpModule.Agent - } - } - - if (self.pool === false) { - self.agent = false - } else { - self.agent = self.agent || self.getNewAgent() - } - - self.on('pipe', function (src) { - if (self.ntick && self._started) { - self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) - } - self.src = src - if (isReadStream(src)) { - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', mime.lookup(src.path)) - } - } else { - if (src.headers) { - for (var i in src.headers) { - if (!self.hasHeader(i)) { - self.setHeader(i, src.headers[i]) - } - } - } - if (self._json && !self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') - } - if (src.method && !self.explicitMethod) { - self.method = src.method - } - } - - // self.on('pipe', function () { - // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') - // }) - }) - - defer(function () { - if (self._aborted) { - return - } - - var end = function () { - if (self._form) { - if (!self._auth.hasAuth) { - self._form.pipe(self) - } else if (self._auth.hasAuth && self._auth.sentAuth) { - self._form.pipe(self) - } - } - if (self._multipart && self._multipart.chunked) { - self._multipart.body.pipe(self) - } - if (self.body) { - if (isstream(self.body)) { - self.body.pipe(self) - } else { - setContentLength() - if (Array.isArray(self.body)) { - self.body.forEach(function (part) { - self.write(part) - }) - } else { - self.write(self.body) - } - self.end() - } - } else if (self.requestBodyStream) { - console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') - self.requestBodyStream.pipe(self) - } else if (!self.src) { - if (self._auth.hasAuth && !self._auth.sentAuth) { - self.end() - return - } - if (self.method !== 'GET' && typeof self.method !== 'undefined') { - self.setHeader('content-length', 0) - } - self.end() - } - } - - if (self._form && !self.hasHeader('content-length')) { - // Before ending the request, we had to compute the length of the whole form, asyncly - self.setHeader(self._form.getHeaders(), true) - self._form.getLength(function (err, length) { - if (!err && !isNaN(length)) { - self.setHeader('content-length', length) - } - end() - }) - } else { - end() - } - - self.ntick = true - }) -} - -Request.prototype.getNewAgent = function () { - var self = this - var Agent = self.agentClass - var options = {} - if (self.agentOptions) { - for (var i in self.agentOptions) { - options[i] = self.agentOptions[i] - } - } - if (self.ca) { - options.ca = self.ca - } - if (self.ciphers) { - options.ciphers = self.ciphers - } - if (self.secureProtocol) { - options.secureProtocol = self.secureProtocol - } - if (self.secureOptions) { - options.secureOptions = self.secureOptions - } - if (typeof self.rejectUnauthorized !== 'undefined') { - options.rejectUnauthorized = self.rejectUnauthorized - } - - if (self.cert && self.key) { - options.key = self.key - options.cert = self.cert - } - - if (self.pfx) { - options.pfx = self.pfx - } - - if (self.passphrase) { - options.passphrase = self.passphrase - } - - var poolKey = '' - - // different types of agents are in different pools - if (Agent !== self.httpModule.Agent) { - poolKey += Agent.name - } - - // ca option is only relevant if proxy or destination are https - var proxy = self.proxy - if (typeof proxy === 'string') { - proxy = url.parse(proxy) - } - var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' - - if (isHttps) { - if (options.ca) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.ca - } - - if (typeof options.rejectUnauthorized !== 'undefined') { - if (poolKey) { - poolKey += ':' - } - poolKey += options.rejectUnauthorized - } - - if (options.cert) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.cert.toString('ascii') + options.key.toString('ascii') - } - - if (options.pfx) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.pfx.toString('ascii') - } - - if (options.ciphers) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.ciphers - } - - if (options.secureProtocol) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.secureProtocol - } - - if (options.secureOptions) { - if (poolKey) { - poolKey += ':' - } - poolKey += options.secureOptions - } - } - - if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { - // not doing anything special. Use the globalAgent - return self.httpModule.globalAgent - } - - // we're using a stored agent. Make sure it's protocol-specific - poolKey = self.uri.protocol + poolKey - - // generate a new agent for this setting if none yet exists - if (!self.pool[poolKey]) { - self.pool[poolKey] = new Agent(options) - // properly set maxSockets on new agents - if (self.pool.maxSockets) { - self.pool[poolKey].maxSockets = self.pool.maxSockets - } - } - - return self.pool[poolKey] -} - -Request.prototype.start = function () { - // start() is called once we are ready to send the outgoing HTTP request. - // this is usually called on the first write(), end() or on nextTick() - var self = this - - if (self.timing) { - // All timings will be relative to this request's startTime. In order to do this, - // we need to capture the wall-clock start time (via Date), immediately followed - // by the high-resolution timer (via now()). While these two won't be set - // at the _exact_ same time, they should be close enough to be able to calculate - // high-resolution, monotonically non-decreasing timestamps relative to startTime. - var startTime = new Date().getTime() - var startTimeNow = now() - } - - if (self._aborted) { - return - } - - self._started = true - self.method = self.method || 'GET' - self.href = self.uri.href - - if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { - self.setHeader('content-length', self.src.stat.size) - } - if (self._aws) { - self.aws(self._aws, true) - } - - // We have a method named auth, which is completely different from the http.request - // auth option. If we don't remove it, we're gonna have a bad time. - var reqOptions = copy(self) - delete reqOptions.auth - - debug('make request', self.uri.href) - - // node v6.8.0 now supports a `timeout` value in `http.request()`, but we - // should delete it for now since we handle timeouts manually for better - // consistency with node versions before v6.8.0 - delete reqOptions.timeout - - try { - self.req = self.httpModule.request(reqOptions) - } catch (err) { - self.emit('error', err) - return - } - - if (self.timing) { - self.startTime = startTime - self.startTimeNow = startTimeNow - - // Timing values will all be relative to startTime (by comparing to startTimeNow - // so we have an accurate clock) - self.timings = {} - } - - var timeout - if (self.timeout && !self.timeoutTimer) { - if (self.timeout < 0) { - timeout = 0 - } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) { - timeout = self.timeout - } - } - - self.req.on('response', self.onRequestResponse.bind(self)) - self.req.on('error', self.onRequestError.bind(self)) - self.req.on('drain', function () { - self.emit('drain') - }) - - self.req.on('socket', function (socket) { - // `._connecting` was the old property which was made public in node v6.1.0 - var isConnecting = socket._connecting || socket.connecting - if (self.timing) { - self.timings.socket = now() - self.startTimeNow - - if (isConnecting) { - var onLookupTiming = function () { - self.timings.lookup = now() - self.startTimeNow - } - - var onConnectTiming = function () { - self.timings.connect = now() - self.startTimeNow - } - - socket.once('lookup', onLookupTiming) - socket.once('connect', onConnectTiming) - - // clean up timing event listeners if needed on error - self.req.once('error', function () { - socket.removeListener('lookup', onLookupTiming) - socket.removeListener('connect', onConnectTiming) - }) - } - } - - var setReqTimeout = function () { - // This timeout sets the amount of time to wait *between* bytes sent - // from the server once connected. - // - // In particular, it's useful for erroring if the server fails to send - // data halfway through streaming a response. - self.req.setTimeout(timeout, function () { - if (self.req) { - self.abort() - var e = new Error('ESOCKETTIMEDOUT') - e.code = 'ESOCKETTIMEDOUT' - e.connect = false - self.emit('error', e) - } - }) - } - if (timeout !== undefined) { - // Only start the connection timer if we're actually connecting a new - // socket, otherwise if we're already connected (because this is a - // keep-alive connection) do not bother. This is important since we won't - // get a 'connect' event for an already connected socket. - if (isConnecting) { - var onReqSockConnect = function () { - socket.removeListener('connect', onReqSockConnect) - clearTimeout(self.timeoutTimer) - self.timeoutTimer = null - setReqTimeout() - } - - socket.on('connect', onReqSockConnect) - - self.req.on('error', function (err) { // eslint-disable-line handle-callback-err - socket.removeListener('connect', onReqSockConnect) - }) - - // Set a timeout in memory - this block will throw if the server takes more - // than `timeout` to write the HTTP status and headers (corresponding to - // the on('response') event on the client). NB: this measures wall-clock - // time, not the time between bytes sent by the server. - self.timeoutTimer = setTimeout(function () { - socket.removeListener('connect', onReqSockConnect) - self.abort() - var e = new Error('ETIMEDOUT') - e.code = 'ETIMEDOUT' - e.connect = true - self.emit('error', e) - }, timeout) - } else { - // We're already connected - setReqTimeout() - } - } - self.emit('socket', socket) - }) - - self.emit('request', self.req) -} - -Request.prototype.onRequestError = function (error) { - var self = this - if (self._aborted) { - return - } - if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' && - self.agent.addRequestNoreuse) { - self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } - self.start() - self.req.end() - return - } - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer) - self.timeoutTimer = null - } - self.emit('error', error) -} - -Request.prototype.onRequestResponse = function (response) { - var self = this - - if (self.timing) { - self.timings.response = now() - self.startTimeNow - } - - debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) - response.on('end', function () { - if (self.timing) { - self.timings.end = now() - self.startTimeNow - response.timingStart = self.startTime - - // fill in the blanks for any periods that didn't trigger, such as - // no lookup or connect due to keep alive - if (!self.timings.socket) { - self.timings.socket = 0 - } - if (!self.timings.lookup) { - self.timings.lookup = self.timings.socket - } - if (!self.timings.connect) { - self.timings.connect = self.timings.lookup - } - if (!self.timings.response) { - self.timings.response = self.timings.connect - } - - debug('elapsed time', self.timings.end) - - // elapsedTime includes all redirects - self.elapsedTime += Math.round(self.timings.end) - - // NOTE: elapsedTime is deprecated in favor of .timings - response.elapsedTime = self.elapsedTime - - // timings is just for the final fetch - response.timings = self.timings - - // pre-calculate phase timings as well - response.timingPhases = { - wait: self.timings.socket, - dns: self.timings.lookup - self.timings.socket, - tcp: self.timings.connect - self.timings.lookup, - firstByte: self.timings.response - self.timings.connect, - download: self.timings.end - self.timings.response, - total: self.timings.end - } - } - debug('response end', self.uri.href, response.statusCode, response.headers) - }) - - if (self._aborted) { - debug('aborted', self.uri.href) - response.resume() - return - } - - self.response = response - response.request = self - response.toJSON = responseToJSON - - // XXX This is different on 0.10, because SSL is strict by default - if (self.httpModule === https && - self.strictSSL && (!response.hasOwnProperty('socket') || - !response.socket.authorized)) { - debug('strict ssl error', self.uri.href) - var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' - self.emit('error', new Error('SSL Error: ' + sslErr)) - return - } - - // Save the original host before any redirect (if it changes, we need to - // remove any authorization headers). Also remember the case of the header - // name because lots of broken servers expect Host instead of host and we - // want the caller to be able to specify this. - self.originalHost = self.getHeader('host') - if (!self.originalHostHeaderName) { - self.originalHostHeaderName = self.hasHeader('host') - } - if (self.setHost) { - self.removeHeader('host') - } - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer) - self.timeoutTimer = null - } - - var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar - var addCookie = function (cookie) { - // set the cookie if it's domain in the href's domain. - try { - targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) - } catch (e) { - self.emit('error', e) - } - } - - response.caseless = caseless(response.headers) - - if (response.caseless.has('set-cookie') && (!self._disableCookies)) { - var headerName = response.caseless.has('set-cookie') - if (Array.isArray(response.headers[headerName])) { - response.headers[headerName].forEach(addCookie) - } else { - addCookie(response.headers[headerName]) - } - } - - if (self._redirect.onResponse(response)) { - return // Ignore the rest of the response - } else { - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) { - self.response.emit('end') - } - }) - - response.once('end', function () { - self._ended = true - }) - - var noBody = function (code) { - return ( - self.method === 'HEAD' || - // Informational - (code >= 100 && code < 200) || - // No Content - code === 204 || - // Not Modified - code === 304 - ) - } - - var responseContent - if (self.gzip && !noBody(response.statusCode)) { - var contentEncoding = response.headers['content-encoding'] || 'identity' - contentEncoding = contentEncoding.trim().toLowerCase() - - // Be more lenient with decoding compressed responses, since (very rarely) - // servers send slightly invalid gzip responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - var zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - } - - if (contentEncoding === 'gzip') { - responseContent = zlib.createGunzip(zlibOptions) - response.pipe(responseContent) - } else if (contentEncoding === 'deflate') { - responseContent = zlib.createInflate(zlibOptions) - response.pipe(responseContent) - } else { - // Since previous versions didn't check for Content-Encoding header, - // ignore any invalid values to preserve backwards-compatibility - if (contentEncoding !== 'identity') { - debug('ignoring unrecognized Content-Encoding ' + contentEncoding) - } - responseContent = response - } - } else { - responseContent = response - } - - if (self.encoding) { - if (self.dests.length !== 0) { - console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') - } else { - responseContent.setEncoding(self.encoding) - } - } - - if (self._paused) { - responseContent.pause() - } - - self.responseContent = responseContent - - self.emit('response', response) - - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) - - responseContent.on('data', function (chunk) { - if (self.timing && !self.responseStarted) { - self.responseStartTime = (new Date()).getTime() - - // NOTE: responseStartTime is deprecated in favor of .timings - response.responseStartTime = self.responseStartTime - } - self._destdata = true - self.emit('data', chunk) - }) - responseContent.once('end', function (chunk) { - self.emit('end', chunk) - }) - responseContent.on('error', function (error) { - self.emit('error', error) - }) - responseContent.on('close', function () { self.emit('close') }) - - if (self.callback) { - self.readResponseBody(response) - } else { // if no callback - self.on('end', function () { - if (self._aborted) { - debug('aborted', self.uri.href) - return - } - self.emit('complete', response) - }) - } - } - debug('finish init function', self.uri.href) -} - -Request.prototype.readResponseBody = function (response) { - var self = this - debug("reading response's body") - var buffers = [] - var bufferLength = 0 - var strings = [] - - self.on('data', function (chunk) { - if (!Buffer.isBuffer(chunk)) { - strings.push(chunk) - } else if (chunk.length) { - bufferLength += chunk.length - buffers.push(chunk) - } - }) - self.on('end', function () { - debug('end event', self.uri.href) - if (self._aborted) { - debug('aborted', self.uri.href) - // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request. - // This can lead to leaky behavior if the user retains a reference to the request object. - buffers = [] - bufferLength = 0 - return - } - - if (bufferLength) { - debug('has body', self.uri.href, bufferLength) - response.body = Buffer.concat(buffers, bufferLength) - if (self.encoding !== null) { - response.body = response.body.toString(self.encoding) - } - // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request. - // This can lead to leaky behavior if the user retains a reference to the request object. - buffers = [] - bufferLength = 0 - } else if (strings.length) { - // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. - // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). - if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { - strings[0] = strings[0].substring(1) - } - response.body = strings.join('') - } - - if (self._json) { - try { - response.body = JSON.parse(response.body, self._jsonReviver) - } catch (e) { - debug('invalid JSON received', self.uri.href) - } - } - debug('emitting complete', self.uri.href) - if (typeof response.body === 'undefined' && !self._json) { - response.body = self.encoding === null ? Buffer.alloc(0) : '' - } - self.emit('complete', response, response.body) - }) -} - -Request.prototype.abort = function () { - var self = this - self._aborted = true - - if (self.req) { - self.req.abort() - } else if (self.response) { - self.response.destroy() - } - - self.emit('abort') -} - -Request.prototype.pipeDest = function (dest) { - var self = this - var response = self.response - // Called after the response is received - if (dest.headers && !dest.headersSent) { - if (response.caseless.has('content-type')) { - var ctname = response.caseless.has('content-type') - if (dest.setHeader) { - dest.setHeader(ctname, response.headers[ctname]) - } else { - dest.headers[ctname] = response.headers[ctname] - } - } - - if (response.caseless.has('content-length')) { - var clname = response.caseless.has('content-length') - if (dest.setHeader) { - dest.setHeader(clname, response.headers[clname]) - } else { - dest.headers[clname] = response.headers[clname] - } - } - } - if (dest.setHeader && !dest.headersSent) { - for (var i in response.headers) { - // If the response content is being decoded, the Content-Encoding header - // of the response doesn't represent the piped content, so don't pass it. - if (!self.gzip || i !== 'content-encoding') { - dest.setHeader(i, response.headers[i]) - } - } - dest.statusCode = response.statusCode - } - if (self.pipefilter) { - self.pipefilter(response, dest) - } -} - -Request.prototype.qs = function (q, clobber) { - var self = this - var base - if (!clobber && self.uri.query) { - base = self._qs.parse(self.uri.query) - } else { - base = {} - } - - for (var i in q) { - base[i] = q[i] - } - - var qs = self._qs.stringify(base) - - if (qs === '') { - return self - } - - self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) - self.url = self.uri - self.path = self.uri.path - - if (self.uri.host === 'unix') { - self.enableUnixSocket() - } - - return self -} -Request.prototype.form = function (form) { - var self = this - if (form) { - if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { - self.setHeader('content-type', 'application/x-www-form-urlencoded') - } - self.body = (typeof form === 'string') - ? self._qs.rfc3986(form.toString('utf8')) - : self._qs.stringify(form).toString('utf8') - return self - } - // create form-data object - self._form = new FormData() - self._form.on('error', function (err) { - err.message = 'form-data: ' + err.message - self.emit('error', err) - self.abort() - }) - return self._form -} -Request.prototype.multipart = function (multipart) { - var self = this - - self._multipart.onRequest(multipart) - - if (!self._multipart.chunked) { - self.body = self._multipart.body - } - - return self -} -Request.prototype.json = function (val) { - var self = this - - if (!self.hasHeader('accept')) { - self.setHeader('accept', 'application/json') - } - - if (typeof self.jsonReplacer === 'function') { - self._jsonReplacer = self.jsonReplacer - } - - self._json = true - if (typeof val === 'boolean') { - if (self.body !== undefined) { - if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { - self.body = safeStringify(self.body, self._jsonReplacer) - } else { - self.body = self._qs.rfc3986(self.body) - } - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') - } - } - } else { - self.body = safeStringify(val, self._jsonReplacer) - if (!self.hasHeader('content-type')) { - self.setHeader('content-type', 'application/json') - } - } - - if (typeof self.jsonReviver === 'function') { - self._jsonReviver = self.jsonReviver - } - - return self -} -Request.prototype.getHeader = function (name, headers) { - var self = this - var result, re, match - if (!headers) { - headers = self.headers - } - Object.keys(headers).forEach(function (key) { - if (key.length !== name.length) { - return - } - re = new RegExp(name, 'i') - match = key.match(re) - if (match) { - result = headers[key] - } - }) - return result -} -Request.prototype.enableUnixSocket = function () { - // Get the socket & request paths from the URL - var unixParts = this.uri.path.split(':') - var host = unixParts[0] - var path = unixParts[1] - // Apply unix properties to request - this.socketPath = host - this.uri.pathname = path - this.uri.path = path - this.uri.host = host - this.uri.hostname = host - this.uri.isUnix = true -} - -Request.prototype.auth = function (user, pass, sendImmediately, bearer) { - var self = this - - self._auth.onRequest(user, pass, sendImmediately, bearer) - - return self -} -Request.prototype.aws = function (opts, now) { - var self = this - - if (!now) { - self._aws = opts - return self - } - - if (opts.sign_version === 4 || opts.sign_version === '4') { - // use aws4 - var options = { - host: self.uri.host, - path: self.uri.path, - method: self.method, - headers: self.headers, - body: self.body - } - if (opts.service) { - options.service = opts.service - } - var signRes = aws4.sign(options, { - accessKeyId: opts.key, - secretAccessKey: opts.secret, - sessionToken: opts.session - }) - self.setHeader('authorization', signRes.headers.Authorization) - self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']) - if (signRes.headers['X-Amz-Security-Token']) { - self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) - } - } else { - // default: use aws-sign2 - var date = new Date() - self.setHeader('date', date.toUTCString()) - var auth = { - key: opts.key, - secret: opts.secret, - verb: self.method.toUpperCase(), - date: date, - contentType: self.getHeader('content-type') || '', - md5: self.getHeader('content-md5') || '', - amazonHeaders: aws2.canonicalizeHeaders(self.headers) - } - var path = self.uri.path - if (opts.bucket && path) { - auth.resource = '/' + opts.bucket + path - } else if (opts.bucket && !path) { - auth.resource = '/' + opts.bucket - } else if (!opts.bucket && path) { - auth.resource = path - } else if (!opts.bucket && !path) { - auth.resource = '/' - } - auth.resource = aws2.canonicalizeResource(auth.resource) - self.setHeader('authorization', aws2.authorization(auth)) - } - - return self -} -Request.prototype.httpSignature = function (opts) { - var self = this - httpSignature.signRequest({ - getHeader: function (header) { - return self.getHeader(header, self.headers) - }, - setHeader: function (header, value) { - self.setHeader(header, value) - }, - method: self.method, - path: self.path - }, opts) - debug('httpSignature authorization', self.getHeader('authorization')) - - return self -} -Request.prototype.hawk = function (opts) { - var self = this - self.setHeader('Authorization', hawk.header(self.uri, self.method, opts)) -} -Request.prototype.oauth = function (_oauth) { - var self = this - - self._oauth.onRequest(_oauth) - - return self -} - -Request.prototype.jar = function (jar) { - var self = this - var cookies - - if (self._redirect.redirectsFollowed === 0) { - self.originalCookieHeader = self.getHeader('cookie') - } - - if (!jar) { - // disable cookies - cookies = false - self._disableCookies = true - } else { - var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar - var urihref = self.uri.href - // fetch cookie in the Specified host - if (targetCookieJar) { - cookies = targetCookieJar.getCookieString(urihref) - } - } - - // if need cookie and cookie is not empty - if (cookies && cookies.length) { - if (self.originalCookieHeader) { - // Don't overwrite existing Cookie header - self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) - } else { - self.setHeader('cookie', cookies) - } - } - self._jar = jar - return self -} - -// Stream API -Request.prototype.pipe = function (dest, opts) { - var self = this - - if (self.response) { - if (self._destdata) { - self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) - } else if (self._ended) { - self.emit('error', new Error('You cannot pipe after the response has been ended.')) - } else { - stream.Stream.prototype.pipe.call(self, dest, opts) - self.pipeDest(dest) - return dest - } - } else { - self.dests.push(dest) - stream.Stream.prototype.pipe.call(self, dest, opts) - return dest - } -} -Request.prototype.write = function () { - var self = this - if (self._aborted) { return } - - if (!self._started) { - self.start() - } - if (self.req) { - return self.req.write.apply(self.req, arguments) - } -} -Request.prototype.end = function (chunk) { - var self = this - if (self._aborted) { return } - - if (chunk) { - self.write(chunk) - } - if (!self._started) { - self.start() - } - if (self.req) { - self.req.end() - } -} -Request.prototype.pause = function () { - var self = this - if (!self.responseContent) { - self._paused = true - } else { - self.responseContent.pause.apply(self.responseContent, arguments) - } -} -Request.prototype.resume = function () { - var self = this - if (!self.responseContent) { - self._paused = false - } else { - self.responseContent.resume.apply(self.responseContent, arguments) - } -} -Request.prototype.destroy = function () { - var self = this - if (!self._ended) { - self.end() - } else if (self.response) { - self.response.destroy() - } -} - -Request.defaultProxyHeaderWhiteList = - Tunnel.defaultProxyHeaderWhiteList.slice() - -Request.defaultProxyHeaderExclusiveList = - Tunnel.defaultProxyHeaderExclusiveList.slice() - -// Exports - -Request.prototype.toJSON = requestToJSON -module.exports = Request - -}).call(this,require('_process')) -},{"./lib/auth":1573,"./lib/cookies":1574,"./lib/getProxyFromURI":1575,"./lib/har":1576,"./lib/hawk":1577,"./lib/helpers":1578,"./lib/multipart":1579,"./lib/oauth":1580,"./lib/querystring":1581,"./lib/redirect":1582,"./lib/tunnel":1583,"_process":1438,"aws-sign2":154,"aws4":155,"caseless":220,"extend":373,"forever-agent":381,"form-data":382,"http":1716,"http-signature":441,"https":446,"is-typedarray":779,"isstream":805,"mime-types":1302,"performance-now":1436,"safe-buffer":1593,"stream":1715,"url":1769,"util":1776,"zlib":211}],1590:[function(require,module,exports){ -'use strict' - -var getTime = require('./time') - -function Retimer (callback, timeout, args) { - var that = this - - this._started = getTime() - this._rescheduled = 0 - this._scheduled = timeout - this._args = args - - this._timer = setTimeout(timerWrapper, timeout) - - function timerWrapper () { - if (that._rescheduled > 0) { - that._scheduled = that._rescheduled - (getTime() - that._started) - that._timer = setTimeout(timerWrapper, that._scheduled) - that._rescheduled = 0 - } else { - callback.apply(null, that._args) - } - } -} - -Retimer.prototype.reschedule = function (timeout) { - var now = getTime() - if ((now + timeout) - (this._started + this._scheduled) < 0) { - return false - } else { - this._started = now - this._rescheduled = timeout - return true - } -} - -Retimer.prototype.clear = function () { - clearTimeout(this._timer) -} - -function retimer () { - if (typeof arguments[0] !== 'function') { - throw new Error('callback needed') - } - - if (typeof arguments[1] !== 'number') { - throw new Error('timeout needed') - } - - var args - - if (arguments.length > 0) { - args = new Array(arguments.length - 2) - - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 2] - } - } - - return new Retimer(arguments[0], arguments[1], args) -} - -module.exports = retimer - -},{"./time":1591}],1591:[function(require,module,exports){ -'use strict' - -module.exports = function getTime () { - return Date.now() -} - -},{}],1592:[function(require,module,exports){ -'use strict' -var Buffer = require('buffer').Buffer -var inherits = require('inherits') -var HashBase = require('hash-base') - -var ARRAY16 = new Array(16) - -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] - -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] - -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -] - -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] - -var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] -var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] - -function RIPEMD160 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 -} - -inherits(RIPEMD160, HashBase) - -RIPEMD160.prototype._update = function () { - var words = ARRAY16 - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) - - var al = this._a | 0 - var bl = this._b | 0 - var cl = this._c | 0 - var dl = this._d | 0 - var el = this._e | 0 - - var ar = this._a | 0 - var br = this._b | 0 - var cr = this._c | 0 - var dr = this._d | 0 - var er = this._e | 0 - - // computation - for (var i = 0; i < 80; i += 1) { - var tl - var tr - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) - } - - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = tl - - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = tr - } - - // update state - var t = (this._b + cl + dr) | 0 - this._b = (this._c + dl + er) | 0 - this._c = (this._d + el + ar) | 0 - this._d = (this._e + al + br) | 0 - this._e = (this._a + bl + cr) | 0 - this._a = t -} - -RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - buffer.writeInt32LE(this._e, 16) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 -} - -function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 -} - -function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 -} - -module.exports = RIPEMD160 - -},{"buffer":217,"hash-base":423,"inherits":453}],1593:[function(require,module,exports){ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -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) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -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) - } else { - buf.fill(fill) - } - } 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":217}],1594:[function(require,module,exports){ -(function (process){ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -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] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -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) - } - 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) - } - return Buffer(value, encodingOrOffset, length) - } -} - -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) - } - 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 - } -} - -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 - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - -}).call(this,require('_process')) -},{"_process":1438,"buffer":217}],1595:[function(require,module,exports){ -/*jshint node:true*/ -'use strict'; - -/** - * Replaces characters in strings that are illegal/unsafe for filenames. - * Unsafe characters are either removed or replaced by a substitute set - * in the optional `options` object. - * - * Illegal Characters on Various Operating Systems - * / ? < > \ : * | " - * https://kb.acronis.com/content/39790 - * - * Unicode Control codes - * C0 0x00-0x1f & C1 (0x80-0x9f) - * http://en.wikipedia.org/wiki/C0_and_C1_control_codes - * - * Reserved filenames on Unix-based systems (".", "..") - * Reserved filenames in Windows ("CON", "PRN", "AUX", "NUL", "COM1", - * "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", - * "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", and - * "LPT9") case-insesitively and with or without filename extensions. - * - * Capped at 255 characters in length. - * http://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs - * - * @param {String} input Original filename - * @param {Object} options {replacement: String | Function } - * @return {String} Sanitized filename - */ - -var truncate = require("truncate-utf8-bytes"); - -var illegalRe = /[\/\?<>\\:\*\|"]/g; -var controlRe = /[\x00-\x1f\x80-\x9f]/g; -var reservedRe = /^\.+$/; -var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; -var windowsTrailingRe = /[\. ]+$/; - -function sanitize(input, replacement) { - if (typeof input !== 'string') { - throw new Error('Input must be string'); - } - var sanitized = input - .replace(illegalRe, replacement) - .replace(controlRe, replacement) - .replace(reservedRe, replacement) - .replace(windowsReservedRe, replacement) - .replace(windowsTrailingRe, replacement); - return truncate(sanitized, 255); -} - -module.exports = function (input, options) { - var replacement = (options && options.replacement) || ''; - var output = sanitize(input, replacement); - if (replacement === '') { - return output; - } - return sanitize(output, ''); -}; - -},{"truncate-utf8-bytes":1759}],1596:[function(require,module,exports){ -const scrypt = require('./scryptSync') -scrypt.async = require('./scrypt') -module.exports = scrypt - -},{"./scrypt":1597,"./scryptSync":1598}],1597:[function(require,module,exports){ -const crypto = require('crypto') -const { - checkAndInit, - smix -} = require('./utils') - -// N = Cpu cost, r = Memory cost, p = parallelization cost -async function scrypt (key, salt, N, r, p, dkLen, progressCallback, promiseInterval) { - const { - XY, - V, - B32, - x, - _X, - B, - tickCallback - } = checkAndInit(key, salt, N, r, p, dkLen, progressCallback) - - for (var i = 0; i < p; i++) { - await smix(B, i * 128 * r, r, N, V, XY, _X, B32, x, tickCallback, promiseInterval) - } - - return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256') -} - -module.exports = scrypt - -},{"./utils":1599,"crypto":236}],1598:[function(require,module,exports){ -const crypto = require('crypto') -const { - checkAndInit, - smixSync -} = require('./utils') - -// N = Cpu cost, r = Memory cost, p = parallelization cost -function scrypt (key, salt, N, r, p, dkLen, progressCallback) { - const { - XY, - V, - B32, - x, - _X, - B, - tickCallback - } = checkAndInit(key, salt, N, r, p, dkLen, progressCallback) - - for (var i = 0; i < p; i++) { - smixSync(B, i * 128 * r, r, N, V, XY, _X, B32, x, tickCallback) - } - - return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256') -} - -module.exports = scrypt - -},{"./utils":1599,"crypto":236}],1599:[function(require,module,exports){ -(function (Buffer,setImmediate){ -const crypto = require('crypto') -const MAX_VALUE = 0x7fffffff -const DEFAULT_PROMISE_INTERVAL = 5000 -/* eslint-disable camelcase */ - -function checkAndInit (key, salt, N, r, p, dkLen, progressCallback) { - if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2') - - if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large') - if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large') - - let XY = Buffer.alloc(256 * r) - let V = Buffer.alloc(128 * r * N) - - // pseudo global - let B32 = new Int32Array(16) // salsa20_8 - let x = new Int32Array(16) // salsa20_8 - let _X = Buffer.alloc(64) // blockmix_salsa8 - - // pseudo global - let B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256') - - let tickCallback - if (progressCallback) { - let totalOps = p * N * 2 - let currentOp = 0 - - tickCallback = function () { - ++currentOp - - // send progress notifications once every 1,000 ops - if (currentOp % 1000 === 0) { - progressCallback({ - current: currentOp, - total: totalOps, - percent: (currentOp / totalOps) * 100.0 - }) - } - } - } - return { - XY, - V, - B32, - x, - _X, - B, - tickCallback - } -} - -async function smix (B, Bi, r, N, V, XY, _X, B32, x, tickCallback, promiseInterval) { - promiseInterval = promiseInterval || DEFAULT_PROMISE_INTERVAL - let Xi = 0 - let Yi = 128 * r - let i - - B.copy(XY, Xi, Bi, Bi + Yi) - - for (i = 0; i < N; i++) { - XY.copy(V, i * Yi, Xi, Xi + Yi) - if (i % promiseInterval === 0) { - await new Promise(resolve => setImmediate(resolve)) - } - blockmix_salsa8(XY, Xi, Yi, r, _X, B32, x) - - if (tickCallback) tickCallback() - } - - for (i = 0; i < N; i++) { - let offset = Xi + (2 * r - 1) * 64 - let j = XY.readUInt32LE(offset) & (N - 1) - blockxor(V, j * Yi, XY, Xi, Yi) - if (i % promiseInterval === 0) { - await new Promise(resolve => setImmediate(resolve)) - } - blockmix_salsa8(XY, Xi, Yi, r, _X, B32, x) - - if (tickCallback) tickCallback() - } - - XY.copy(B, Bi, Xi, Xi + Yi) -} - -function smixSync (B, Bi, r, N, V, XY, _X, B32, x, tickCallback) { - let Xi = 0 - let Yi = 128 * r - let i - - B.copy(XY, Xi, Bi, Bi + Yi) - - for (i = 0; i < N; i++) { - XY.copy(V, i * Yi, Xi, Xi + Yi) - blockmix_salsa8(XY, Xi, Yi, r, _X, B32, x) - - if (tickCallback) tickCallback() - } - - for (i = 0; i < N; i++) { - let offset = Xi + (2 * r - 1) * 64 - let j = XY.readUInt32LE(offset) & (N - 1) - blockxor(V, j * Yi, XY, Xi, Yi) - blockmix_salsa8(XY, Xi, Yi, r, _X, B32, x) - - if (tickCallback) tickCallback() - } - - XY.copy(B, Bi, Xi, Xi + Yi) -} - -function blockmix_salsa8 (BY, Bi, Yi, r, _X, B32, x) { - let i - - arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64) - - for (i = 0; i < 2 * r; i++) { - blockxor(BY, i * 64, _X, 0, 64) - salsa20_8(_X, B32, x) - arraycopy(_X, 0, BY, Yi + (i * 64), 64) - } - - for (i = 0; i < r; i++) { - arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64) - } - - for (i = 0; i < r; i++) { - arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64) - } -} - -function R (a, b) { - return (a << b) | (a >>> (32 - b)) -} - -function salsa20_8 (B, B32, x) { - let i - - for (i = 0; i < 16; i++) { - B32[i] = (B[i * 4 + 0] & 0xff) << 0 - B32[i] |= (B[i * 4 + 1] & 0xff) << 8 - B32[i] |= (B[i * 4 + 2] & 0xff) << 16 - B32[i] |= (B[i * 4 + 3] & 0xff) << 24 - // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js - } - - arraycopy(B32, 0, x, 0, 16) - - for (i = 8; i > 0; i -= 2) { - x[4] ^= R(x[0] + x[12], 7) - x[8] ^= R(x[4] + x[0], 9) - x[12] ^= R(x[8] + x[4], 13) - x[0] ^= R(x[12] + x[8], 18) - x[9] ^= R(x[5] + x[1], 7) - x[13] ^= R(x[9] + x[5], 9) - x[1] ^= R(x[13] + x[9], 13) - x[5] ^= R(x[1] + x[13], 18) - x[14] ^= R(x[10] + x[6], 7) - x[2] ^= R(x[14] + x[10], 9) - x[6] ^= R(x[2] + x[14], 13) - x[10] ^= R(x[6] + x[2], 18) - x[3] ^= R(x[15] + x[11], 7) - x[7] ^= R(x[3] + x[15], 9) - x[11] ^= R(x[7] + x[3], 13) - x[15] ^= R(x[11] + x[7], 18) - x[1] ^= R(x[0] + x[3], 7) - x[2] ^= R(x[1] + x[0], 9) - x[3] ^= R(x[2] + x[1], 13) - x[0] ^= R(x[3] + x[2], 18) - x[6] ^= R(x[5] + x[4], 7) - x[7] ^= R(x[6] + x[5], 9) - x[4] ^= R(x[7] + x[6], 13) - x[5] ^= R(x[4] + x[7], 18) - x[11] ^= R(x[10] + x[9], 7) - x[8] ^= R(x[11] + x[10], 9) - x[9] ^= R(x[8] + x[11], 13) - x[10] ^= R(x[9] + x[8], 18) - x[12] ^= R(x[15] + x[14], 7) - x[13] ^= R(x[12] + x[15], 9) - x[14] ^= R(x[13] + x[12], 13) - x[15] ^= R(x[14] + x[13], 18) - } - - for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i] - - for (i = 0; i < 16; i++) { - let bi = i * 4 - B[bi + 0] = (B32[i] >> 0 & 0xff) - B[bi + 1] = (B32[i] >> 8 & 0xff) - B[bi + 2] = (B32[i] >> 16 & 0xff) - B[bi + 3] = (B32[i] >> 24 & 0xff) - // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js - } -} - -// naive approach... going back to loop unrolling may yield additional performance -function blockxor (S, Si, D, Di, len) { - for (let i = 0; i < len; i++) { - D[Di + i] ^= S[Si + i] - } -} - -function arraycopy (src, srcPos, dest, destPos, length) { - if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { - src.copy(dest, destPos, srcPos, srcPos + length) - } else { - while (length--) { - dest[destPos++] = src[srcPos++] - } - } -} - -module.exports = { - checkAndInit, - smix, - smixSync -} - -}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"buffer":217,"crypto":236,"timers":1749}],1600:[function(require,module,exports){ -'use strict' -module.exports = require('./lib')(require('./lib/elliptic')) - -},{"./lib":1605,"./lib/elliptic":1604}],1601:[function(require,module,exports){ -'use strict' -module.exports = require('./lib')(require('./lib/js')) - -},{"./lib":1605,"./lib/js":1611}],1602:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var toString = Object.prototype.toString - -// TypeError -exports.isArray = function (value, message) { - if (!Array.isArray(value)) throw TypeError(message) -} - -exports.isBoolean = function (value, message) { - if (toString.call(value) !== '[object Boolean]') throw TypeError(message) -} - -exports.isBuffer = function (value, message) { - if (!Buffer.isBuffer(value)) throw TypeError(message) -} - -exports.isFunction = function (value, message) { - if (toString.call(value) !== '[object Function]') throw TypeError(message) -} - -exports.isNumber = function (value, message) { - if (toString.call(value) !== '[object Number]') throw TypeError(message) -} - -exports.isObject = function (value, message) { - if (toString.call(value) !== '[object Object]') throw TypeError(message) -} - -// RangeError -exports.isBufferLength = function (buffer, length, message) { - if (buffer.length !== length) throw RangeError(message) -} - -exports.isBufferLength2 = function (buffer, length1, length2, message) { - if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message) -} - -exports.isLengthGTZero = function (value, message) { - if (value.length === 0) throw RangeError(message) -} - -exports.isNumberInInterval = function (number, x, y, message) { - if (number <= x || number >= y) throw RangeError(message) -} - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766}],1603:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var bip66 = require('bip66') - -var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([ - // begin - 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20, - // private key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // middle - 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, - 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, - 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, - 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, - 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, - 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, - // public key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00 -]) - -var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ - // begin - 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, - // private key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // middle - 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, - 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, - 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, - 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, - 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, - 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, - 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, - 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, - // public key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00 -]) - -exports.privateKeyExport = function (privateKey, publicKey, compressed) { - var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED) - privateKey.copy(result, compressed ? 8 : 9) - publicKey.copy(result, compressed ? 181 : 214) - return result -} - -exports.privateKeyImport = function (privateKey) { - var length = privateKey.length - - // sequence header - var index = 0 - if (length < index + 1 || privateKey[index] !== 0x30) return - index += 1 - - // sequence length constructor - if (length < index + 1 || !(privateKey[index] & 0x80)) return - - var lenb = privateKey[index] & 0x7f - index += 1 - if (lenb < 1 || lenb > 2) return - if (length < index + lenb) return - - // sequence length - var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) - index += lenb - if (length < index + len) return - - // sequence element 0: version number (=1) - if (length < index + 3 || - privateKey[index] !== 0x02 || - privateKey[index + 1] !== 0x01 || - privateKey[index + 2] !== 0x01) { - return - } - index += 3 - - // sequence element 1: octet string, up to 32 bytes - if (length < index + 2 || - privateKey[index] !== 0x04 || - privateKey[index + 1] > 0x20 || - length < index + 2 + privateKey[index + 1]) { - return - } - - return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) -} - -exports.signatureExport = function (sigObj) { - var r = Buffer.concat([Buffer.from([0]), sigObj.r]) - for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR); - - var s = Buffer.concat([Buffer.from([0]), sigObj.s]) - for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); - - return bip66.encode(r.slice(posR), s.slice(posS)) -} - -exports.signatureImport = function (sig) { - var r = Buffer.alloc(32, 0) - var s = Buffer.alloc(32, 0) - - try { - var sigObj = bip66.decode(sig) - if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) - if (sigObj.r.length > 32) throw new Error('R length is too long') - if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) - if (sigObj.s.length > 32) throw new Error('S length is too long') - } catch (err) { - return - } - - sigObj.r.copy(r, 32 - sigObj.r.length) - sigObj.s.copy(s, 32 - sigObj.s.length) - - return { r: r, s: s } -} - -exports.signatureImportLax = function (sig) { - var r = Buffer.alloc(32, 0) - var s = Buffer.alloc(32, 0) - - var length = sig.length - var index = 0 - - // sequence tag byte - if (sig[index++] !== 0x30) return - - // sequence length byte - var lenbyte = sig[index++] - if (lenbyte & 0x80) { - index += lenbyte - 0x80 - if (index > length) return - } - - // sequence tag byte for r - if (sig[index++] !== 0x02) return - - // length for r - var rlen = sig[index++] - if (rlen & 0x80) { - lenbyte = rlen - 0x80 - if (index + lenbyte > length) return - for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); - for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] - } - if (rlen > length - index) return - var rindex = index - index += rlen - - // sequence tag byte for s - if (sig[index++] !== 0x02) return - - // length for s - var slen = sig[index++] - if (slen & 0x80) { - lenbyte = slen - 0x80 - if (index + lenbyte > length) return - for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); - for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] - } - if (slen > length - index) return - var sindex = index - index += slen - - // ignore leading zeros in r - for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); - // copy r value - if (rlen > 32) return - var rvalue = sig.slice(rindex, rindex + rlen) - rvalue.copy(r, 32 - rvalue.length) - - // ignore leading zeros in s - for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); - // copy s value - if (slen > 32) return - var svalue = sig.slice(sindex, sindex + slen) - svalue.copy(s, 32 - svalue.length) - - return { r: r, s: s } -} - -},{"bip66":165,"safe-buffer":1593}],1604:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var createHash = require('create-hash') -var BN = require('bn.js') -var EC = require('elliptic').ec - -var messages = require('../messages.json') - -var ec = new EC('secp256k1') -var ecparams = ec.curve - -function loadCompressedPublicKey (first, xBuffer) { - var x = new BN(xBuffer) - - // overflow - if (x.cmp(ecparams.p) >= 0) return null - x = x.toRed(ecparams.red) - - // compute corresponding Y - var y = x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt() - if ((first === 0x03) !== y.isOdd()) y = y.redNeg() - - return ec.keyPair({ pub: { x: x, y: y } }) -} - -function loadUncompressedPublicKey (first, xBuffer, yBuffer) { - var x = new BN(xBuffer) - var y = new BN(yBuffer) - - // overflow - if (x.cmp(ecparams.p) >= 0 || y.cmp(ecparams.p) >= 0) return null - - x = x.toRed(ecparams.red) - y = y.toRed(ecparams.red) - - // is odd flag - if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null - - // x*x*x + b = y*y - var x3 = x.redSqr().redIMul(x) - if (!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()) return null - - return ec.keyPair({ pub: { x: x, y: y } }) -} - -function loadPublicKey (publicKey) { - var first = publicKey[0] - switch (first) { - case 0x02: - case 0x03: - if (publicKey.length !== 33) return null - return loadCompressedPublicKey(first, publicKey.slice(1, 33)) - case 0x04: - case 0x06: - case 0x07: - if (publicKey.length !== 65) return null - return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65)) - default: - return null - } -} - -exports.privateKeyVerify = function (privateKey) { - var bn = new BN(privateKey) - return bn.cmp(ecparams.n) < 0 && !bn.isZero() -} - -exports.privateKeyExport = function (privateKey, compressed) { - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) - - return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) -} - -exports.privateKeyNegate = function (privateKey) { - var bn = new BN(privateKey) - return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyModInverse = function (privateKey) { - var bn = new BN(privateKey) - if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) - - return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyTweakAdd = function (privateKey, tweak) { - var bn = new BN(tweak) - if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - bn.iadd(new BN(privateKey)) - if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n) - if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - return bn.toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyTweakMul = function (privateKey, tweak) { - var bn = new BN(tweak) - if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) - - bn.imul(new BN(privateKey)) - if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n) - - return bn.toArrayLike(Buffer, 'be', 32) -} - -exports.publicKeyCreate = function (privateKey, compressed) { - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) - - return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) -} - -exports.publicKeyConvert = function (publicKey, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - return Buffer.from(pair.getPublic(compressed, true)) -} - -exports.publicKeyVerify = function (publicKey) { - return loadPublicKey(publicKey) !== null -} - -exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = new BN(tweak) - if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - var point = ecparams.g.mul(tweak).add(pair.pub) - if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - return Buffer.from(point.encode(true, compressed)) -} - -exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = new BN(tweak) - if (tweak.cmp(ecparams.n) >= 0 || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL) - - return Buffer.from(pair.pub.mul(tweak).encode(true, compressed)) -} - -exports.publicKeyCombine = function (publicKeys, compressed) { - var pairs = new Array(publicKeys.length) - for (var i = 0; i < publicKeys.length; ++i) { - pairs[i] = loadPublicKey(publicKeys[i]) - if (pairs[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - } - - var point = pairs[0].pub - for (var j = 1; j < pairs.length; ++j) point = point.add(pairs[j].pub) - if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL) - - return Buffer.from(point.encode(true, compressed)) -} - -exports.signatureNormalize = function (signature) { - var r = new BN(signature.slice(0, 32)) - var s = new BN(signature.slice(32, 64)) - if (r.cmp(ecparams.n) >= 0 || s.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - var result = Buffer.from(signature) - if (s.cmp(ec.nh) === 1) ecparams.n.sub(s).toArrayLike(Buffer, 'be', 32).copy(result, 32) - - return result -} - -exports.signatureExport = function (signature) { - var r = signature.slice(0, 32) - var s = signature.slice(32, 64) - if (new BN(r).cmp(ecparams.n) >= 0 || new BN(s).cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - return { r: r, s: s } -} - -exports.signatureImport = function (sigObj) { - var r = new BN(sigObj.r) - if (r.cmp(ecparams.n) >= 0) r = new BN(0) - - var s = new BN(sigObj.s) - if (s.cmp(ecparams.n) >= 0) s = new BN(0) - - return Buffer.concat([ - r.toArrayLike(Buffer, 'be', 32), - s.toArrayLike(Buffer, 'be', 32) - ]) -} - -exports.sign = function (message, privateKey, noncefn, data) { - if (typeof noncefn === 'function') { - var getNonce = noncefn - noncefn = function (counter) { - var nonce = getNonce(message, privateKey, null, data, counter) - if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL) - - return new BN(nonce) - } - } - - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL) - - var result = ec.sign(message, privateKey, { canonical: true, k: noncefn, pers: data }) - return { - signature: Buffer.concat([ - result.r.toArrayLike(Buffer, 'be', 32), - result.s.toArrayLike(Buffer, 'be', 32) - ]), - recovery: result.recoveryParam - } -} - -exports.verify = function (message, signature, publicKey) { - var sigObj = { r: signature.slice(0, 32), s: signature.slice(32, 64) } - - var sigr = new BN(sigObj.r) - var sigs = new BN(sigObj.s) - if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false - - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - return ec.verify(message, sigObj, { x: pair.pub.x, y: pair.pub.y }) -} - -exports.recover = function (message, signature, recovery, compressed) { - var sigObj = { r: signature.slice(0, 32), s: signature.slice(32, 64) } - - var sigr = new BN(sigObj.r) - var sigs = new BN(sigObj.s) - if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - try { - if (sigr.isZero() || sigs.isZero()) throw new Error() - - var point = ec.recoverPubKey(message, sigObj, recovery) - return Buffer.from(point.encode(true, compressed)) - } catch (err) { - throw new Error(messages.ECDSA_RECOVER_FAIL) - } -} - -exports.ecdh = function (publicKey, privateKey) { - var shared = exports.ecdhUnsafe(publicKey, privateKey, true) - return createHash('sha256').update(shared).digest() -} - -exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - var scalar = new BN(privateKey) - if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL) - - return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) -} - -},{"../messages.json":1612,"bn.js":171,"create-hash":232,"elliptic":282,"safe-buffer":1593}],1605:[function(require,module,exports){ -'use strict' -var assert = require('./assert') -var der = require('./der') -var messages = require('./messages.json') - -function initCompressedValue (value, defaultValue) { - if (value === undefined) return defaultValue - - assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID) - return value -} - -module.exports = function (secp256k1) { - return { - privateKeyVerify: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey) - }, - - privateKeyExport: function (privateKey, compressed) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - var publicKey = secp256k1.privateKeyExport(privateKey, compressed) - - return der.privateKeyExport(privateKey, publicKey, compressed) - }, - - privateKeyImport: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - - privateKey = der.privateKeyImport(privateKey) - if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey - - throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL) - }, - - privateKeyNegate: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.privateKeyNegate(privateKey) - }, - - privateKeyModInverse: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.privateKeyModInverse(privateKey) - }, - - privateKeyTweakAdd: function (privateKey, tweak) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - return secp256k1.privateKeyTweakAdd(privateKey, tweak) - }, - - privateKeyTweakMul: function (privateKey, tweak) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - return secp256k1.privateKeyTweakMul(privateKey, tweak) - }, - - publicKeyCreate: function (privateKey, compressed) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyCreate(privateKey, compressed) - }, - - publicKeyConvert: function (publicKey, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyConvert(publicKey, compressed) - }, - - publicKeyVerify: function (publicKey) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - return secp256k1.publicKeyVerify(publicKey) - }, - - publicKeyTweakAdd: function (publicKey, tweak, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed) - }, - - publicKeyTweakMul: function (publicKey, tweak, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed) - }, - - publicKeyCombine: function (publicKeys, compressed) { - assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID) - assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID) - for (var i = 0; i < publicKeys.length; ++i) { - assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - } - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyCombine(publicKeys, compressed) - }, - - signatureNormalize: function (signature) { - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - return secp256k1.signatureNormalize(signature) - }, - - signatureExport: function (signature) { - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = secp256k1.signatureExport(signature) - return der.signatureExport(sigObj) - }, - - signatureImport: function (sig) { - assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = der.signatureImport(sig) - if (sigObj) return secp256k1.signatureImport(sigObj) - - throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) - }, - - signatureImportLax: function (sig) { - assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = der.signatureImportLax(sig) - if (sigObj) return secp256k1.signatureImport(sigObj) - - throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) - }, - - sign: function (message, privateKey, options) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - var data = null - var noncefn = null - if (options !== undefined) { - assert.isObject(options, messages.OPTIONS_TYPE_INVALID) - - if (options.data !== undefined) { - assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) - assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) - data = options.data - } - - if (options.noncefn !== undefined) { - assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) - noncefn = options.noncefn - } - } - - return secp256k1.sign(message, privateKey, noncefn, data) - }, - - verify: function (message, signature, publicKey) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - return secp256k1.verify(message, signature, publicKey) - }, - - recover: function (message, signature, recovery, compressed) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) - assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.recover(message, signature, recovery, compressed) - }, - - ecdh: function (publicKey, privateKey) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.ecdh(publicKey, privateKey) - }, - - ecdhUnsafe: function (publicKey, privateKey, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) - } - } -} - -},{"./assert":1602,"./der":1603,"./messages.json":1612}],1606:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var optimized = require('./optimized') - -function BN () { - this.negative = 0 - this.words = null - this.length = 0 -} - -BN.fromNumber = function (n) { - var bn = new BN() - bn.words = [n & 0x03ffffff] - bn.length = 1 - return bn -} - -BN.fromBuffer = function (b32) { - var bn = new BN() - - bn.words = new Array(10) - bn.words[0] = (b32[28] & 0x03) << 24 | b32[29] << 16 | b32[30] << 8 | b32[31] - bn.words[1] = (b32[25] & 0x0F) << 22 | b32[26] << 14 | b32[27] << 6 | b32[28] >>> 2 - bn.words[2] = (b32[22] & 0x3F) << 20 | b32[23] << 12 | b32[24] << 4 | b32[25] >>> 4 - bn.words[3] = (b32[19] & 0xFF) << 18 | b32[20] << 10 | b32[21] << 2 | b32[22] >>> 6 - - bn.words[4] = (b32[15] & 0x03) << 24 | b32[16] << 16 | b32[17] << 8 | b32[18] - bn.words[5] = (b32[12] & 0x0F) << 22 | b32[13] << 14 | b32[14] << 6 | b32[15] >>> 2 - bn.words[6] = (b32[9] & 0x3F) << 20 | b32[10] << 12 | b32[11] << 4 | b32[12] >>> 4 - bn.words[7] = (b32[6] & 0xFF) << 18 | b32[7] << 10 | b32[8] << 2 | b32[9] >>> 6 - - bn.words[8] = (b32[2] & 0x03) << 24 | b32[3] << 16 | b32[4] << 8 | b32[5] - bn.words[9] = b32[0] << 14 | b32[1] << 6 | b32[2] >>> 2 - - bn.length = 10 - return bn.strip() -} - -BN.prototype.toBuffer = function () { - var w = this.words - for (var i = this.length; i < 10; ++i) w[i] = 0 - - return Buffer.from([ - (w[9] >>> 14) & 0xFF, (w[9] >>> 6) & 0xFF, (w[9] & 0x3F) << 2 | ((w[8] >>> 24) & 0x03), // 0, 1, 2 - (w[8] >>> 16) & 0xFF, (w[8] >>> 8) & 0xFF, w[8] & 0xFF, // 3, 4, 5 - - (w[7] >>> 18) & 0xFF, (w[7] >>> 10) & 0xFF, (w[7] >>> 2) & 0xFF, // 6, 7, 8 - ((w[7] & 0x03) << 6) | ((w[6] >>> 20) & 0x3F), (w[6] >>> 12) & 0xFF, (w[6] >>> 4) & 0xFF, // 9, 10, 11 - ((w[6] & 0x0F) << 4) | ((w[5] >>> 22) & 0x0F), (w[5] >>> 14) & 0xFF, (w[5] >>> 6) & 0xFF, // 12, 13, 14 - ((w[5] & 0x3F) << 2) | ((w[4] >>> 24) & 0x03), (w[4] >>> 16) & 0xFF, (w[4] >>> 8) & 0xFF, w[4] & 0xFF, // 15, 16, 17, 18 - - (w[3] >>> 18) & 0xFF, (w[3] >>> 10) & 0xFF, (w[3] >>> 2) & 0xFF, // 19, 20, 21 - ((w[3] & 0x03) << 6) | ((w[2] >>> 20) & 0x3F), (w[2] >>> 12) & 0xFF, (w[2] >>> 4) & 0xFF, // 22, 23, 24 - ((w[2] & 0x0F) << 4) | ((w[1] >>> 22) & 0x0F), (w[1] >>> 14) & 0xFF, (w[1] >>> 6) & 0xFF, // 25, 26, 27 - ((w[1] & 0x3F) << 2) | ((w[0] >>> 24) & 0x03), (w[0] >>> 16) & 0xFF, (w[0] >>> 8) & 0xFF, w[0] & 0xFF // 28, 29, 30, 31 - ]) -} - -BN.prototype.clone = function () { - var r = new BN() - r.words = new Array(this.length) - for (var i = 0; i < this.length; i++) r.words[i] = this.words[i] - r.length = this.length - r.negative = this.negative - return r -} - -BN.prototype.strip = function () { - while (this.length > 1 && (this.words[this.length - 1] | 0) === 0) this.length-- - return this -} - -BN.prototype.normSign = function () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) this.negative = 0 - return this -} - -BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0 -} - -BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1 -} - -BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0 -} - -BN.prototype.ucmp = function (num) { - if (this.length !== num.length) return this.length > num.length ? 1 : -1 - - for (var i = this.length - 1; i >= 0; --i) { - if (this.words[i] !== num.words[i]) return this.words[i] > num.words[i] ? 1 : -1 - } - - return 0 -} - -BN.prototype.gtOne = function () { - return this.length > 1 || this.words[0] > 1 -} - -BN.prototype.isOverflow = function () { - return this.ucmp(BN.n) >= 0 -} - -BN.prototype.isHigh = function () { - return this.ucmp(BN.nh) === 1 -} - -BN.prototype.bitLengthGT256 = function () { - return this.length > 10 || (this.length === 10 && this.words[9] > 0x003fffff) -} - -BN.prototype.iuaddn = function (num) { - this.words[0] += num - - for (var i = 0; this.words[i] > 0x03ffffff && i < this.length; ++i) { - this.words[i] -= 0x04000000 - this.words[i + 1] += 1 - } - - if (i === this.length) { - this.words[i] = 1 - this.length += 1 - } - - return this -} - -BN.prototype.iadd = function (num) { - // (-this) + num -> -(this - num) - // this + (-num) -> this - num - if (this.negative !== num.negative) { - if (this.negative !== 0) { - this.negative = 0 - this.isub(num) - this.negative ^= 1 - } else { - num.negative = 0 - this.isub(num) - num.negative = 1 - } - - return this.normSign() - } - - // a.length > b.length - var a - var b - if (this.length > num.length) { - a = this - b = num - } else { - a = num - b = this - } - - for (var i = 0, carry = 0; i < b.length; ++i) { - var word = a.words[i] + b.words[i] + carry - this.words[i] = word & 0x03ffffff - carry = word >>> 26 - } - - for (; carry !== 0 && i < a.length; ++i) { - word = a.words[i] + carry - this.words[i] = word & 0x03ffffff - carry = word >>> 26 - } - - this.length = a.length - if (carry !== 0) { - this.words[this.length++] = carry - } else if (a !== this) { - for (; i < a.length; ++i) { - this.words[i] = a.words[i] - } - } - - return this -} - -BN.prototype.add = function (num) { - return this.clone().iadd(num) -} - -BN.prototype.isub = function (num) { - // (-this) - num -> -(this + num) - // this - (-num) -> this + num - if (this.negative !== num.negative) { - if (this.negative !== 0) { - this.negative = 0 - this.iadd(num) - this.negative = 1 - } else { - num.negative = 0 - this.iadd(num) - num.negative = 1 - } - - return this.normSign() - } - - var cmp = this.ucmp(num) - if (cmp === 0) { - this.negative = 0 - this.words[0] = 0 - this.length = 1 - return this - } - - // a > b - var a - var b - if (cmp > 0) { - a = this - b = num - } else { - a = num - b = this - } - - for (var i = 0, carry = 0; i < b.length; ++i) { - var word = a.words[i] - b.words[i] + carry - carry = word >> 26 - this.words[i] = word & 0x03ffffff - } - - for (; carry !== 0 && i < a.length; ++i) { - word = a.words[i] + carry - carry = word >> 26 - this.words[i] = word & 0x03ffffff - } - - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; ++i) this.words[i] = a.words[i] - } - - this.length = Math.max(this.length, i) - - if (a !== this) this.negative ^= 1 - - return this.strip().normSign() -} - -BN.prototype.sub = function (num) { - return this.clone().isub(num) -} - -BN.umulTo = function (num1, num2, out) { - out.length = num1.length + num2.length - 1 - - var a1 = num1.words[0] - var b1 = num2.words[0] - var r1 = a1 * b1 - - var carry = (r1 / 0x04000000) | 0 - out.words[0] = r1 & 0x03ffffff - - for (var k = 1, maxK = out.length; k < maxK; k++) { - var ncarry = carry >>> 26 - var rword = carry & 0x03ffffff - for (var j = Math.max(0, k - num1.length + 1), maxJ = Math.min(k, num2.length - 1); j <= maxJ; j++) { - var i = k - j - var a = num1.words[i] - var b = num2.words[j] - var r = a * b + rword - ncarry += (r / 0x04000000) | 0 - rword = r & 0x03ffffff - } - out.words[k] = rword - carry = ncarry - } - - if (carry !== 0) out.words[out.length++] = carry - - return out.strip() -} - -BN.umulTo10x10 = Math.imul ? optimized.umulTo10x10 : BN.umulTo - -BN.umulnTo = function (num, k, out) { - if (k === 0) { - out.words = [0] - out.length = 1 - return out - } - - for (var i = 0, carry = 0; i < num.length; ++i) { - var r = num.words[i] * k + carry - out.words[i] = r & 0x03ffffff - carry = (r / 0x04000000) | 0 - } - - if (carry > 0) { - out.words[i] = carry - out.length = num.length + 1 - } else { - out.length = num.length - } - - return out -} - -BN.prototype.umul = function (num) { - var out = new BN() - out.words = new Array(this.length + num.length) - - if (this.length === 10 && num.length === 10) { - return BN.umulTo10x10(this, num, out) - } else if (this.length === 1) { - return BN.umulnTo(num, this.words[0], out) - } else if (num.length === 1) { - return BN.umulnTo(this, num.words[0], out) - } else { - return BN.umulTo(this, num, out) - } -} - -BN.prototype.isplit = function (output) { - output.length = Math.min(this.length, 9) - for (var i = 0; i < output.length; ++i) output.words[i] = this.words[i] - - if (this.length <= 9) { - this.words[0] = 0 - this.length = 1 - return this - } - - // Shift by 9 limbs - var prev = this.words[9] - output.words[output.length++] = prev & 0x003fffff - - for (i = 10; i < this.length; ++i) { - var word = this.words[i] - this.words[i - 10] = ((word & 0x003fffff) << 4) | (prev >>> 22) - prev = word - } - prev >>>= 22 - this.words[i - 10] = prev - - if (prev === 0 && this.length > 10) { - this.length -= 10 - } else { - this.length -= 9 - } - - return this -} - -BN.prototype.fireduce = function () { - if (this.isOverflow()) this.isub(BN.n) - return this -} - -BN.prototype.ureduce = function () { - var num = this.clone().isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) - if (num.bitLengthGT256()) { - num = num.isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) - if (num.bitLengthGT256()) num = num.isplit(BN.tmp).umul(BN.nc).iadd(BN.tmp) - } - - return num.fireduce() -} - -BN.prototype.ishrn = function (n) { - var mask = (1 << n) - 1 - var m = 26 - n - - for (var i = this.length - 1, carry = 0; i >= 0; --i) { - var word = this.words[i] - this.words[i] = (carry << m) | (word >>> n) - carry = word & mask - } - - if (this.length > 1 && this.words[this.length - 1] === 0) this.length -= 1 - - return this -} - -BN.prototype.uinvm = function () { - var x = this.clone() - var y = BN.n.clone() - - // A * x + B * y = x - var A = BN.fromNumber(1) - var B = BN.fromNumber(0) - - // C * x + D * y = y - var C = BN.fromNumber(0) - var D = BN.fromNumber(1) - - while (x.isEven() && y.isEven()) { - for (var k = 1, m = 1; (x.words[0] & m) === 0 && (y.words[0] & m) === 0 && k < 26; ++k, m <<= 1); - x.ishrn(k) - y.ishrn(k) - } - - var yp = y.clone() - var xp = x.clone() - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.ishrn(i) - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp) - B.isub(xp) - } - - A.ishrn(1) - B.ishrn(1) - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.ishrn(j) - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp) - D.isub(xp) - } - - C.ishrn(1) - D.ishrn(1) - } - } - - if (x.ucmp(y) >= 0) { - x.isub(y) - A.isub(C) - B.isub(D) - } else { - y.isub(x) - C.isub(A) - D.isub(B) - } - } - - if (C.negative === 1) { - C.negative = 0 - var result = C.ureduce() - result.negative ^= 1 - return result.normSign().iadd(BN.n) - } else { - return C.ureduce() - } -} - -BN.prototype.imulK = function () { - this.words[this.length] = 0 - this.words[this.length + 1] = 0 - this.length += 2 - - for (var i = 0, lo = 0; i < this.length; ++i) { - var w = this.words[i] | 0 - lo += w * 0x3d1 - this.words[i] = lo & 0x03ffffff - lo = w * 0x40 + ((lo / 0x04000000) | 0) - } - - if (this.words[this.length - 1] === 0) { - this.length -= 1 - if (this.words[this.length - 1] === 0) this.length -= 1 - } - - return this -} - -BN.prototype.redIReduce = function () { - this.isplit(BN.tmp).imulK().iadd(BN.tmp) - if (this.bitLengthGT256()) this.isplit(BN.tmp).imulK().iadd(BN.tmp) - - var cmp = this.ucmp(BN.p) - if (cmp === 0) { - this.words[0] = 0 - this.length = 1 - } else if (cmp > 0) { - this.isub(BN.p) - } else { - this.strip() - } - - return this -} - -BN.prototype.redNeg = function () { - if (this.isZero()) return BN.fromNumber(0) - - return BN.p.sub(this) -} - -BN.prototype.redAdd = function (num) { - return this.clone().redIAdd(num) -} - -BN.prototype.redIAdd = function (num) { - this.iadd(num) - if (this.ucmp(BN.p) >= 0) this.isub(BN.p) - - return this -} - -BN.prototype.redIAdd7 = function () { - this.iuaddn(7) - if (this.ucmp(BN.p) >= 0) this.isub(BN.p) - - return this -} - -BN.prototype.redSub = function (num) { - return this.clone().redISub(num) -} - -BN.prototype.redISub = function (num) { - this.isub(num) - if (this.negative !== 0) this.iadd(BN.p) - - return this -} - -BN.prototype.redMul = function (num) { - return this.umul(num).redIReduce() -} - -BN.prototype.redSqr = function () { - return this.umul(this).redIReduce() -} - -BN.prototype.redSqrt = function () { - if (this.isZero()) return this.clone() - - var wv2 = this.redSqr() - var wv4 = wv2.redSqr() - var wv12 = wv4.redSqr().redMul(wv4) - var wv14 = wv12.redMul(wv2) - var wv15 = wv14.redMul(this) - - var out = wv15 - for (var i = 0; i < 54; ++i) out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv15) - out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv14) - for (i = 0; i < 5; ++i) out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv15) - out = out.redSqr().redSqr().redSqr().redSqr().redMul(wv12) - out = out.redSqr().redSqr().redSqr().redSqr().redSqr().redSqr().redMul(wv12) - - if (out.redSqr().ucmp(this) === 0) { - return out - } else { - return null - } -} - -BN.prototype.redInvm = function () { - var a = this.clone() - var b = BN.p.clone() - - var x1 = BN.fromNumber(1) - var x2 = BN.fromNumber(0) - - while (a.gtOne() && b.gtOne()) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.ishrn(i) - while (i-- > 0) { - if (x1.isOdd()) x1.iadd(BN.p) - x1.ishrn(1) - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.ishrn(j) - while (j-- > 0) { - if (x2.isOdd()) x2.iadd(BN.p) - x2.ishrn(1) - } - } - - if (a.ucmp(b) >= 0) { - a.isub(b) - x1.isub(x2) - } else { - b.isub(a) - x2.isub(x1) - } - } - - var res - if (a.length === 1 && a.words[0] === 1) { - res = x1 - } else { - res = x2 - } - - if (res.negative !== 0) res.iadd(BN.p) - - if (res.negative !== 0) { - res.negative = 0 - return res.redIReduce().redNeg() - } else { - return res.redIReduce() - } -} - -BN.prototype.getNAF = function (w) { - var naf = [] - var ws = 1 << (w + 1) - var wsm1 = ws - 1 - var ws2 = ws >> 1 - - var k = this.clone() - while (!k.isZero()) { - for (var i = 0, m = 1; (k.words[0] & m) === 0 && i < 26; ++i, m <<= 1) naf.push(0) - - if (i !== 0) { - k.ishrn(i) - } else { - var mod = k.words[0] & wsm1 - if (mod >= ws2) { - naf.push(ws2 - mod) - k.iuaddn(mod - ws2).ishrn(1) - } else { - naf.push(mod) - k.words[0] -= mod - if (!k.isZero()) { - for (i = w - 1; i > 0; --i) naf.push(0) - k.ishrn(w) - } - } - } - } - - return naf -} - -BN.prototype.inspect = function () { - if (this.isZero()) return '0' - - var buffer = this.toBuffer().toString('hex') - for (var i = 0; buffer[i] === '0'; ++i); - return buffer.slice(i) -} - -BN.n = BN.fromBuffer(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', 'hex')) -BN.nh = BN.n.clone().ishrn(1) -BN.nc = BN.fromBuffer(Buffer.from('000000000000000000000000000000014551231950B75FC4402DA1732FC9BEBF', 'hex')) -BN.p = BN.fromBuffer(Buffer.from('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F', 'hex')) -BN.psn = BN.p.sub(BN.n) -BN.tmp = new BN() -BN.tmp.words = new Array(10) - -// WTF?! it speed-up benchmark on ~20% -;(function () { - var x = BN.fromNumber(1) - x.words[3] = 0 -})() - -module.exports = BN - -},{"./optimized":1607,"safe-buffer":1593}],1607:[function(require,module,exports){ -'use strict' -exports.umulTo10x10 = function (num1, num2, out) { - var a = num1.words - var b = num2.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.length = 19 - /* k = 0 */ - lo = Math.imul(al0, bl0) - mid = Math.imul(al0, bh0) - mid += Math.imul(ah0, bl0) - hi = Math.imul(ah0, bh0) - var w0 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w0 >>> 26) - w0 &= 0x3ffffff - /* k = 1 */ - lo = Math.imul(al1, bl0) - mid = Math.imul(al1, bh0) - mid += Math.imul(ah1, bl0) - hi = Math.imul(ah1, bh0) - lo += Math.imul(al0, bl1) - mid += Math.imul(al0, bh1) - mid += Math.imul(ah0, bl1) - hi += Math.imul(ah0, bh1) - var w1 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w1 >>> 26) - w1 &= 0x3ffffff - /* k = 2 */ - lo = Math.imul(al2, bl0) - mid = Math.imul(al2, bh0) - mid += Math.imul(ah2, bl0) - hi = Math.imul(ah2, bh0) - lo += Math.imul(al1, bl1) - mid += Math.imul(al1, bh1) - mid += Math.imul(ah1, bl1) - hi += Math.imul(ah1, bh1) - lo += Math.imul(al0, bl2) - mid += Math.imul(al0, bh2) - mid += Math.imul(ah0, bl2) - hi += Math.imul(ah0, bh2) - var w2 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w2 >>> 26) - w2 &= 0x3ffffff - /* k = 3 */ - lo = Math.imul(al3, bl0) - mid = Math.imul(al3, bh0) - mid += Math.imul(ah3, bl0) - hi = Math.imul(ah3, bh0) - lo += Math.imul(al2, bl1) - mid += Math.imul(al2, bh1) - mid += Math.imul(ah2, bl1) - hi += Math.imul(ah2, bh1) - lo += Math.imul(al1, bl2) - mid += Math.imul(al1, bh2) - mid += Math.imul(ah1, bl2) - hi += Math.imul(ah1, bh2) - lo += Math.imul(al0, bl3) - mid += Math.imul(al0, bh3) - mid += Math.imul(ah0, bl3) - hi += Math.imul(ah0, bh3) - var w3 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w3 >>> 26) - w3 &= 0x3ffffff - /* k = 4 */ - lo = Math.imul(al4, bl0) - mid = Math.imul(al4, bh0) - mid += Math.imul(ah4, bl0) - hi = Math.imul(ah4, bh0) - lo += Math.imul(al3, bl1) - mid += Math.imul(al3, bh1) - mid += Math.imul(ah3, bl1) - hi += Math.imul(ah3, bh1) - lo += Math.imul(al2, bl2) - mid += Math.imul(al2, bh2) - mid += Math.imul(ah2, bl2) - hi += Math.imul(ah2, bh2) - lo += Math.imul(al1, bl3) - mid += Math.imul(al1, bh3) - mid += Math.imul(ah1, bl3) - hi += Math.imul(ah1, bh3) - lo += Math.imul(al0, bl4) - mid += Math.imul(al0, bh4) - mid += Math.imul(ah0, bl4) - hi += Math.imul(ah0, bh4) - var w4 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w4 >>> 26) - w4 &= 0x3ffffff - /* k = 5 */ - lo = Math.imul(al5, bl0) - mid = Math.imul(al5, bh0) - mid += Math.imul(ah5, bl0) - hi = Math.imul(ah5, bh0) - lo += Math.imul(al4, bl1) - mid += Math.imul(al4, bh1) - mid += Math.imul(ah4, bl1) - hi += Math.imul(ah4, bh1) - lo += Math.imul(al3, bl2) - mid += Math.imul(al3, bh2) - mid += Math.imul(ah3, bl2) - hi += Math.imul(ah3, bh2) - lo += Math.imul(al2, bl3) - mid += Math.imul(al2, bh3) - mid += Math.imul(ah2, bl3) - hi += Math.imul(ah2, bh3) - lo += Math.imul(al1, bl4) - mid += Math.imul(al1, bh4) - mid += Math.imul(ah1, bl4) - hi += Math.imul(ah1, bh4) - lo += Math.imul(al0, bl5) - mid += Math.imul(al0, bh5) - mid += Math.imul(ah0, bl5) - hi += Math.imul(ah0, bh5) - var w5 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w5 >>> 26) - w5 &= 0x3ffffff - /* k = 6 */ - lo = Math.imul(al6, bl0) - mid = Math.imul(al6, bh0) - mid += Math.imul(ah6, bl0) - hi = Math.imul(ah6, bh0) - lo += Math.imul(al5, bl1) - mid += Math.imul(al5, bh1) - mid += Math.imul(ah5, bl1) - hi += Math.imul(ah5, bh1) - lo += Math.imul(al4, bl2) - mid += Math.imul(al4, bh2) - mid += Math.imul(ah4, bl2) - hi += Math.imul(ah4, bh2) - lo += Math.imul(al3, bl3) - mid += Math.imul(al3, bh3) - mid += Math.imul(ah3, bl3) - hi += Math.imul(ah3, bh3) - lo += Math.imul(al2, bl4) - mid += Math.imul(al2, bh4) - mid += Math.imul(ah2, bl4) - hi += Math.imul(ah2, bh4) - lo += Math.imul(al1, bl5) - mid += Math.imul(al1, bh5) - mid += Math.imul(ah1, bl5) - hi += Math.imul(ah1, bh5) - lo += Math.imul(al0, bl6) - mid += Math.imul(al0, bh6) - mid += Math.imul(ah0, bl6) - hi += Math.imul(ah0, bh6) - var w6 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w6 >>> 26) - w6 &= 0x3ffffff - /* k = 7 */ - lo = Math.imul(al7, bl0) - mid = Math.imul(al7, bh0) - mid += Math.imul(ah7, bl0) - hi = Math.imul(ah7, bh0) - lo += Math.imul(al6, bl1) - mid += Math.imul(al6, bh1) - mid += Math.imul(ah6, bl1) - hi += Math.imul(ah6, bh1) - lo += Math.imul(al5, bl2) - mid += Math.imul(al5, bh2) - mid += Math.imul(ah5, bl2) - hi += Math.imul(ah5, bh2) - lo += Math.imul(al4, bl3) - mid += Math.imul(al4, bh3) - mid += Math.imul(ah4, bl3) - hi += Math.imul(ah4, bh3) - lo += Math.imul(al3, bl4) - mid += Math.imul(al3, bh4) - mid += Math.imul(ah3, bl4) - hi += Math.imul(ah3, bh4) - lo += Math.imul(al2, bl5) - mid += Math.imul(al2, bh5) - mid += Math.imul(ah2, bl5) - hi += Math.imul(ah2, bh5) - lo += Math.imul(al1, bl6) - mid += Math.imul(al1, bh6) - mid += Math.imul(ah1, bl6) - hi += Math.imul(ah1, bh6) - lo += Math.imul(al0, bl7) - mid += Math.imul(al0, bh7) - mid += Math.imul(ah0, bl7) - hi += Math.imul(ah0, bh7) - var w7 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w7 >>> 26) - w7 &= 0x3ffffff - /* k = 8 */ - lo = Math.imul(al8, bl0) - mid = Math.imul(al8, bh0) - mid += Math.imul(ah8, bl0) - hi = Math.imul(ah8, bh0) - lo += Math.imul(al7, bl1) - mid += Math.imul(al7, bh1) - mid += Math.imul(ah7, bl1) - hi += Math.imul(ah7, bh1) - lo += Math.imul(al6, bl2) - mid += Math.imul(al6, bh2) - mid += Math.imul(ah6, bl2) - hi += Math.imul(ah6, bh2) - lo += Math.imul(al5, bl3) - mid += Math.imul(al5, bh3) - mid += Math.imul(ah5, bl3) - hi += Math.imul(ah5, bh3) - lo += Math.imul(al4, bl4) - mid += Math.imul(al4, bh4) - mid += Math.imul(ah4, bl4) - hi += Math.imul(ah4, bh4) - lo += Math.imul(al3, bl5) - mid += Math.imul(al3, bh5) - mid += Math.imul(ah3, bl5) - hi += Math.imul(ah3, bh5) - lo += Math.imul(al2, bl6) - mid += Math.imul(al2, bh6) - mid += Math.imul(ah2, bl6) - hi += Math.imul(ah2, bh6) - lo += Math.imul(al1, bl7) - mid += Math.imul(al1, bh7) - mid += Math.imul(ah1, bl7) - hi += Math.imul(ah1, bh7) - lo += Math.imul(al0, bl8) - mid += Math.imul(al0, bh8) - mid += Math.imul(ah0, bl8) - hi += Math.imul(ah0, bh8) - var w8 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w8 >>> 26) - w8 &= 0x3ffffff - /* k = 9 */ - lo = Math.imul(al9, bl0) - mid = Math.imul(al9, bh0) - mid += Math.imul(ah9, bl0) - hi = Math.imul(ah9, bh0) - lo += Math.imul(al8, bl1) - mid += Math.imul(al8, bh1) - mid += Math.imul(ah8, bl1) - hi += Math.imul(ah8, bh1) - lo += Math.imul(al7, bl2) - mid += Math.imul(al7, bh2) - mid += Math.imul(ah7, bl2) - hi += Math.imul(ah7, bh2) - lo += Math.imul(al6, bl3) - mid += Math.imul(al6, bh3) - mid += Math.imul(ah6, bl3) - hi += Math.imul(ah6, bh3) - lo += Math.imul(al5, bl4) - mid += Math.imul(al5, bh4) - mid += Math.imul(ah5, bl4) - hi += Math.imul(ah5, bh4) - lo += Math.imul(al4, bl5) - mid += Math.imul(al4, bh5) - mid += Math.imul(ah4, bl5) - hi += Math.imul(ah4, bh5) - lo += Math.imul(al3, bl6) - mid += Math.imul(al3, bh6) - mid += Math.imul(ah3, bl6) - hi += Math.imul(ah3, bh6) - lo += Math.imul(al2, bl7) - mid += Math.imul(al2, bh7) - mid += Math.imul(ah2, bl7) - hi += Math.imul(ah2, bh7) - lo += Math.imul(al1, bl8) - mid += Math.imul(al1, bh8) - mid += Math.imul(ah1, bl8) - hi += Math.imul(ah1, bh8) - lo += Math.imul(al0, bl9) - mid += Math.imul(al0, bh9) - mid += Math.imul(ah0, bl9) - hi += Math.imul(ah0, bh9) - var w9 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w9 >>> 26) - w9 &= 0x3ffffff - /* k = 10 */ - lo = Math.imul(al9, bl1) - mid = Math.imul(al9, bh1) - mid += Math.imul(ah9, bl1) - hi = Math.imul(ah9, bh1) - lo += Math.imul(al8, bl2) - mid += Math.imul(al8, bh2) - mid += Math.imul(ah8, bl2) - hi += Math.imul(ah8, bh2) - lo += Math.imul(al7, bl3) - mid += Math.imul(al7, bh3) - mid += Math.imul(ah7, bl3) - hi += Math.imul(ah7, bh3) - lo += Math.imul(al6, bl4) - mid += Math.imul(al6, bh4) - mid += Math.imul(ah6, bl4) - hi += Math.imul(ah6, bh4) - lo += Math.imul(al5, bl5) - mid += Math.imul(al5, bh5) - mid += Math.imul(ah5, bl5) - hi += Math.imul(ah5, bh5) - lo += Math.imul(al4, bl6) - mid += Math.imul(al4, bh6) - mid += Math.imul(ah4, bl6) - hi += Math.imul(ah4, bh6) - lo += Math.imul(al3, bl7) - mid += Math.imul(al3, bh7) - mid += Math.imul(ah3, bl7) - hi += Math.imul(ah3, bh7) - lo += Math.imul(al2, bl8) - mid += Math.imul(al2, bh8) - mid += Math.imul(ah2, bl8) - hi += Math.imul(ah2, bh8) - lo += Math.imul(al1, bl9) - mid += Math.imul(al1, bh9) - mid += Math.imul(ah1, bl9) - hi += Math.imul(ah1, bh9) - var w10 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w10 >>> 26) - w10 &= 0x3ffffff - /* k = 11 */ - lo = Math.imul(al9, bl2) - mid = Math.imul(al9, bh2) - mid += Math.imul(ah9, bl2) - hi = Math.imul(ah9, bh2) - lo += Math.imul(al8, bl3) - mid += Math.imul(al8, bh3) - mid += Math.imul(ah8, bl3) - hi += Math.imul(ah8, bh3) - lo += Math.imul(al7, bl4) - mid += Math.imul(al7, bh4) - mid += Math.imul(ah7, bl4) - hi += Math.imul(ah7, bh4) - lo += Math.imul(al6, bl5) - mid += Math.imul(al6, bh5) - mid += Math.imul(ah6, bl5) - hi += Math.imul(ah6, bh5) - lo += Math.imul(al5, bl6) - mid += Math.imul(al5, bh6) - mid += Math.imul(ah5, bl6) - hi += Math.imul(ah5, bh6) - lo += Math.imul(al4, bl7) - mid += Math.imul(al4, bh7) - mid += Math.imul(ah4, bl7) - hi += Math.imul(ah4, bh7) - lo += Math.imul(al3, bl8) - mid += Math.imul(al3, bh8) - mid += Math.imul(ah3, bl8) - hi += Math.imul(ah3, bh8) - lo += Math.imul(al2, bl9) - mid += Math.imul(al2, bh9) - mid += Math.imul(ah2, bl9) - hi += Math.imul(ah2, bh9) - var w11 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w11 >>> 26) - w11 &= 0x3ffffff - /* k = 12 */ - lo = Math.imul(al9, bl3) - mid = Math.imul(al9, bh3) - mid += Math.imul(ah9, bl3) - hi = Math.imul(ah9, bh3) - lo += Math.imul(al8, bl4) - mid += Math.imul(al8, bh4) - mid += Math.imul(ah8, bl4) - hi += Math.imul(ah8, bh4) - lo += Math.imul(al7, bl5) - mid += Math.imul(al7, bh5) - mid += Math.imul(ah7, bl5) - hi += Math.imul(ah7, bh5) - lo += Math.imul(al6, bl6) - mid += Math.imul(al6, bh6) - mid += Math.imul(ah6, bl6) - hi += Math.imul(ah6, bh6) - lo += Math.imul(al5, bl7) - mid += Math.imul(al5, bh7) - mid += Math.imul(ah5, bl7) - hi += Math.imul(ah5, bh7) - lo += Math.imul(al4, bl8) - mid += Math.imul(al4, bh8) - mid += Math.imul(ah4, bl8) - hi += Math.imul(ah4, bh8) - lo += Math.imul(al3, bl9) - mid += Math.imul(al3, bh9) - mid += Math.imul(ah3, bl9) - hi += Math.imul(ah3, bh9) - var w12 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w12 >>> 26) - w12 &= 0x3ffffff - /* k = 13 */ - lo = Math.imul(al9, bl4) - mid = Math.imul(al9, bh4) - mid += Math.imul(ah9, bl4) - hi = Math.imul(ah9, bh4) - lo += Math.imul(al8, bl5) - mid += Math.imul(al8, bh5) - mid += Math.imul(ah8, bl5) - hi += Math.imul(ah8, bh5) - lo += Math.imul(al7, bl6) - mid += Math.imul(al7, bh6) - mid += Math.imul(ah7, bl6) - hi += Math.imul(ah7, bh6) - lo += Math.imul(al6, bl7) - mid += Math.imul(al6, bh7) - mid += Math.imul(ah6, bl7) - hi += Math.imul(ah6, bh7) - lo += Math.imul(al5, bl8) - mid += Math.imul(al5, bh8) - mid += Math.imul(ah5, bl8) - hi += Math.imul(ah5, bh8) - lo += Math.imul(al4, bl9) - mid += Math.imul(al4, bh9) - mid += Math.imul(ah4, bl9) - hi += Math.imul(ah4, bh9) - var w13 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w13 >>> 26) - w13 &= 0x3ffffff - /* k = 14 */ - lo = Math.imul(al9, bl5) - mid = Math.imul(al9, bh5) - mid += Math.imul(ah9, bl5) - hi = Math.imul(ah9, bh5) - lo += Math.imul(al8, bl6) - mid += Math.imul(al8, bh6) - mid += Math.imul(ah8, bl6) - hi += Math.imul(ah8, bh6) - lo += Math.imul(al7, bl7) - mid += Math.imul(al7, bh7) - mid += Math.imul(ah7, bl7) - hi += Math.imul(ah7, bh7) - lo += Math.imul(al6, bl8) - mid += Math.imul(al6, bh8) - mid += Math.imul(ah6, bl8) - hi += Math.imul(ah6, bh8) - lo += Math.imul(al5, bl9) - mid += Math.imul(al5, bh9) - mid += Math.imul(ah5, bl9) - hi += Math.imul(ah5, bh9) - var w14 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w14 >>> 26) - w14 &= 0x3ffffff - /* k = 15 */ - lo = Math.imul(al9, bl6) - mid = Math.imul(al9, bh6) - mid += Math.imul(ah9, bl6) - hi = Math.imul(ah9, bh6) - lo += Math.imul(al8, bl7) - mid += Math.imul(al8, bh7) - mid += Math.imul(ah8, bl7) - hi += Math.imul(ah8, bh7) - lo += Math.imul(al7, bl8) - mid += Math.imul(al7, bh8) - mid += Math.imul(ah7, bl8) - hi += Math.imul(ah7, bh8) - lo += Math.imul(al6, bl9) - mid += Math.imul(al6, bh9) - mid += Math.imul(ah6, bl9) - hi += Math.imul(ah6, bh9) - var w15 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w15 >>> 26) - w15 &= 0x3ffffff - /* k = 16 */ - lo = Math.imul(al9, bl7) - mid = Math.imul(al9, bh7) - mid += Math.imul(ah9, bl7) - hi = Math.imul(ah9, bh7) - lo += Math.imul(al8, bl8) - mid += Math.imul(al8, bh8) - mid += Math.imul(ah8, bl8) - hi += Math.imul(ah8, bh8) - lo += Math.imul(al7, bl9) - mid += Math.imul(al7, bh9) - mid += Math.imul(ah7, bl9) - hi += Math.imul(ah7, bh9) - var w16 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w16 >>> 26) - w16 &= 0x3ffffff - /* k = 17 */ - lo = Math.imul(al9, bl8) - mid = Math.imul(al9, bh8) - mid += Math.imul(ah9, bl8) - hi = Math.imul(ah9, bh8) - lo += Math.imul(al8, bl9) - mid += Math.imul(al8, bh9) - mid += Math.imul(ah8, bl9) - hi += Math.imul(ah8, bh9) - var w17 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w17 >>> 26) - w17 &= 0x3ffffff - /* k = 18 */ - lo = Math.imul(al9, bl9) - mid = Math.imul(al9, bh9) - mid += Math.imul(ah9, bl9) - hi = Math.imul(ah9, bh9) - var w18 = c + lo + ((mid & 0x1fff) << 13) - c = hi + (mid >>> 13) + (w18 >>> 26) - 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 -} - -},{}],1608:[function(require,module,exports){ -'use strict' -var BN = require('./bn') - -function ECJPoint (x, y, z) { - if (x === null && y === null && z === null) { - this.x = ECJPoint.one - this.y = ECJPoint.one - this.z = ECJPoint.zero - } else { - this.x = x - this.y = y - this.z = z - } - - this.zOne = this.z === ECJPoint.one -} - -ECJPoint.zero = BN.fromNumber(0) -ECJPoint.one = BN.fromNumber(1) - -ECJPoint.prototype.neg = function () { - if (this.inf) return this - - return new ECJPoint(this.x, this.y.redNeg(), this.z) -} - -ECJPoint.prototype.add = function (p) { - // O + P = P - if (this.inf) return p - - // P + O = P - if (p.inf) return this - - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-1998-cmo-2 - // 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 h = u1.redSub(u2) - var r = s1.redSub(s2) - if (h.isZero()) { - if (r.isZero()) return this.dbl() - return new ECJPoint(null, null, null) - } - - var h2 = h.redSqr() - var v = u1.redMul(h2) - var h3 = h2.redMul(h) - - 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) - - return new ECJPoint(nx, ny, nz) -} - -ECJPoint.prototype.mixedAdd = function (p) { - // O + P = P - if (this.inf) return p.toECJPoint() - - // P + O = P - if (p.inf) return this - - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-1998-cmo-2 - // with p.z = 1 - // 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) - - var h = u1.redSub(u2) - var r = s1.redSub(s2) - if (h.isZero()) { - if (r.isZero()) return this.dbl() - return new ECJPoint(null, null, null) - } - - var h2 = h.redSqr() - var v = u1.redMul(h2) - var h3 = h2.redMul(h) - - 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) - - return new ECJPoint(nx, ny, nz) -} - -ECJPoint.prototype.dbl = function () { - if (this.inf) return this - - var nx - var ny - var nz - - // Z = 1 - if (this.zOne) { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl - // 1M + 5S + 6A + 3*2 + 1*3 + 1*8 - - // 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 - var m = xx.redAdd(xx).redIAdd(xx) - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s) - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy).redIAdd(yyyy).redIAdd(yyyy) - - // 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 { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - // 2M + 5S + 6A + 3*2 + 1*3 + 1*8 - - // 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() - - // 8 * C - var c8 = c.redIAdd(c).redIAdd(c).redIAdd(c) - - // 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) - } - - return new ECJPoint(nx, ny, nz) -} - -ECJPoint.prototype.dblp = function (pow) { - if (pow === 0 || this.inf) return this - - var point = this - for (var i = 0; i < pow; i++) point = point.dbl() - - return point -} - -Object.defineProperty(ECJPoint.prototype, 'inf', { - enumerable: true, - get: function () { - return this.z.isZero() - } -}) - -module.exports = ECJPoint - -},{"./bn":1606}],1609:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var BN = require('./bn') -var ECJPoint = require('./ecjpoint') - -function ECPoint (x, y) { - if (x === null && y === null) { - this.x = this.y = null - this.inf = true - } else { - this.x = x - this.y = y - this.inf = false - } -} - -ECPoint.fromPublicKey = function (publicKey) { - var first = publicKey[0] - var x - var y - - if (publicKey.length === 33 && (first === 0x02 || first === 0x03)) { - x = BN.fromBuffer(publicKey.slice(1, 33)) - - // overflow - if (x.ucmp(BN.p) >= 0) return null - - // create from X - y = x.redSqr().redMul(x).redIAdd7().redSqrt() - if (y === null) return null - if ((first === 0x03) !== y.isOdd()) y = y.redNeg() - - return new ECPoint(x, y) - } - - if (publicKey.length === 65 && (first === 0x04 || first === 0x06 || first === 0x07)) { - x = BN.fromBuffer(publicKey.slice(1, 33)) - y = BN.fromBuffer(publicKey.slice(33, 65)) - - // overflow - if (x.ucmp(BN.p) >= 0 || y.ucmp(BN.p) >= 0) return null - - // is odd flag - if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null - - // x*x*x + 7 = y*y - if (x.redSqr().redMul(x).redIAdd7().ucmp(y.redSqr()) !== 0) return null - - return new ECPoint(x, y) - } - - return null -} - -ECPoint.prototype.toPublicKey = function (compressed) { - var x = this.x - var y = this.y - var publicKey - - if (compressed) { - publicKey = Buffer.alloc(33) - publicKey[0] = y.isOdd() ? 0x03 : 0x02 - x.toBuffer().copy(publicKey, 1) - } else { - publicKey = Buffer.alloc(65) - publicKey[0] = 0x04 - x.toBuffer().copy(publicKey, 1) - y.toBuffer().copy(publicKey, 33) - } - - return publicKey -} - -ECPoint.fromECJPoint = function (p) { - if (p.inf) return new ECPoint(null, null) - - var zinv = p.z.redInvm() - var zinv2 = zinv.redSqr() - var ax = p.x.redMul(zinv2) - var ay = p.y.redMul(zinv2).redMul(zinv) - - return new ECPoint(ax, ay) -} - -ECPoint.prototype.toECJPoint = function () { - if (this.inf) return new ECJPoint(null, null, null) - - return new ECJPoint(this.x, this.y, ECJPoint.one) -} - -ECPoint.prototype.neg = function () { - if (this.inf) return this - - return new ECPoint(this.x, this.y.redNeg()) -} - -ECPoint.prototype.add = function (p) { - // O + P = P - if (this.inf) return p - - // P + O = P - if (p.inf) return this - - if (this.x.ucmp(p.x) === 0) { - // P + P = 2P - if (this.y.ucmp(p.y) === 0) return this.dbl() - // P + (-P) = O - return new ECPoint(null, null) - } - - // s = (y - yp) / (x - xp) - // nx = s^2 - x - xp - // ny = s * (x - nx) - y - var s = this.y.redSub(p.y) - if (!s.isZero()) s = s.redMul(this.x.redSub(p.x).redInvm()) - - var nx = s.redSqr().redISub(this.x).redISub(p.x) - var ny = s.redMul(this.x.redSub(nx)).redISub(this.y) - return new ECPoint(nx, ny) -} - -ECPoint.prototype.dbl = function () { - if (this.inf) return this - - // 2P = O - var yy = this.y.redAdd(this.y) - if (yy.isZero()) return new ECPoint(null, null) - - // s = (3 * x^2) / (2 * y) - // nx = s^2 - 2*x - // ny = s * (x - nx) - y - var x2 = this.x.redSqr() - var s = x2.redAdd(x2).redIAdd(x2).redMul(yy.redInvm()) - - var nx = s.redSqr().redISub(this.x.redAdd(this.x)) - var ny = s.redMul(this.x.redSub(nx)).redISub(this.y) - return new ECPoint(nx, ny) -} - -ECPoint.prototype.mul = function (num) { - // Algorithm 3.36 Window NAF method for point multiplication - var nafPoints = this._getNAFPoints(4) - var points = nafPoints.points - - // Get NAF form - var naf = num.getNAF(nafPoints.wnd) - - // Add `this`*(N+1) for every w-NAF index - var acc = new ECJPoint(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 += 1 - acc = acc.dblp(k) - - if (i < 0) break - - // J +- P - var z = naf[i] - if (z > 0) { - acc = acc.mixedAdd(points[(z - 1) >> 1]) - } else { - acc = acc.mixedAdd(points[(-z - 1) >> 1].neg()) - } - } - - return ECPoint.fromECJPoint(acc) -} - -ECPoint.prototype._getNAFPoints1 = function () { - return { wnd: 1, points: [this] } -} - -ECPoint.prototype._getNAFPoints = function (wnd) { - var points = new Array((1 << wnd) - 1) - points[0] = this - var dbl = this.dbl() - for (var i = 1; i < points.length; ++i) points[i] = points[i - 1].add(dbl) - return { wnd: wnd, points: points } -} - -module.exports = ECPoint - -},{"./bn":1606,"./ecjpoint":1608,"safe-buffer":1593}],1610:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var BN = require('./bn') -var ECPoint = require('./ecpoint') -var ECJPoint = require('./ecjpoint') - -function ECPointG () { - this.x = BN.fromBuffer(Buffer.from('79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798', 'hex')) - this.y = BN.fromBuffer(Buffer.from('483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8', 'hex')) - this.inf = false - - this._precompute() -} - -ECPointG.prototype._precompute = function () { - var ecpoint = new ECPoint(this.x, this.y) - - var dstep = 4 - var points = new Array(1 + Math.ceil(257 / dstep)) - var acc = points[0] = ecpoint - for (var i = 1; i < points.length; ++i) { - for (var j = 0; j < dstep; j++) acc = acc.dbl() - points[i] = acc - } - - this.precomputed = { - naf: ecpoint._getNAFPoints(7), - doubles: { - step: dstep, - points: points, - negpoints: points.map(function (p) { return p.neg() }) - } - } -} - -ECPointG.prototype.mul = function (num) { - // Algorithm 3.42 Fixed-base NAF windowing method for point multiplication - var step = this.precomputed.doubles.step - var points = this.precomputed.doubles.points - var negpoints = this.precomputed.doubles.negpoints - - var naf = num.getNAF(1) - var I = ((1 << (step + 1)) - (step % 2 === 0 ? 2 : 1)) / 3 - - // Translate into more windowed form - var repr = [] - for (var j = 0; j < naf.length; j += step) { - var nafW = 0 - for (var k = j + step - 1; k >= j; k--) nafW = (nafW << 1) + naf[k] - repr.push(nafW) - } - - var a = new ECJPoint(null, null, null) - var b = new ECJPoint(null, null, null) - for (var i = I; i > 0; i--) { - for (var jj = 0; jj < repr.length; jj++) { - if (repr[jj] === i) { - b = b.mixedAdd(points[jj]) - } else if (repr[jj] === -i) { - b = b.mixedAdd(negpoints[jj]) - } - } - - a = a.add(b) - } - - return ECPoint.fromECJPoint(a) -} - -ECPointG.prototype.mulAdd = function (k1, p2, k2) { - var nafPointsP1 = this.precomputed.naf - var nafPointsP2 = p2._getNAFPoints1() - var wnd = [nafPointsP1.points, nafPointsP2.points] - var naf = [k1.getNAF(nafPointsP1.wnd), k2.getNAF(nafPointsP2.wnd)] - - var acc = new ECJPoint(null, null, null) - var tmp = [null, null] - for (var i = Math.max(naf[0].length, naf[1].length); i >= 0; i--) { - var k = 0 - - for (; i >= 0; ++k, --i) { - tmp[0] = naf[0][i] | 0 - tmp[1] = naf[1][i] | 0 - - if (tmp[0] !== 0 || tmp[1] !== 0) break - } - - if (i >= 0) k += 1 - acc = acc.dblp(k) - - if (i < 0) break - - for (var jj = 0; jj < 2; jj++) { - var z = tmp[jj] - var p - if (z === 0) { - continue - } else if (z > 0) { - p = wnd[jj][z >> 1] - } else if (z < 0) { - p = wnd[jj][-z >> 1].neg() - } - - // hack: ECPoint detection - if (p.z === undefined) { - acc = acc.mixedAdd(p) - } else { - acc = acc.add(p) - } - } - } - - return acc -} - -module.exports = new ECPointG() - -},{"./bn":1606,"./ecjpoint":1608,"./ecpoint":1609,"safe-buffer":1593}],1611:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var createHash = require('create-hash') -var HmacDRBG = require('drbg.js/hmac') -var messages = require('../messages.json') -var BN = require('./bn') -var ECPoint = require('./ecpoint') -var g = require('./ecpointg') - -exports.privateKeyVerify = function (privateKey) { - var bn = BN.fromBuffer(privateKey) - return !(bn.isOverflow() || bn.isZero()) -} - -exports.privateKeyExport = function (privateKey, compressed) { - var d = BN.fromBuffer(privateKey) - if (d.isOverflow() || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) - - return g.mul(d).toPublicKey(compressed) -} - -exports.privateKeyNegate = function (privateKey) { - var bn = BN.fromBuffer(privateKey) - if (bn.isZero()) return Buffer.alloc(32) - - if (bn.ucmp(BN.n) > 0) bn.isub(BN.n) - return BN.n.sub(bn).toBuffer() -} - -exports.privateKeyModInverse = function (privateKey) { - var bn = BN.fromBuffer(privateKey) - if (bn.isOverflow() || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) - - return bn.uinvm().toBuffer() -} - -exports.privateKeyTweakAdd = function (privateKey, tweak) { - var bn = BN.fromBuffer(tweak) - if (bn.isOverflow()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - bn.iadd(BN.fromBuffer(privateKey)) - if (bn.isOverflow()) bn.isub(BN.n) - if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - return bn.toBuffer() -} - -exports.privateKeyTweakMul = function (privateKey, tweak) { - var bn = BN.fromBuffer(tweak) - if (bn.isOverflow() || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) - - var d = BN.fromBuffer(privateKey) - return bn.umul(d).ureduce().toBuffer() -} - -exports.publicKeyCreate = function (privateKey, compressed) { - var d = BN.fromBuffer(privateKey) - if (d.isOverflow() || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) - - return g.mul(d).toPublicKey(compressed) -} - -exports.publicKeyConvert = function (publicKey, compressed) { - var point = ECPoint.fromPublicKey(publicKey) - if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - return point.toPublicKey(compressed) -} - -exports.publicKeyVerify = function (publicKey) { - return ECPoint.fromPublicKey(publicKey) !== null -} - -exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { - var point = ECPoint.fromPublicKey(publicKey) - if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = BN.fromBuffer(tweak) - if (tweak.isOverflow()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - var result = g.mul(tweak).add(point) - if (result.inf) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - return result.toPublicKey(compressed) -} - -exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { - var point = ECPoint.fromPublicKey(publicKey) - if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = BN.fromBuffer(tweak) - if (tweak.isOverflow() || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL) - - return point.mul(tweak).toPublicKey(compressed) -} - -exports.publicKeyCombine = function (publicKeys, compressed) { - var points = new Array(publicKeys.length) - for (var i = 0; i < publicKeys.length; ++i) { - points[i] = ECPoint.fromPublicKey(publicKeys[i]) - if (points[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - } - - var point = points[0] - for (var j = 1; j < points.length; ++j) point = point.add(points[j]) - if (point.inf) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL) - - return point.toPublicKey(compressed) -} - -exports.signatureNormalize = function (signature) { - var r = BN.fromBuffer(signature.slice(0, 32)) - var s = BN.fromBuffer(signature.slice(32, 64)) - if (r.isOverflow() || s.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - var result = Buffer.from(signature) - if (s.isHigh()) BN.n.sub(s).toBuffer().copy(result, 32) - - return result -} - -exports.signatureExport = function (signature) { - var r = signature.slice(0, 32) - var s = signature.slice(32, 64) - if (BN.fromBuffer(r).isOverflow() || BN.fromBuffer(s).isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - return { r: r, s: s } -} - -exports.signatureImport = function (sigObj) { - var r = BN.fromBuffer(sigObj.r) - if (r.isOverflow()) r = BN.fromNumber(0) - - var s = BN.fromBuffer(sigObj.s) - if (s.isOverflow()) s = BN.fromNumber(0) - - return Buffer.concat([r.toBuffer(), s.toBuffer()]) -} - -exports.sign = function (message, privateKey, noncefn, data) { - var d = BN.fromBuffer(privateKey) - if (d.isOverflow() || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL) - - if (noncefn === null) { - var drbg = new HmacDRBG('sha256', privateKey, message, data) - noncefn = function () { return drbg.generate(32) } - } - - var bnMessage = BN.fromBuffer(message) - for (var count = 0; ; ++count) { - var nonce = noncefn(message, privateKey, null, data, count) - if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL) - - var k = BN.fromBuffer(nonce) - if (k.isOverflow() || k.isZero()) continue - - var kp = g.mul(k) - var r = kp.x.fireduce() - if (r.isZero()) continue - - var s = k.uinvm().umul(r.umul(d).ureduce().iadd(bnMessage).fireduce()).ureduce() - if (s.isZero()) continue - - var recovery = (kp.x.ucmp(r) !== 0 ? 2 : 0) | (kp.y.isOdd() ? 1 : 0) - if (s.isHigh()) { - s = BN.n.sub(s) - recovery ^= 1 - } - - return { - signature: Buffer.concat([r.toBuffer(), s.toBuffer()]), - recovery: recovery - } - } -} - -exports.verify = function (message, signature, publicKey) { - var sigr = BN.fromBuffer(signature.slice(0, 32)) - var sigs = BN.fromBuffer(signature.slice(32, 64)) - if (sigr.isOverflow() || sigs.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - if (sigs.isHigh() || sigr.isZero() || sigs.isZero()) return false - - var pub = ECPoint.fromPublicKey(publicKey) - if (pub === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - var sinv = sigs.uinvm() - var u1 = sinv.umul(BN.fromBuffer(message)).ureduce() - var u2 = sinv.umul(sigr).ureduce() - var point = g.mulAdd(u1, pub, u2) - if (point.inf) return false - - // return ECPoint.fromECJPoint(point).x.fireduce().ucmp(sigr) === 0 - // Inversion-free - var z2 = point.z.redSqr() - if (sigr.redMul(z2).ucmp(point.x) === 0) return true - if (sigr.ucmp(BN.psn) >= 0) return false - - return sigr.iadd(BN.psn).redMul(z2).ucmp(point.x) === 0 -} - -exports.recover = function (message, signature, recovery, compressed) { - var sigr = BN.fromBuffer(signature.slice(0, 32)) - var sigs = BN.fromBuffer(signature.slice(32, 64)) - if (sigr.isOverflow() || sigs.isOverflow()) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - do { - if (sigr.isZero() || sigs.isZero()) break - - var kpx = sigr - if (recovery >> 1) { - if (kpx.ucmp(BN.psn) >= 0) break - kpx = sigr.add(BN.n) - } - - var kpPublicKey = Buffer.concat([Buffer.from([0x02 + (recovery & 0x01)]), kpx.toBuffer()]) - var kp = ECPoint.fromPublicKey(kpPublicKey) - if (kp === null) break - - var rInv = sigr.uinvm() - var s1 = BN.n.sub(BN.fromBuffer(message)).umul(rInv).ureduce() - var s2 = sigs.umul(rInv).ureduce() - var point = ECPoint.fromECJPoint(g.mulAdd(s1, kp, s2)) - return point.toPublicKey(compressed) - } while (false) - - throw new Error(messages.ECDSA_RECOVER_FAIL) -} - -exports.ecdh = function (publicKey, privateKey) { - var shared = exports.ecdhUnsafe(publicKey, privateKey, true) - return createHash('sha256').update(shared).digest() -} - -exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { - var point = ECPoint.fromPublicKey(publicKey) - if (point === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - var scalar = BN.fromBuffer(privateKey) - if (scalar.isOverflow() || scalar.isZero()) throw new Error(messages.ECDH_FAIL) - - return point.mul(scalar).toPublicKey(compressed) -} - -},{"../messages.json":1612,"./bn":1606,"./ecpoint":1609,"./ecpointg":1610,"create-hash":232,"drbg.js/hmac":277,"safe-buffer":1593}],1612:[function(require,module,exports){ -module.exports={ - "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", - "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", - "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid", - "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid", - "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid", - "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range", - "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format", - "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format", - "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array", - "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element", - "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer", - "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid", - "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid", - "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again", - "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid", - "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range", - "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid", - "ECDH_FAIL": "scalar was invalid (zero or overflow)", - "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer", - "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid", - "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature", - "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature", - "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format", - "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid", - "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature", - "MSG32_TYPE_INVALID": "message should be a Buffer", - "MSG32_LENGTH_INVALID": "message length is invalid", - "OPTIONS_TYPE_INVALID": "options should be an Object", - "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer", - "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid", - "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function", - "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number", - "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4", - "TWEAK_TYPE_INVALID": "tweak should be a Buffer", - "TWEAK_LENGTH_INVALID": "tweak length is invalid" -} - -},{}],1613:[function(require,module,exports){ -(function (process){ -exports = module.exports = SemVer - -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' - -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' - -src[FULL] = '^' + FULLPLAIN + '$' - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' - -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' - -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' -var COERCERTL = R++ -re[COERCERTL] = new RegExp(src[COERCE], 'g') - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} - -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -SemVer.prototype.compareBuild = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - var i = 0 - do { - var a = this.build[i] - var b = other.build[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } - - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} - -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} - -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.compareBuild = compareBuild -function compareBuild (a, b, loose) { - var versionA = new SemVer(a, loose) - var versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.compareBuild(b, a, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} - -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) -} - -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - if (this.value === '') { - return true - } - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set -} - -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return ( - isSatisfiable(thisComparators, options) && - range.set.some(function (rangeComparators) { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every(function (thisComparator) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) -} - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -function isSatisfiable (comparators, options) { - var result = true - var remainingComparators = comparators.slice() - var testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every(function (otherComparator) { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - ret = gtlt + M + '.' + m + '.' + p + pr - } else if (xm) { - ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr - } else if (xp) { - ret = '>=' + M + '.' + m + '.0' + pr + - ' <' + M + '.' + (+m + 1) + '.0' + pr - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} - -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version, options) { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - var match = null - if (!options.rtl) { - match = version.match(re[COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - var next - while ((next = re[COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[COERCERTL].lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - re[COERCERTL].lastIndex = -1 - } - - if (match === null) { - return null - } - - return parse(match[2] + - '.' + (match[3] || '0') + - '.' + (match[4] || '0'), options) -} - -}).call(this,require('_process')) -},{"_process":1438}],1614:[function(require,module,exports){ -(function (setImmediate){ -'use strict'; -module.exports = typeof setImmediate === 'function' ? setImmediate : - function setImmediate() { - var args = [].slice.apply(arguments); - args.splice(1, 0, 0); - setTimeout.apply(null, args); - }; - -}).call(this,require("timers").setImmediate) -},{"timers":1749}],1615:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -// prototype class for hash functions -function Hash (blockSize, finalSize) { - this._block = Buffer.alloc(blockSize) - this._finalSize = finalSize - this._blockSize = blockSize - this._len = 0 -} - -Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8' - data = Buffer.from(data, enc) - } - - var block = this._block - var blockSize = this._blockSize - var length = data.length - var accum = this._len - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize - var remainder = Math.min(length - offset, blockSize - assigned) - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i] - } - - accum += remainder - offset += remainder - - if ((accum % blockSize) === 0) { - this._update(block) - } - } - - this._len += length - return this -} - -Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize - - this._block[rem] = 0x80 - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1) - - if (rem >= this._finalSize) { - this._update(this._block) - this._block.fill(0) - } - - var bits = this._len * 8 - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4) - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0 - var highBits = (bits - lowBits) / 0x100000000 - - this._block.writeUInt32BE(highBits, this._blockSize - 8) - this._block.writeUInt32BE(lowBits, this._blockSize - 4) - } - - this._update(this._block) - var hash = this._hash() - - return enc ? hash.toString(enc) : hash -} - -Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') -} - -module.exports = Hash - -},{"safe-buffer":1593}],1616:[function(require,module,exports){ -var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase() - - var Algorithm = exports[algorithm] - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() -} - -exports.sha = require('./sha') -exports.sha1 = require('./sha1') -exports.sha224 = require('./sha224') -exports.sha256 = require('./sha256') -exports.sha384 = require('./sha384') -exports.sha512 = require('./sha512') - -},{"./sha":1617,"./sha1":1618,"./sha224":1619,"./sha256":1620,"./sha384":1621,"./sha512":1622}],1617:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha, Hash) - -Sha.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha - -},{"./hash":1615,"inherits":453,"safe-buffer":1593}],1618:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha1 () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha1, Hash) - -Sha1.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl1 (num) { - return (num << 1) | (num >>> 31) -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha1.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha1.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha1 - -},{"./hash":1615,"inherits":453,"safe-buffer":1593}],1619:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Sha256 = require('./sha256') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(64) - -function Sha224 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha224, Sha256) - -Sha224.prototype.init = function () { - this._a = 0xc1059ed8 - this._b = 0x367cd507 - this._c = 0x3070dd17 - this._d = 0xf70e5939 - this._e = 0xffc00b31 - this._f = 0x68581511 - this._g = 0x64f98fa7 - this._h = 0xbefa4fa4 - - return this -} - -Sha224.prototype._hash = function () { - var H = Buffer.allocUnsafe(28) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - - return H -} - -module.exports = Sha224 - -},{"./hash":1615,"./sha256":1620,"inherits":453,"safe-buffer":1593}],1620:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] - -var W = new Array(64) - -function Sha256 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha256, Hash) - -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 - - return this -} - -function ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) -} - -function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) -} - -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) -} - -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) -} - -Sha256.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} - -Sha256.prototype._hash = function () { - var H = Buffer.allocUnsafe(32) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) - - return H -} - -module.exports = Sha256 - -},{"./hash":1615,"inherits":453,"safe-buffer":1593}],1621:[function(require,module,exports){ -var inherits = require('inherits') -var SHA512 = require('./sha512') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(160) - -function Sha384 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha384, SHA512) - -Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d - this._bh = 0x629a292a - this._ch = 0x9159015a - this._dh = 0x152fecd8 - this._eh = 0x67332667 - this._fh = 0x8eb44a87 - this._gh = 0xdb0c2e0d - this._hh = 0x47b5481d - - this._al = 0xc1059ed8 - this._bl = 0x367cd507 - this._cl = 0x3070dd17 - this._dl = 0xf70e5939 - this._el = 0xffc00b31 - this._fl = 0x68581511 - this._gl = 0x64f98fa7 - this._hl = 0xbefa4fa4 - - return this -} - -Sha384.prototype._hash = function () { - var H = Buffer.allocUnsafe(48) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - - return H -} - -module.exports = Sha384 - -},{"./hash":1615,"./sha512":1622,"inherits":453,"safe-buffer":1593}],1622:[function(require,module,exports){ -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -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 -] - -var W = new Array(160) - -function Sha512 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha512, Hash) - -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 - - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 - - return this -} - -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} - -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} - -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} - -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} - -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} - -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} - -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 -} - -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 - - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) - - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] - - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] - - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 - - W[i] = Wih - W[i + 1] = Wil - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] - - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) - - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 - } - - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} - -Sha512.prototype._hash = function () { - var H = Buffer.allocUnsafe(64) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) - - return H -} - -module.exports = Sha512 - -},{"./hash":1615,"inherits":453,"safe-buffer":1593}],1623:[function(require,module,exports){ -'use strict'; -module.exports = require('./lib/index'); - -},{"./lib/index":1627}],1624:[function(require,module,exports){ -'use strict'; - -var randomFromSeed = require('./random/random-from-seed'); - -var ORIGINAL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-'; -var alphabet; -var previousSeed; - -var shuffled; - -function reset() { - shuffled = false; -} - -function setCharacters(_alphabet_) { - if (!_alphabet_) { - if (alphabet !== ORIGINAL) { - alphabet = ORIGINAL; - reset(); - } - return; - } - - if (_alphabet_ === alphabet) { - return; - } - - if (_alphabet_.length !== ORIGINAL.length) { - throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. You submitted ' + _alphabet_.length + ' characters: ' + _alphabet_); - } - - var unique = _alphabet_.split('').filter(function(item, ind, arr){ - return ind !== arr.lastIndexOf(item); - }); - - if (unique.length) { - throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. These characters were not unique: ' + unique.join(', ')); - } - - alphabet = _alphabet_; - reset(); -} - -function characters(_alphabet_) { - setCharacters(_alphabet_); - return alphabet; -} - -function setSeed(seed) { - randomFromSeed.seed(seed); - if (previousSeed !== seed) { - reset(); - previousSeed = seed; - } -} - -function shuffle() { - if (!alphabet) { - setCharacters(ORIGINAL); - } - - var sourceArray = alphabet.split(''); - var targetArray = []; - var r = randomFromSeed.nextValue(); - var characterIndex; - - while (sourceArray.length > 0) { - r = randomFromSeed.nextValue(); - characterIndex = Math.floor(r * sourceArray.length); - targetArray.push(sourceArray.splice(characterIndex, 1)[0]); - } - return targetArray.join(''); -} - -function getShuffled() { - if (shuffled) { - return shuffled; - } - shuffled = shuffle(); - return shuffled; -} - -/** - * lookup shuffled letter - * @param index - * @returns {string} - */ -function lookup(index) { - var alphabetShuffled = getShuffled(); - return alphabetShuffled[index]; -} - -function get () { - return alphabet || ORIGINAL; -} - -module.exports = { - get: get, - characters: characters, - seed: setSeed, - lookup: lookup, - shuffled: getShuffled -}; - -},{"./random/random-from-seed":1630}],1625:[function(require,module,exports){ -'use strict'; - -var generate = require('./generate'); -var alphabet = require('./alphabet'); - -// Ignore all milliseconds before a certain time to reduce the size of the date entropy without sacrificing uniqueness. -// This number should be updated every year or so to keep the generated id short. -// To regenerate `new Date() - 0` and bump the version. Always bump the version! -var REDUCE_TIME = 1567752802062; - -// don't change unless we change the algos or REDUCE_TIME -// must be an integer and less than 16 -var version = 7; - -// Counter is used when shortid is called multiple times in one second. -var counter; - -// Remember the last time shortid was called in case counter is needed. -var previousSeconds; - -/** - * Generate unique id - * Returns string id - */ -function build(clusterWorkerId) { - var str = ''; - - var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001); - - if (seconds === previousSeconds) { - counter++; - } else { - counter = 0; - previousSeconds = seconds; - } - - str = str + generate(version); - str = str + generate(clusterWorkerId); - if (counter > 0) { - str = str + generate(counter); - } - str = str + generate(seconds); - return str; -} - -module.exports = build; - -},{"./alphabet":1624,"./generate":1626}],1626:[function(require,module,exports){ -'use strict'; - -var alphabet = require('./alphabet'); -var random = require('./random/random-byte'); -var format = require('nanoid/format'); - -function generate(number) { - var loopCounter = 0; - var done; - - var str = ''; - - while (!done) { - str = str + format(random, alphabet.get(), 1); - done = number < (Math.pow(16, loopCounter + 1 ) ); - loopCounter++; - } - return str; -} - -module.exports = generate; - -},{"./alphabet":1624,"./random/random-byte":1629,"nanoid/format":1356}],1627:[function(require,module,exports){ -'use strict'; - -var alphabet = require('./alphabet'); -var build = require('./build'); -var isValid = require('./is-valid'); - -// if you are using cluster or multiple servers use this to make each instance -// has a unique value for worker -// Note: I don't know if this is automatically set when using third -// party cluster solutions such as pm2. -var clusterWorkerId = require('./util/cluster-worker-id') || 0; - -/** - * Set the seed. - * Highly recommended if you don't want people to try to figure out your id schema. - * exposed as shortid.seed(int) - * @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps. - */ -function seed(seedValue) { - alphabet.seed(seedValue); - return module.exports; -} - -/** - * Set the cluster worker or machine id - * exposed as shortid.worker(int) - * @param workerId worker must be positive integer. Number less than 16 is recommended. - * returns shortid module so it can be chained. - */ -function worker(workerId) { - clusterWorkerId = workerId; - return module.exports; -} - -/** - * - * sets new characters to use in the alphabet - * returns the shuffled alphabet - */ -function characters(newCharacters) { - if (newCharacters !== undefined) { - alphabet.characters(newCharacters); - } - - return alphabet.shuffled(); -} - -/** - * Generate unique id - * Returns string id - */ -function generate() { - return build(clusterWorkerId); -} - -// Export all other functions as properties of the generate function -module.exports = generate; -module.exports.generate = generate; -module.exports.seed = seed; -module.exports.worker = worker; -module.exports.characters = characters; -module.exports.isValid = isValid; - -},{"./alphabet":1624,"./build":1625,"./is-valid":1628,"./util/cluster-worker-id":1631}],1628:[function(require,module,exports){ -'use strict'; -var alphabet = require('./alphabet'); - -function isShortId(id) { - if (!id || typeof id !== 'string' || id.length < 6 ) { - return false; - } - - var nonAlphabetic = new RegExp('[^' + - alphabet.get().replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') + - ']'); - return !nonAlphabetic.test(id); -} - -module.exports = isShortId; - -},{"./alphabet":1624}],1629:[function(require,module,exports){ -'use strict'; - -var crypto = typeof window === 'object' && (window.crypto || window.msCrypto); // IE 11 uses window.msCrypto - -var randomByte; - -if (!crypto || !crypto.getRandomValues) { - randomByte = function(size) { - var bytes = []; - for (var i = 0; i < size; i++) { - bytes.push(Math.floor(Math.random() * 256)); - } - return bytes; - }; -} else { - randomByte = function(size) { - return crypto.getRandomValues(new Uint8Array(size)); - }; -} - -module.exports = randomByte; - -},{}],1630:[function(require,module,exports){ -'use strict'; - -// Found this seed-based random generator somewhere -// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu) - -var seed = 1; - -/** - * return a random number based on a seed - * @param seed - * @returns {number} - */ -function getNextValue() { - seed = (seed * 9301 + 49297) % 233280; - return seed/(233280.0); -} - -function setSeed(_seed_) { - seed = _seed_; -} - -module.exports = { - nextValue: getNextValue, - seed: setSeed -}; - -},{}],1631:[function(require,module,exports){ -'use strict'; - -module.exports = 0; - -},{}],1632:[function(require,module,exports){ -var varint = require('varint') -exports.encode = function encode (v, b, o) { - v = v >= 0 ? v*2 : v*-2 - 1 - var r = varint.encode(v, b, o) - encode.bytes = varint.encode.bytes - return r -} -exports.decode = function decode (b, o) { - var v = varint.decode(b, o) - decode.bytes = varint.decode.bytes - return v & 1 ? (v+1) / -2 : v / 2 -} - -exports.encodingLength = function (v) { - return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1) -} - -},{"varint":1785}],1633:[function(require,module,exports){ -(function (Buffer){ -var debug = require('debug')('simple-peer') -var getBrowserRTC = require('get-browser-rtc') -var randombytes = require('randombytes') -var stream = require('readable-stream') -var queueMicrotask = require('queue-microtask') // TODO: remove when Node 10 is not supported - -var MAX_BUFFERED_AMOUNT = 64 * 1024 -var ICECOMPLETE_TIMEOUT = 5 * 1000 -var CHANNEL_CLOSING_TIMEOUT = 5 * 1000 - -// HACK: Filter trickle lines when trickle is disabled #354 -function filterTrickle (sdp) { - return sdp.replace(/a=ice-options:trickle\s\n/g, '') -} - -function makeError (message, code) { - var err = new Error(message) - err.code = code - return err -} - -function warn (message) { - console.warn(message) -} - -/** - * WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods. - * Duplex stream. - * @param {Object} opts - */ -class Peer extends stream.Duplex { - constructor (opts) { - opts = Object.assign({ - allowHalfOpen: false - }, opts) - - super(opts) - - this._id = randombytes(4).toString('hex').slice(0, 7) - this._debug('new peer %o', opts) - - this.channelName = opts.initiator - ? opts.channelName || randombytes(20).toString('hex') - : null - - this.initiator = opts.initiator || false - this.channelConfig = opts.channelConfig || Peer.channelConfig - this.config = Object.assign({}, Peer.config, opts.config) - this.offerOptions = opts.offerOptions || {} - this.answerOptions = opts.answerOptions || {} - this.sdpTransform = opts.sdpTransform || (sdp => sdp) - this.streams = opts.streams || (opts.stream ? [opts.stream] : []) // support old "stream" option - this.trickle = opts.trickle !== undefined ? opts.trickle : true - this.allowHalfTrickle = opts.allowHalfTrickle !== undefined ? opts.allowHalfTrickle : false - this.iceCompleteTimeout = opts.iceCompleteTimeout || ICECOMPLETE_TIMEOUT - - this.destroyed = false - this._connected = false - - this.remoteAddress = undefined - this.remoteFamily = undefined - this.remotePort = undefined - this.localAddress = undefined - this.localFamily = undefined - this.localPort = undefined - - this._wrtc = (opts.wrtc && typeof opts.wrtc === 'object') - ? opts.wrtc - : getBrowserRTC() - - if (!this._wrtc) { - if (typeof window === 'undefined') { - throw makeError('No WebRTC support: Specify `opts.wrtc` option in this environment', 'ERR_WEBRTC_SUPPORT') - } else { - throw makeError('No WebRTC support: Not a supported browser', 'ERR_WEBRTC_SUPPORT') - } - } - - this._pcReady = false - this._channelReady = false - this._iceComplete = false // ice candidate trickle done (got null candidate) - this._iceCompleteTimer = null // send an offer/answer anyway after some timeout - this._channel = null - this._pendingCandidates = [] - - this._isNegotiating = !this.initiator // is this peer waiting for negotiation to complete? - this._batchedNegotiation = false // batch synchronous negotiations - this._queuedNegotiation = false // is there a queued negotiation request? - this._sendersAwaitingStable = [] - this._senderMap = new Map() - this._firstStable = true - this._closingInterval = null - - this._remoteTracks = [] - this._remoteStreams = [] - - this._chunk = null - this._cb = null - this._interval = null - - try { - this._pc = new (this._wrtc.RTCPeerConnection)(this.config) - } catch (err) { - queueMicrotask(() => this.destroy(makeError(err, 'ERR_PC_CONSTRUCTOR'))) - return - } - - // We prefer feature detection whenever possible, but sometimes that's not - // possible for certain implementations. - this._isReactNativeWebrtc = typeof this._pc._peerConnectionId === 'number' - - this._pc.oniceconnectionstatechange = () => { - this._onIceStateChange() - } - this._pc.onicegatheringstatechange = () => { - this._onIceStateChange() - } - this._pc.onsignalingstatechange = () => { - this._onSignalingStateChange() - } - this._pc.onicecandidate = event => { - this._onIceCandidate(event) - } - - // Other spec events, unused by this implementation: - // - onconnectionstatechange - // - onicecandidateerror - // - onfingerprintfailure - // - onnegotiationneeded - - if (this.initiator) { - this._setupData({ - channel: this._pc.createDataChannel(this.channelName, this.channelConfig) - }) - } else { - this._pc.ondatachannel = event => { - this._setupData(event) - } - } - - if (this.streams) { - this.streams.forEach(stream => { - this.addStream(stream) - }) - } - this._pc.ontrack = event => { - this._onTrack(event) - } - - if (this.initiator) { - this._needsNegotiation() - } - - this._onFinishBound = () => { - this._onFinish() - } - this.once('finish', this._onFinishBound) - } - - get bufferSize () { - return (this._channel && this._channel.bufferedAmount) || 0 - } - - // HACK: it's possible channel.readyState is "closing" before peer.destroy() fires - // https://bugs.chromium.org/p/chromium/issues/detail?id=882743 - get connected () { - return (this._connected && this._channel.readyState === 'open') - } - - address () { - return { port: this.localPort, family: this.localFamily, address: this.localAddress } - } - - signal (data) { - if (this.destroyed) throw makeError('cannot signal after peer is destroyed', 'ERR_SIGNALING') - if (typeof data === 'string') { - try { - data = JSON.parse(data) - } catch (err) { - data = {} - } - } - this._debug('signal()') - - if (data.renegotiate && this.initiator) { - this._debug('got request to renegotiate') - this._needsNegotiation() - } - if (data.transceiverRequest && this.initiator) { - this._debug('got request for transceiver') - this.addTransceiver(data.transceiverRequest.kind, data.transceiverRequest.init) - } - if (data.candidate) { - if (this._pc.localDescription && this._pc.localDescription.type && this._pc.remoteDescription && this._pc.remoteDescription.type) { - this._addIceCandidate(data.candidate) - } else { - this._pendingCandidates.push(data.candidate) - } - } - if (data.sdp) { - this._pc.setRemoteDescription(new (this._wrtc.RTCSessionDescription)(data)) - .then(() => { - if (this.destroyed) return - - this._pendingCandidates.forEach(candidate => { - this._addIceCandidate(candidate) - }) - this._pendingCandidates = [] - - if (this._pc.remoteDescription.type === 'offer') this._createAnswer() - }) - .catch(err => { - this.destroy(makeError(err, 'ERR_SET_REMOTE_DESCRIPTION')) - }) - } - if (!data.sdp && !data.candidate && !data.renegotiate && !data.transceiverRequest) { - this.destroy(makeError('signal() called with invalid signal data', 'ERR_SIGNALING')) - } - } - - _addIceCandidate (candidate) { - var iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate) - this._pc.addIceCandidate(iceCandidateObj) - .catch(err => { - if (!iceCandidateObj.address || iceCandidateObj.address.endsWith('.local')) { - warn('Ignoring unsupported ICE candidate.') - } else { - this.destroy(makeError(err, 'ERR_ADD_ICE_CANDIDATE')) - } - }) - } - - /** - * Send text/binary data to the remote peer. - * @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk - */ - send (chunk) { - this._channel.send(chunk) - } - - /** - * Add a Transceiver to the connection. - * @param {String} kind - * @param {Object} init - */ - addTransceiver (kind, init) { - this._debug('addTransceiver()') - - if (this.initiator) { - try { - this._pc.addTransceiver(kind, init) - this._needsNegotiation() - } catch (err) { - this.destroy(makeError(err, 'ERR_ADD_TRANSCEIVER')) - } - } else { - this.emit('signal', { // request initiator to renegotiate - transceiverRequest: { kind, init } - }) - } - } - - /** - * Add a MediaStream to the connection. - * @param {MediaStream} stream - */ - addStream (stream) { - this._debug('addStream()') - - stream.getTracks().forEach(track => { - this.addTrack(track, stream) - }) - } - - /** - * Add a MediaStreamTrack to the connection. - * @param {MediaStreamTrack} track - * @param {MediaStream} stream - */ - addTrack (track, stream) { - this._debug('addTrack()') - - var submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender - var sender = submap.get(stream) - if (!sender) { - sender = this._pc.addTrack(track, stream) - submap.set(stream, sender) - this._senderMap.set(track, submap) - this._needsNegotiation() - } else if (sender.removed) { - throw makeError('Track has been removed. You should enable/disable tracks that you want to re-add.', 'ERR_SENDER_REMOVED') - } else { - throw makeError('Track has already been added to that stream.', 'ERR_SENDER_ALREADY_ADDED') - } - } - - /** - * Replace a MediaStreamTrack by another in the connection. - * @param {MediaStreamTrack} oldTrack - * @param {MediaStreamTrack} newTrack - * @param {MediaStream} stream - */ - replaceTrack (oldTrack, newTrack, stream) { - this._debug('replaceTrack()') - - var submap = this._senderMap.get(oldTrack) - var sender = submap ? submap.get(stream) : null - if (!sender) { - throw makeError('Cannot replace track that was never added.', 'ERR_TRACK_NOT_ADDED') - } - if (newTrack) this._senderMap.set(newTrack, submap) - - if (sender.replaceTrack != null) { - sender.replaceTrack(newTrack) - } else { - this.destroy(makeError('replaceTrack is not supported in this browser', 'ERR_UNSUPPORTED_REPLACETRACK')) - } - } - - /** - * Remove a MediaStreamTrack from the connection. - * @param {MediaStreamTrack} track - * @param {MediaStream} stream - */ - removeTrack (track, stream) { - this._debug('removeSender()') - - var submap = this._senderMap.get(track) - var sender = submap ? submap.get(stream) : null - if (!sender) { - throw makeError('Cannot remove track that was never added.', 'ERR_TRACK_NOT_ADDED') - } - try { - sender.removed = true - this._pc.removeTrack(sender) - } catch (err) { - if (err.name === 'NS_ERROR_UNEXPECTED') { - this._sendersAwaitingStable.push(sender) // HACK: Firefox must wait until (signalingState === stable) https://bugzilla.mozilla.org/show_bug.cgi?id=1133874 - } else { - this.destroy(makeError(err, 'ERR_REMOVE_TRACK')) - } - } - this._needsNegotiation() - } - - /** - * Remove a MediaStream from the connection. - * @param {MediaStream} stream - */ - removeStream (stream) { - this._debug('removeSenders()') - - stream.getTracks().forEach(track => { - this.removeTrack(track, stream) - }) - } - - _needsNegotiation () { - this._debug('_needsNegotiation') - if (this._batchedNegotiation) return // batch synchronous renegotiations - this._batchedNegotiation = true - queueMicrotask(() => { - this._batchedNegotiation = false - this._debug('starting batched negotiation') - this.negotiate() - }) - } - - negotiate () { - if (this.initiator) { - if (this._isNegotiating) { - this._queuedNegotiation = true - this._debug('already negotiating, queueing') - } else { - this._debug('start negotiation') - setTimeout(() => { // HACK: Chrome crashes if we immediately call createOffer - this._createOffer() - }, 0) - } - } else { - if (!this._isNegotiating) { - this._debug('requesting negotiation from initiator') - this.emit('signal', { // request initiator to renegotiate - renegotiate: true - }) - } - } - this._isNegotiating = true - } - - // TODO: Delete this method once readable-stream is updated to contain a default - // implementation of destroy() that automatically calls _destroy() - // See: https://github.com/nodejs/readable-stream/issues/283 - destroy (err) { - this._destroy(err, () => {}) - } - - _destroy (err, cb) { - if (this.destroyed) return - - this._debug('destroy (error: %s)', err && (err.message || err)) - - this.readable = this.writable = false - - if (!this._readableState.ended) this.push(null) - if (!this._writableState.finished) this.end() - - this.destroyed = true - this._connected = false - this._pcReady = false - this._channelReady = false - this._remoteTracks = null - this._remoteStreams = null - this._senderMap = null - - clearInterval(this._closingInterval) - this._closingInterval = null - - clearInterval(this._interval) - this._interval = null - this._chunk = null - this._cb = null - - if (this._onFinishBound) this.removeListener('finish', this._onFinishBound) - this._onFinishBound = null - - if (this._channel) { - try { - this._channel.close() - } catch (err) {} - - this._channel.onmessage = null - this._channel.onopen = null - this._channel.onclose = null - this._channel.onerror = null - } - if (this._pc) { - try { - this._pc.close() - } catch (err) {} - - this._pc.oniceconnectionstatechange = null - this._pc.onicegatheringstatechange = null - this._pc.onsignalingstatechange = null - this._pc.onicecandidate = null - this._pc.ontrack = null - this._pc.ondatachannel = null - } - this._pc = null - this._channel = null - - if (err) this.emit('error', err) - this.emit('close') - cb() - } - - _setupData (event) { - if (!event.channel) { - // In some situations `pc.createDataChannel()` returns `undefined` (in wrtc), - // which is invalid behavior. Handle it gracefully. - // See: https://github.com/feross/simple-peer/issues/163 - return this.destroy(makeError('Data channel event is missing `channel` property', 'ERR_DATA_CHANNEL')) - } - - this._channel = event.channel - this._channel.binaryType = 'arraybuffer' - - if (typeof this._channel.bufferedAmountLowThreshold === 'number') { - this._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT - } - - this.channelName = this._channel.label - - this._channel.onmessage = event => { - this._onChannelMessage(event) - } - this._channel.onbufferedamountlow = () => { - this._onChannelBufferedAmountLow() - } - this._channel.onopen = () => { - this._onChannelOpen() - } - this._channel.onclose = () => { - this._onChannelClose() - } - this._channel.onerror = err => { - this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) - } - - // HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition - // https://bugs.chromium.org/p/chromium/issues/detail?id=882743 - var isClosing = false - this._closingInterval = setInterval(() => { // No "onclosing" event - if (this._channel && this._channel.readyState === 'closing') { - if (isClosing) this._onChannelClose() // closing timed out: equivalent to onclose firing - isClosing = true - } else { - isClosing = false - } - }, CHANNEL_CLOSING_TIMEOUT) - } - - _read () {} - - _write (chunk, encoding, cb) { - if (this.destroyed) return cb(makeError('cannot write after peer is destroyed', 'ERR_DATA_CHANNEL')) - - if (this._connected) { - try { - this.send(chunk) - } catch (err) { - return this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) - } - if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { - this._debug('start backpressure: bufferedAmount %d', this._channel.bufferedAmount) - this._cb = cb - } else { - cb(null) - } - } else { - this._debug('write before connect') - this._chunk = chunk - this._cb = cb - } - } - - // When stream finishes writing, close socket. Half open connections are not - // supported. - _onFinish () { - if (this.destroyed) return - - // Wait a bit before destroying so the socket flushes. - // TODO: is there a more reliable way to accomplish this? - const destroySoon = () => { - setTimeout(() => this.destroy(), 1000) - } - - if (this._connected) { - destroySoon() - } else { - this.once('connect', destroySoon) - } - } - - _startIceCompleteTimeout () { - if (this.destroyed) return - if (this._iceCompleteTimer) return - this._debug('started iceComplete timeout') - this._iceCompleteTimer = setTimeout(() => { - if (!this._iceComplete) { - this._iceComplete = true - this._debug('iceComplete timeout completed') - this.emit('iceTimeout') - this.emit('_iceComplete') - } - }, this.iceCompleteTimeout) - } - - _createOffer () { - if (this.destroyed) return - - this._pc.createOffer(this.offerOptions) - .then(offer => { - if (this.destroyed) return - if (!this.trickle && !this.allowHalfTrickle) offer.sdp = filterTrickle(offer.sdp) - offer.sdp = this.sdpTransform(offer.sdp) - - const sendOffer = () => { - if (this.destroyed) return - var signal = this._pc.localDescription || offer - this._debug('signal') - this.emit('signal', { - type: signal.type, - sdp: signal.sdp - }) - } - - const onSuccess = () => { - this._debug('createOffer success') - if (this.destroyed) return - if (this.trickle || this._iceComplete) sendOffer() - else this.once('_iceComplete', sendOffer) // wait for candidates - } - - const onError = err => { - this.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION')) - } - - this._pc.setLocalDescription(offer) - .then(onSuccess) - .catch(onError) - }) - .catch(err => { - this.destroy(makeError(err, 'ERR_CREATE_OFFER')) - }) - } - - _requestMissingTransceivers () { - if (this._pc.getTransceivers) { - this._pc.getTransceivers().forEach(transceiver => { - if (!transceiver.mid && transceiver.sender.track && !transceiver.requested) { - transceiver.requested = true // HACK: Safari returns negotiated transceivers with a null mid - this.addTransceiver(transceiver.sender.track.kind) - } - }) - } - } - - _createAnswer () { - if (this.destroyed) return - - this._pc.createAnswer(this.answerOptions) - .then(answer => { - if (this.destroyed) return - if (!this.trickle && !this.allowHalfTrickle) answer.sdp = filterTrickle(answer.sdp) - answer.sdp = this.sdpTransform(answer.sdp) - - const sendAnswer = () => { - if (this.destroyed) return - var signal = this._pc.localDescription || answer - this._debug('signal') - this.emit('signal', { - type: signal.type, - sdp: signal.sdp - }) - if (!this.initiator) this._requestMissingTransceivers() - } - - const onSuccess = () => { - if (this.destroyed) return - if (this.trickle || this._iceComplete) sendAnswer() - else this.once('_iceComplete', sendAnswer) - } - - const onError = err => { - this.destroy(makeError(err, 'ERR_SET_LOCAL_DESCRIPTION')) - } - - this._pc.setLocalDescription(answer) - .then(onSuccess) - .catch(onError) - }) - .catch(err => { - this.destroy(makeError(err, 'ERR_CREATE_ANSWER')) - }) - } - - _onIceStateChange () { - if (this.destroyed) return - var iceConnectionState = this._pc.iceConnectionState - var iceGatheringState = this._pc.iceGatheringState - - this._debug( - 'iceStateChange (connection: %s) (gathering: %s)', - iceConnectionState, - iceGatheringState - ) - this.emit('iceStateChange', iceConnectionState, iceGatheringState) - - if (iceConnectionState === 'connected' || iceConnectionState === 'completed') { - this._pcReady = true - this._maybeReady() - } - if (iceConnectionState === 'failed') { - this.destroy(makeError('Ice connection failed.', 'ERR_ICE_CONNECTION_FAILURE')) - } - if (iceConnectionState === 'closed') { - this.destroy(makeError('Ice connection closed.', 'ERR_ICE_CONNECTION_CLOSED')) - } - } - - getStats (cb) { - // statreports can come with a value array instead of properties - const flattenValues = report => { - if (Object.prototype.toString.call(report.values) === '[object Array]') { - report.values.forEach(value => { - Object.assign(report, value) - }) - } - return report - } - - // Promise-based getStats() (standard) - if (this._pc.getStats.length === 0) { - this._pc.getStats() - .then(res => { - var reports = [] - res.forEach(report => { - reports.push(flattenValues(report)) - }) - cb(null, reports) - }, err => cb(err)) - - // Two-parameter callback-based getStats() (deprecated, former standard) - } else if (this._isReactNativeWebrtc) { - this._pc.getStats(null, res => { - var reports = [] - res.forEach(report => { - reports.push(flattenValues(report)) - }) - cb(null, reports) - }, err => cb(err)) - - // Single-parameter callback-based getStats() (non-standard) - } else if (this._pc.getStats.length > 0) { - this._pc.getStats(res => { - // If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed - if (this.destroyed) return - - var reports = [] - res.result().forEach(result => { - var report = {} - result.names().forEach(name => { - report[name] = result.stat(name) - }) - report.id = result.id - report.type = result.type - report.timestamp = result.timestamp - reports.push(flattenValues(report)) - }) - cb(null, reports) - }, err => cb(err)) - - // Unknown browser, skip getStats() since it's anyone's guess which style of - // getStats() they implement. - } else { - cb(null, []) - } - } - - _maybeReady () { - this._debug('maybeReady pc %s channel %s', this._pcReady, this._channelReady) - if (this._connected || this._connecting || !this._pcReady || !this._channelReady) return - - this._connecting = true - - // HACK: We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339 - const findCandidatePair = () => { - if (this.destroyed) return - - this.getStats((err, items) => { - if (this.destroyed) return - - // Treat getStats error as non-fatal. It's not essential. - if (err) items = [] - - var remoteCandidates = {} - var localCandidates = {} - var candidatePairs = {} - var foundSelectedCandidatePair = false - - items.forEach(item => { - // TODO: Once all browsers support the hyphenated stats report types, remove - // the non-hypenated ones - if (item.type === 'remotecandidate' || item.type === 'remote-candidate') { - remoteCandidates[item.id] = item - } - if (item.type === 'localcandidate' || item.type === 'local-candidate') { - localCandidates[item.id] = item - } - if (item.type === 'candidatepair' || item.type === 'candidate-pair') { - candidatePairs[item.id] = item - } - }) - - const setSelectedCandidatePair = selectedCandidatePair => { - foundSelectedCandidatePair = true - - var local = localCandidates[selectedCandidatePair.localCandidateId] - - if (local && (local.ip || local.address)) { - // Spec - this.localAddress = local.ip || local.address - this.localPort = Number(local.port) - } else if (local && local.ipAddress) { - // Firefox - this.localAddress = local.ipAddress - this.localPort = Number(local.portNumber) - } else if (typeof selectedCandidatePair.googLocalAddress === 'string') { - // TODO: remove this once Chrome 58 is released - local = selectedCandidatePair.googLocalAddress.split(':') - this.localAddress = local[0] - this.localPort = Number(local[1]) - } - if (this.localAddress) { - this.localFamily = this.localAddress.includes(':') ? 'IPv6' : 'IPv4' - } - - var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId] - - if (remote && (remote.ip || remote.address)) { - // Spec - this.remoteAddress = remote.ip || remote.address - this.remotePort = Number(remote.port) - } else if (remote && remote.ipAddress) { - // Firefox - this.remoteAddress = remote.ipAddress - this.remotePort = Number(remote.portNumber) - } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') { - // TODO: remove this once Chrome 58 is released - remote = selectedCandidatePair.googRemoteAddress.split(':') - this.remoteAddress = remote[0] - this.remotePort = Number(remote[1]) - } - if (this.remoteAddress) { - this.remoteFamily = this.remoteAddress.includes(':') ? 'IPv6' : 'IPv4' - } - - this._debug( - 'connect local: %s:%s remote: %s:%s', - this.localAddress, this.localPort, this.remoteAddress, this.remotePort - ) - } - - items.forEach(item => { - // Spec-compliant - if (item.type === 'transport' && item.selectedCandidatePairId) { - setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]) - } - - // Old implementations - if ( - (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') || - ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected) - ) { - setSelectedCandidatePair(item) - } - }) - - // Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates - // But wait until at least 1 candidate pair is available - if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) { - setTimeout(findCandidatePair, 100) - return - } else { - this._connecting = false - this._connected = true - } - - if (this._chunk) { - try { - this.send(this._chunk) - } catch (err) { - return this.destroy(makeError(err, 'ERR_DATA_CHANNEL')) - } - this._chunk = null - this._debug('sent chunk from "write before connect"') - - var cb = this._cb - this._cb = null - cb(null) - } - - // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported, - // fallback to using setInterval to implement backpressure. - if (typeof this._channel.bufferedAmountLowThreshold !== 'number') { - this._interval = setInterval(() => this._onInterval(), 150) - if (this._interval.unref) this._interval.unref() - } - - this._debug('connect') - this.emit('connect') - }) - } - findCandidatePair() - } - - _onInterval () { - if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { - return - } - this._onChannelBufferedAmountLow() - } - - _onSignalingStateChange () { - if (this.destroyed) return - - if (this._pc.signalingState === 'stable' && !this._firstStable) { - this._isNegotiating = false - - // HACK: Firefox doesn't yet support removing tracks when signalingState !== 'stable' - this._debug('flushing sender queue', this._sendersAwaitingStable) - this._sendersAwaitingStable.forEach(sender => { - this._pc.removeTrack(sender) - this._queuedNegotiation = true - }) - this._sendersAwaitingStable = [] - - if (this._queuedNegotiation) { - this._debug('flushing negotiation queue') - this._queuedNegotiation = false - this._needsNegotiation() // negotiate again - } - - this._debug('negotiate') - this.emit('negotiate') - } - this._firstStable = false - - this._debug('signalingStateChange %s', this._pc.signalingState) - this.emit('signalingStateChange', this._pc.signalingState) - } - - _onIceCandidate (event) { - if (this.destroyed) return - if (event.candidate && this.trickle) { - this.emit('signal', { - candidate: { - candidate: event.candidate.candidate, - sdpMLineIndex: event.candidate.sdpMLineIndex, - sdpMid: event.candidate.sdpMid - } - }) - } else if (!event.candidate && !this._iceComplete) { - this._iceComplete = true - this.emit('_iceComplete') - } - // as soon as we've received one valid candidate start timeout - if (event.candidate) { - this._startIceCompleteTimeout() - } - } - - _onChannelMessage (event) { - if (this.destroyed) return - var data = event.data - if (data instanceof ArrayBuffer) data = Buffer.from(data) - this.push(data) - } - - _onChannelBufferedAmountLow () { - if (this.destroyed || !this._cb) return - this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount) - var cb = this._cb - this._cb = null - cb(null) - } - - _onChannelOpen () { - if (this._connected || this.destroyed) return - this._debug('on channel open') - this._channelReady = true - this._maybeReady() - } - - _onChannelClose () { - if (this.destroyed) return - this._debug('on channel close') - this.destroy() - } - - _onTrack (event) { - if (this.destroyed) return - - event.streams.forEach(eventStream => { - this._debug('on track') - this.emit('track', event.track, eventStream) - - this._remoteTracks.push({ - track: event.track, - stream: eventStream - }) - - if (this._remoteStreams.some(remoteStream => { - return remoteStream.id === eventStream.id - })) return // Only fire one 'stream' event, even though there may be multiple tracks per stream - - this._remoteStreams.push(eventStream) - queueMicrotask(() => { - this.emit('stream', eventStream) // ensure all tracks have been added - }) - }) - } - - _debug () { - var args = [].slice.call(arguments) - args[0] = '[' + this._id + '] ' + args[0] - debug.apply(null, args) - } -} - -Peer.WEBRTC_SUPPORT = !!getBrowserRTC() - -/** - * Expose peer and data channel config for overriding all Peer - * instances. Otherwise, just set opts.config or opts.channelConfig - * when constructing a Peer. - */ -Peer.config = { - iceServers: [ - { - urls: 'stun:stun.l.google.com:19302' - }, - { - urls: 'stun:global.stun.twilio.com:3478?transport=udp' - } - ], - sdpSemantics: 'unified-plan' -} - -Peer.channelConfig = {} - -module.exports = Peer - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"debug":1634,"get-browser-rtc":387,"queue-microtask":1548,"randombytes":1552,"readable-stream":1651}],1634:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1635,"_process":1438,"dup":247}],1635:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1636}],1636:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1637:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],1638:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],1639:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":1641,"./_stream_writable":1643,"_process":1438,"dup":90,"inherits":453}],1640:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":1642,"dup":91,"inherits":453}],1641:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":1637,"../experimentalWarning":1638,"./_stream_duplex":1639,"./internal/streams/async_iterator":1644,"./internal/streams/buffer_list":1645,"./internal/streams/destroy":1646,"./internal/streams/state":1649,"./internal/streams/stream":1650,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],1642:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":1637,"./_stream_duplex":1639,"dup":93,"inherits":453}],1643:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":1637,"./_stream_duplex":1639,"./internal/streams/destroy":1646,"./internal/streams/state":1649,"./internal/streams/stream":1650,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],1644:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":1647,"_process":1438,"dup":95}],1645:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],1646:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],1647:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":1637,"dup":98}],1648:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":1637,"./end-of-stream":1647,"dup":99}],1649:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":1637,"dup":100}],1650:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],1651:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":1639,"./lib/_stream_passthrough.js":1640,"./lib/_stream_readable.js":1641,"./lib/_stream_transform.js":1642,"./lib/_stream_writable.js":1643,"./lib/internal/streams/end-of-stream.js":1647,"./lib/internal/streams/pipeline.js":1648,"dup":102}],1652:[function(require,module,exports){ - -/** - * Module dependencies. - */ - -var url = require('./url'); -var parser = require('socket.io-parser'); -var Manager = require('./manager'); -var debug = require('debug')('socket.io-client'); - -/** - * Module exports. - */ - -module.exports = exports = lookup; - -/** - * Managers cache. - */ - -var cache = exports.managers = {}; - -/** - * Looks up an existing `Manager` for multiplexing. - * If the user summons: - * - * `io('http://localhost/a');` - * `io('http://localhost/b');` - * - * We reuse the existing instance based on same scheme/port/host, - * and we initialize sockets for each namespace. - * - * @api public - */ - -function lookup (uri, opts) { - if (typeof uri === 'object') { - opts = uri; - uri = undefined; - } - - opts = opts || {}; - - var parsed = url(uri); - var source = parsed.source; - var id = parsed.id; - var path = parsed.path; - var sameNamespace = cache[id] && path in cache[id].nsps; - var newConnection = opts.forceNew || opts['force new connection'] || - false === opts.multiplex || sameNamespace; - - var io; - - if (newConnection) { - debug('ignoring socket cache for %s', source); - io = Manager(source, opts); - } else { - if (!cache[id]) { - debug('new io instance for %s', source); - cache[id] = Manager(source, opts); - } - io = cache[id]; - } - if (parsed.query && !opts.query) { - opts.query = parsed.query; - } - return io.socket(parsed.path, opts); -} - -/** - * Protocol version. - * - * @api public - */ - -exports.protocol = parser.protocol; - -/** - * `connect`. - * - * @param {String} uri - * @api public - */ - -exports.connect = lookup; - -/** - * Expose constructors for standalone build. - * - * @api public - */ - -exports.Manager = require('./manager'); -exports.Socket = require('./socket'); - -},{"./manager":1653,"./socket":1655,"./url":1656,"debug":1657,"socket.io-parser":1662}],1653:[function(require,module,exports){ - -/** - * Module dependencies. - */ - -var eio = require('engine.io-client'); -var Socket = require('./socket'); -var Emitter = require('component-emitter'); -var parser = require('socket.io-parser'); -var on = require('./on'); -var bind = require('component-bind'); -var debug = require('debug')('socket.io-client:manager'); -var indexOf = require('indexof'); -var Backoff = require('backo2'); - -/** - * IE6+ hasOwnProperty - */ - -var has = Object.prototype.hasOwnProperty; - -/** - * Module exports - */ - -module.exports = Manager; - -/** - * `Manager` constructor. - * - * @param {String} engine instance or engine uri/opts - * @param {Object} options - * @api public - */ - -function Manager (uri, opts) { - if (!(this instanceof Manager)) return new Manager(uri, opts); - if (uri && ('object' === typeof uri)) { - opts = uri; - uri = undefined; - } - opts = opts || {}; - - opts.path = opts.path || '/socket.io'; - this.nsps = {}; - this.subs = []; - this.opts = opts; - this.reconnection(opts.reconnection !== false); - this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - this.reconnectionDelay(opts.reconnectionDelay || 1000); - this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - this.randomizationFactor(opts.randomizationFactor || 0.5); - this.backoff = new Backoff({ - min: this.reconnectionDelay(), - max: this.reconnectionDelayMax(), - jitter: this.randomizationFactor() - }); - this.timeout(null == opts.timeout ? 20000 : opts.timeout); - this.readyState = 'closed'; - this.uri = uri; - this.connecting = []; - this.lastPing = null; - this.encoding = false; - this.packetBuffer = []; - var _parser = opts.parser || parser; - this.encoder = new _parser.Encoder(); - this.decoder = new _parser.Decoder(); - this.autoConnect = opts.autoConnect !== false; - if (this.autoConnect) this.open(); -} - -/** - * Propagate given event to sockets and emit on `this` - * - * @api private - */ - -Manager.prototype.emitAll = function () { - this.emit.apply(this, arguments); - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); - } - } -}; - -/** - * Update `socket.id` of all sockets - * - * @api private - */ - -Manager.prototype.updateSocketIds = function () { - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].id = this.generateId(nsp); - } - } -}; - -/** - * generate `socket.id` for the given `nsp` - * - * @param {String} nsp - * @return {String} - * @api private - */ - -Manager.prototype.generateId = function (nsp) { - return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id; -}; - -/** - * Mix in `Emitter`. - */ - -Emitter(Manager.prototype); - -/** - * Sets the `reconnection` config. - * - * @param {Boolean} true/false if it should automatically reconnect - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnection = function (v) { - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; -}; - -/** - * Sets the reconnection attempts config. - * - * @param {Number} max reconnection attempts before giving up - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionAttempts = function (v) { - if (!arguments.length) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; -}; - -/** - * Sets the delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionDelay = function (v) { - if (!arguments.length) return this._reconnectionDelay; - this._reconnectionDelay = v; - this.backoff && this.backoff.setMin(v); - return this; -}; - -Manager.prototype.randomizationFactor = function (v) { - if (!arguments.length) return this._randomizationFactor; - this._randomizationFactor = v; - this.backoff && this.backoff.setJitter(v); - return this; -}; - -/** - * Sets the maximum delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionDelayMax = function (v) { - if (!arguments.length) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - this.backoff && this.backoff.setMax(v); - return this; -}; - -/** - * Sets the connection timeout. `false` to disable - * - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.timeout = function (v) { - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; -}; - -/** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @api private - */ - -Manager.prototype.maybeReconnectOnOpen = function () { - // Only try to reconnect if it's the first time we're connecting - if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } -}; - -/** - * Sets the current transport `socket`. - * - * @param {Function} optional, callback - * @return {Manager} self - * @api public - */ - -Manager.prototype.open = -Manager.prototype.connect = function (fn, opts) { - debug('readyState %s', this.readyState); - if (~this.readyState.indexOf('open')) return this; - - debug('opening %s', this.uri); - this.engine = eio(this.uri, this.opts); - var socket = this.engine; - var self = this; - this.readyState = 'opening'; - this.skipReconnect = false; - - // emit `open` - var openSub = on(socket, 'open', function () { - self.onopen(); - fn && fn(); - }); - - // emit `connect_error` - var errorSub = on(socket, 'error', function (data) { - debug('connect_error'); - self.cleanup(); - self.readyState = 'closed'; - self.emitAll('connect_error', data); - if (fn) { - var err = new Error('Connection error'); - err.data = data; - fn(err); - } else { - // Only do this if there is no fn to handle the error - self.maybeReconnectOnOpen(); - } - }); - - // emit `connect_timeout` - if (false !== this._timeout) { - var timeout = this._timeout; - debug('connect attempt will timeout after %d', timeout); - - // set timer - var timer = setTimeout(function () { - debug('connect attempt timed out after %d', timeout); - openSub.destroy(); - socket.close(); - socket.emit('error', 'timeout'); - self.emitAll('connect_timeout', timeout); - }, timeout); - - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); - } - - this.subs.push(openSub); - this.subs.push(errorSub); - - return this; -}; - -/** - * Called upon transport open. - * - * @api private - */ - -Manager.prototype.onopen = function () { - debug('open'); - - // clear old subs - this.cleanup(); - - // mark as open - this.readyState = 'open'; - this.emit('open'); - - // add new subs - var socket = this.engine; - this.subs.push(on(socket, 'data', bind(this, 'ondata'))); - this.subs.push(on(socket, 'ping', bind(this, 'onping'))); - this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); - this.subs.push(on(socket, 'error', bind(this, 'onerror'))); - this.subs.push(on(socket, 'close', bind(this, 'onclose'))); - this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); -}; - -/** - * Called upon a ping. - * - * @api private - */ - -Manager.prototype.onping = function () { - this.lastPing = new Date(); - this.emitAll('ping'); -}; - -/** - * Called upon a packet. - * - * @api private - */ - -Manager.prototype.onpong = function () { - this.emitAll('pong', new Date() - this.lastPing); -}; - -/** - * Called with data. - * - * @api private - */ - -Manager.prototype.ondata = function (data) { - this.decoder.add(data); -}; - -/** - * Called when parser fully decodes a packet. - * - * @api private - */ - -Manager.prototype.ondecoded = function (packet) { - this.emit('packet', packet); -}; - -/** - * Called upon socket error. - * - * @api private - */ - -Manager.prototype.onerror = function (err) { - debug('error', err); - this.emitAll('error', err); -}; - -/** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @api public - */ - -Manager.prototype.socket = function (nsp, opts) { - var socket = this.nsps[nsp]; - if (!socket) { - socket = new Socket(this, nsp, opts); - this.nsps[nsp] = socket; - var self = this; - socket.on('connecting', onConnecting); - socket.on('connect', function () { - socket.id = self.generateId(nsp); - }); - - if (this.autoConnect) { - // manually call here since connecting event is fired before listening - onConnecting(); - } - } - - function onConnecting () { - if (!~indexOf(self.connecting, socket)) { - self.connecting.push(socket); - } - } - - return socket; -}; - -/** - * Called upon a socket close. - * - * @param {Socket} socket - */ - -Manager.prototype.destroy = function (socket) { - var index = indexOf(this.connecting, socket); - if (~index) this.connecting.splice(index, 1); - if (this.connecting.length) return; - - this.close(); -}; - -/** - * Writes a packet. - * - * @param {Object} packet - * @api private - */ - -Manager.prototype.packet = function (packet) { - debug('writing packet %j', packet); - var self = this; - if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; - - if (!self.encoding) { - // encode, then write to engine with result - self.encoding = true; - this.encoder.encode(packet, function (encodedPackets) { - for (var i = 0; i < encodedPackets.length; i++) { - self.engine.write(encodedPackets[i], packet.options); - } - self.encoding = false; - self.processPacketQueue(); - }); - } else { // add packet to the queue - self.packetBuffer.push(packet); - } -}; - -/** - * If packet buffer is non-empty, begins encoding the - * next packet in line. - * - * @api private - */ - -Manager.prototype.processPacketQueue = function () { - if (this.packetBuffer.length > 0 && !this.encoding) { - var pack = this.packetBuffer.shift(); - this.packet(pack); - } -}; - -/** - * Clean up transport subscriptions and packet buffer. - * - * @api private - */ - -Manager.prototype.cleanup = function () { - debug('cleanup'); - - var subsLength = this.subs.length; - for (var i = 0; i < subsLength; i++) { - var sub = this.subs.shift(); - sub.destroy(); - } - - this.packetBuffer = []; - this.encoding = false; - this.lastPing = null; - - this.decoder.destroy(); -}; - -/** - * Close the current socket. - * - * @api private - */ - -Manager.prototype.close = -Manager.prototype.disconnect = function () { - debug('disconnect'); - this.skipReconnect = true; - this.reconnecting = false; - if ('opening' === this.readyState) { - // `onclose` will not fire because - // an open event never happened - this.cleanup(); - } - this.backoff.reset(); - this.readyState = 'closed'; - if (this.engine) this.engine.close(); -}; - -/** - * Called upon engine close. - * - * @api private - */ - -Manager.prototype.onclose = function (reason) { - debug('onclose'); - - this.cleanup(); - this.backoff.reset(); - this.readyState = 'closed'; - this.emit('close', reason); - - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } -}; - -/** - * Attempt a reconnection. - * - * @api private - */ - -Manager.prototype.reconnect = function () { - if (this.reconnecting || this.skipReconnect) return this; - - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug('reconnect failed'); - this.backoff.reset(); - this.emitAll('reconnect_failed'); - this.reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug('will wait %dms before reconnect attempt', delay); - - this.reconnecting = true; - var timer = setTimeout(function () { - if (self.skipReconnect) return; - - debug('attempting reconnect'); - self.emitAll('reconnect_attempt', self.backoff.attempts); - self.emitAll('reconnecting', self.backoff.attempts); - - // check again for the case socket closed in above events - if (self.skipReconnect) return; - - self.open(function (err) { - if (err) { - debug('reconnect attempt error'); - self.reconnecting = false; - self.reconnect(); - self.emitAll('reconnect_error', err.data); - } else { - debug('reconnect success'); - self.onreconnect(); - } - }); - }, delay); - - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); - } -}; - -/** - * Called upon successful reconnect. - * - * @api private - */ - -Manager.prototype.onreconnect = function () { - var attempt = this.backoff.attempts; - this.reconnecting = false; - this.backoff.reset(); - this.updateSocketIds(); - this.emitAll('reconnect', attempt); -}; - -},{"./on":1654,"./socket":1655,"backo2":157,"component-bind":226,"component-emitter":227,"debug":1657,"engine.io-client":300,"indexof":452,"socket.io-parser":1662}],1654:[function(require,module,exports){ - -/** - * Module exports. - */ - -module.exports = on; - -/** - * Helper for subscriptions. - * - * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` - * @param {String} event name - * @param {Function} callback - * @api public - */ - -function on (obj, ev, fn) { - obj.on(ev, fn); - return { - destroy: function () { - obj.removeListener(ev, fn); - } - }; -} - -},{}],1655:[function(require,module,exports){ - -/** - * Module dependencies. - */ - -var parser = require('socket.io-parser'); -var Emitter = require('component-emitter'); -var toArray = require('to-array'); -var on = require('./on'); -var bind = require('component-bind'); -var debug = require('debug')('socket.io-client:socket'); -var parseqs = require('parseqs'); -var hasBin = require('has-binary2'); - -/** - * Module exports. - */ - -module.exports = exports = Socket; - -/** - * Internal events (blacklisted). - * These events can't be emitted by the user. - * - * @api private - */ - -var events = { - connect: 1, - connect_error: 1, - connect_timeout: 1, - connecting: 1, - disconnect: 1, - error: 1, - reconnect: 1, - reconnect_attempt: 1, - reconnect_failed: 1, - reconnect_error: 1, - reconnecting: 1, - ping: 1, - pong: 1 -}; - -/** - * Shortcut to `Emitter#emit`. - */ - -var emit = Emitter.prototype.emit; - -/** - * `Socket` constructor. - * - * @api public - */ - -function Socket (io, nsp, opts) { - this.io = io; - this.nsp = nsp; - this.json = this; // compat - this.ids = 0; - this.acks = {}; - this.receiveBuffer = []; - this.sendBuffer = []; - this.connected = false; - this.disconnected = true; - this.flags = {}; - if (opts && opts.query) { - this.query = opts.query; - } - if (this.io.autoConnect) this.open(); -} - -/** - * Mix in `Emitter`. - */ - -Emitter(Socket.prototype); - -/** - * Subscribe to open, close and packet events - * - * @api private - */ - -Socket.prototype.subEvents = function () { - if (this.subs) return; - - var io = this.io; - this.subs = [ - on(io, 'open', bind(this, 'onopen')), - on(io, 'packet', bind(this, 'onpacket')), - on(io, 'close', bind(this, 'onclose')) - ]; -}; - -/** - * "Opens" the socket. - * - * @api public - */ - -Socket.prototype.open = -Socket.prototype.connect = function () { - if (this.connected) return this; - - this.subEvents(); - this.io.open(); // ensure open - if ('open' === this.io.readyState) this.onopen(); - this.emit('connecting'); - return this; -}; - -/** - * Sends a `message` event. - * - * @return {Socket} self - * @api public - */ - -Socket.prototype.send = function () { - var args = toArray(arguments); - args.unshift('message'); - this.emit.apply(this, args); - return this; -}; - -/** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param {String} event name - * @return {Socket} self - * @api public - */ - -Socket.prototype.emit = function (ev) { - if (events.hasOwnProperty(ev)) { - emit.apply(this, arguments); - return this; - } - - var args = toArray(arguments); - var packet = { - type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT, - data: args - }; - - packet.options = {}; - packet.options.compress = !this.flags || false !== this.flags.compress; - - // event ack callback - if ('function' === typeof args[args.length - 1]) { - debug('emitting packet with ack id %d', this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; - } - - if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - - this.flags = {}; - - return this; -}; - -/** - * Sends a packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.packet = function (packet) { - packet.nsp = this.nsp; - this.io.packet(packet); -}; - -/** - * Called upon engine `open`. - * - * @api private - */ - -Socket.prototype.onopen = function () { - debug('transport is open - connecting'); - - // write connect packet if necessary - if ('/' !== this.nsp) { - if (this.query) { - var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query; - debug('sending connect packet with query %s', query); - this.packet({type: parser.CONNECT, query: query}); - } else { - this.packet({type: parser.CONNECT}); - } - } -}; - -/** - * Called upon engine `close`. - * - * @param {String} reason - * @api private - */ - -Socket.prototype.onclose = function (reason) { - debug('close (%s)', reason); - this.connected = false; - this.disconnected = true; - delete this.id; - this.emit('disconnect', reason); -}; - -/** - * Called with socket packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onpacket = function (packet) { - var sameNamespace = packet.nsp === this.nsp; - var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/'; - - if (!sameNamespace && !rootNamespaceError) return; - - switch (packet.type) { - case parser.CONNECT: - this.onconnect(); - break; - - case parser.EVENT: - this.onevent(packet); - break; - - case parser.BINARY_EVENT: - this.onevent(packet); - break; - - case parser.ACK: - this.onack(packet); - break; - - case parser.BINARY_ACK: - this.onack(packet); - break; - - case parser.DISCONNECT: - this.ondisconnect(); - break; - - case parser.ERROR: - this.emit('error', packet.data); - break; - } -}; - -/** - * Called upon a server event. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onevent = function (packet) { - var args = packet.data || []; - debug('emitting event %j', args); - - if (null != packet.id) { - debug('attaching ack callback to event'); - args.push(this.ack(packet.id)); - } - - if (this.connected) { - emit.apply(this, args); - } else { - this.receiveBuffer.push(args); - } -}; - -/** - * Produces an ack callback to emit with an event. - * - * @api private - */ - -Socket.prototype.ack = function (id) { - var self = this; - var sent = false; - return function () { - // prevent double callbacks - if (sent) return; - sent = true; - var args = toArray(arguments); - debug('sending ack %j', args); - - self.packet({ - type: hasBin(args) ? parser.BINARY_ACK : parser.ACK, - id: id, - data: args - }); - }; -}; - -/** - * Called upon a server acknowlegement. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onack = function (packet) { - var ack = this.acks[packet.id]; - if ('function' === typeof ack) { - debug('calling ack %s with %j', packet.id, packet.data); - ack.apply(this, packet.data); - delete this.acks[packet.id]; - } else { - debug('bad ack %s', packet.id); - } -}; - -/** - * Called upon server connect. - * - * @api private - */ - -Socket.prototype.onconnect = function () { - this.connected = true; - this.disconnected = false; - this.emit('connect'); - this.emitBuffered(); -}; - -/** - * Emit buffered events (received and emitted). - * - * @api private - */ - -Socket.prototype.emitBuffered = function () { - var i; - for (i = 0; i < this.receiveBuffer.length; i++) { - emit.apply(this, this.receiveBuffer[i]); - } - this.receiveBuffer = []; - - for (i = 0; i < this.sendBuffer.length; i++) { - this.packet(this.sendBuffer[i]); - } - this.sendBuffer = []; -}; - -/** - * Called upon server disconnect. - * - * @api private - */ - -Socket.prototype.ondisconnect = function () { - debug('server disconnect (%s)', this.nsp); - this.destroy(); - this.onclose('io server disconnect'); -}; - -/** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @api private. - */ - -Socket.prototype.destroy = function () { - if (this.subs) { - // clean subscriptions to avoid reconnections - for (var i = 0; i < this.subs.length; i++) { - this.subs[i].destroy(); - } - this.subs = null; - } - - this.io.destroy(this); -}; - -/** - * Disconnects the socket manually. - * - * @return {Socket} self - * @api public - */ - -Socket.prototype.close = -Socket.prototype.disconnect = function () { - if (this.connected) { - debug('performing disconnect (%s)', this.nsp); - this.packet({ type: parser.DISCONNECT }); - } - - // remove socket from pool - this.destroy(); - - if (this.connected) { - // fire events - this.onclose('io client disconnect'); - } - return this; -}; - -/** - * Sets the compress flag. - * - * @param {Boolean} if `true`, compresses the sending data - * @return {Socket} self - * @api public - */ - -Socket.prototype.compress = function (compress) { - this.flags.compress = compress; - return this; -}; - -/** - * Sets the binary flag - * - * @param {Boolean} whether the emitted data contains binary - * @return {Socket} self - * @api public - */ - -Socket.prototype.binary = function (binary) { - this.flags.binary = binary; - return this; -}; - -},{"./on":1654,"component-bind":226,"component-emitter":227,"debug":1657,"has-binary2":419,"parseqs":1423,"socket.io-parser":1662,"to-array":1751}],1656:[function(require,module,exports){ - -/** - * Module dependencies. - */ - -var parseuri = require('parseuri'); -var debug = require('debug')('socket.io-client:url'); - -/** - * Module exports. - */ - -module.exports = url; - -/** - * URL parser. - * - * @param {String} url - * @param {Object} An object meant to mimic window.location. - * Defaults to window.location. - * @api public - */ - -function url (uri, loc) { - var obj = uri; - - // default to window.location - loc = loc || (typeof location !== 'undefined' && location); - if (null == uri) uri = loc.protocol + '//' + loc.host; - - // relative path support - if ('string' === typeof uri) { - if ('/' === uri.charAt(0)) { - if ('/' === uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.host + uri; - } - } - - if (!/^(https?|wss?):\/\//.test(uri)) { - debug('protocol-less url %s', uri); - if ('undefined' !== typeof loc) { - uri = loc.protocol + '//' + uri; - } else { - uri = 'https://' + uri; - } - } - - // parse - debug('parse %s', uri); - obj = parseuri(uri); - } - - // make sure we treat `localhost:80` and `localhost` equally - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = '80'; - } else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = '443'; - } - } - - obj.path = obj.path || '/'; - - var ipv6 = obj.host.indexOf(':') !== -1; - var host = ipv6 ? '[' + obj.host + ']' : obj.host; - - // define unique id - obj.id = obj.protocol + '://' + host + ':' + obj.port; - // define href - obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port)); - - return obj; -} - -},{"debug":1657,"parseuri":1424}],1657:[function(require,module,exports){ -arguments[4][247][0].apply(exports,arguments) -},{"./common":1658,"_process":1438,"dup":247}],1658:[function(require,module,exports){ -arguments[4][248][0].apply(exports,arguments) -},{"dup":248,"ms":1660}],1659:[function(require,module,exports){ -arguments[4][420][0].apply(exports,arguments) -},{"dup":420}],1660:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1661:[function(require,module,exports){ -/*global Blob,File*/ - -/** - * Module requirements - */ - -var isArray = require('isarray'); -var isBuf = require('./is-buffer'); -var toString = Object.prototype.toString; -var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'); -var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'); - -/** - * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. - * Anything with blobs or files should be fed through removeBlobs before coming - * here. - * - * @param {Object} packet - socket.io event packet - * @return {Object} with deconstructed packet and list of buffers - * @api public - */ - -exports.deconstructPacket = function(packet) { - var buffers = []; - var packetData = packet.data; - var pack = packet; - pack.data = _deconstructPacket(packetData, buffers); - pack.attachments = buffers.length; // number of binary 'attachments' - return {packet: pack, buffers: buffers}; -}; - -function _deconstructPacket(data, buffers) { - if (!data) return data; - - if (isBuf(data)) { - var placeholder = { _placeholder: true, num: buffers.length }; - buffers.push(data); - return placeholder; - } else if (isArray(data)) { - var newData = new Array(data.length); - for (var i = 0; i < data.length; i++) { - newData[i] = _deconstructPacket(data[i], buffers); - } - return newData; - } else if (typeof data === 'object' && !(data instanceof Date)) { - var newData = {}; - for (var key in data) { - newData[key] = _deconstructPacket(data[key], buffers); - } - return newData; - } - return data; -} - -/** - * Reconstructs a binary packet from its placeholder packet and buffers - * - * @param {Object} packet - event packet with placeholders - * @param {Array} buffers - binary buffers to put in placeholder positions - * @return {Object} reconstructed packet - * @api public - */ - -exports.reconstructPacket = function(packet, buffers) { - packet.data = _reconstructPacket(packet.data, buffers); - packet.attachments = undefined; // no longer useful - return packet; -}; - -function _reconstructPacket(data, buffers) { - if (!data) return data; - - if (data && data._placeholder) { - return buffers[data.num]; // appropriate buffer (should be natural order anyway) - } else if (isArray(data)) { - for (var i = 0; i < data.length; i++) { - data[i] = _reconstructPacket(data[i], buffers); - } - } else if (typeof data === 'object') { - for (var key in data) { - data[key] = _reconstructPacket(data[key], buffers); - } - } - - return data; -} - -/** - * Asynchronously removes Blobs or Files from data via - * FileReader's readAsArrayBuffer method. Used before encoding - * data as msgpack. Calls callback with the blobless data. - * - * @param {Object} data - * @param {Function} callback - * @api private - */ - -exports.removeBlobs = function(data, callback) { - function _removeBlobs(obj, curKey, containingObject) { - if (!obj) return obj; - - // convert any blob - if ((withNativeBlob && obj instanceof Blob) || - (withNativeFile && obj instanceof File)) { - pendingBlobs++; - - // async filereader - var fileReader = new FileReader(); - fileReader.onload = function() { // this.result == arraybuffer - if (containingObject) { - containingObject[curKey] = this.result; - } - else { - bloblessData = this.result; - } - - // if nothing pending its callback time - if(! --pendingBlobs) { - callback(bloblessData); - } - }; - - fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer - } else if (isArray(obj)) { // handle array - for (var i = 0; i < obj.length; i++) { - _removeBlobs(obj[i], i, obj); - } - } else if (typeof obj === 'object' && !isBuf(obj)) { // and object - for (var key in obj) { - _removeBlobs(obj[key], key, obj); - } - } - } - - var pendingBlobs = 0; - var bloblessData = data; - _removeBlobs(bloblessData); - if (!pendingBlobs) { - callback(bloblessData); - } -}; - -},{"./is-buffer":1663,"isarray":1659}],1662:[function(require,module,exports){ - -/** - * Module dependencies. - */ - -var debug = require('debug')('socket.io-parser'); -var Emitter = require('component-emitter'); -var binary = require('./binary'); -var isArray = require('isarray'); -var isBuf = require('./is-buffer'); - -/** - * Protocol version. - * - * @api public - */ - -exports.protocol = 4; - -/** - * Packet types. - * - * @api public - */ - -exports.types = [ - 'CONNECT', - 'DISCONNECT', - 'EVENT', - 'ACK', - 'ERROR', - 'BINARY_EVENT', - 'BINARY_ACK' -]; - -/** - * Packet type `connect`. - * - * @api public - */ - -exports.CONNECT = 0; - -/** - * Packet type `disconnect`. - * - * @api public - */ - -exports.DISCONNECT = 1; - -/** - * Packet type `event`. - * - * @api public - */ - -exports.EVENT = 2; - -/** - * Packet type `ack`. - * - * @api public - */ - -exports.ACK = 3; - -/** - * Packet type `error`. - * - * @api public - */ - -exports.ERROR = 4; - -/** - * Packet type 'binary event' - * - * @api public - */ - -exports.BINARY_EVENT = 5; - -/** - * Packet type `binary ack`. For acks with binary arguments. - * - * @api public - */ - -exports.BINARY_ACK = 6; - -/** - * Encoder constructor. - * - * @api public - */ - -exports.Encoder = Encoder; - -/** - * Decoder constructor. - * - * @api public - */ - -exports.Decoder = Decoder; - -/** - * A socket.io Encoder instance - * - * @api public - */ - -function Encoder() {} - -var ERROR_PACKET = exports.ERROR + '"encode error"'; - -/** - * Encode a packet as a single string if non-binary, or as a - * buffer sequence, depending on packet type. - * - * @param {Object} obj - packet object - * @param {Function} callback - function to handle encodings (likely engine.write) - * @return Calls callback with Array of encodings - * @api public - */ - -Encoder.prototype.encode = function(obj, callback){ - debug('encoding packet %j', obj); - - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - encodeAsBinary(obj, callback); - } else { - var encoding = encodeAsString(obj); - callback([encoding]); - } -}; - -/** - * Encode packet as string. - * - * @param {Object} packet - * @return {String} encoded - * @api private - */ - -function encodeAsString(obj) { - - // first is type - var str = '' + obj.type; - - // attachments if we have them - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - str += obj.attachments + '-'; - } - - // if we have a namespace other than `/` - // we append it followed by a comma `,` - if (obj.nsp && '/' !== obj.nsp) { - str += obj.nsp + ','; - } - - // immediately followed by the id - if (null != obj.id) { - str += obj.id; - } - - // json data - if (null != obj.data) { - var payload = tryStringify(obj.data); - if (payload !== false) { - str += payload; - } else { - return ERROR_PACKET; - } - } - - debug('encoded %j as %s', obj, str); - return str; -} - -function tryStringify(str) { - try { - return JSON.stringify(str); - } catch(e){ - return false; - } -} - -/** - * Encode packet as 'buffer sequence' by removing blobs, and - * deconstructing packet into object with placeholders and - * a list of buffers. - * - * @param {Object} packet - * @return {Buffer} encoded - * @api private - */ - -function encodeAsBinary(obj, callback) { - - function writeEncoding(bloblessData) { - var deconstruction = binary.deconstructPacket(bloblessData); - var pack = encodeAsString(deconstruction.packet); - var buffers = deconstruction.buffers; - - buffers.unshift(pack); // add packet info to beginning of data list - callback(buffers); // write all the buffers - } - - binary.removeBlobs(obj, writeEncoding); -} - -/** - * A socket.io Decoder instance - * - * @return {Object} decoder - * @api public - */ - -function Decoder() { - this.reconstructor = null; -} - -/** - * Mix in `Emitter` with Decoder. - */ - -Emitter(Decoder.prototype); - -/** - * Decodes an encoded packet string into packet JSON. - * - * @param {String} obj - encoded packet - * @return {Object} packet - * @api public - */ - -Decoder.prototype.add = function(obj) { - var packet; - if (typeof obj === 'string') { - packet = decodeString(obj); - if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json - this.reconstructor = new BinaryReconstructor(packet); - - // no attachments, labeled binary but no binary data to follow - if (this.reconstructor.reconPack.attachments === 0) { - this.emit('decoded', packet); - } - } else { // non-binary full packet - this.emit('decoded', packet); - } - } else if (isBuf(obj) || obj.base64) { // raw binary data - if (!this.reconstructor) { - throw new Error('got binary data when not reconstructing a packet'); - } else { - packet = this.reconstructor.takeBinaryData(obj); - if (packet) { // received final buffer - this.reconstructor = null; - this.emit('decoded', packet); - } - } - } else { - throw new Error('Unknown type: ' + obj); - } -}; - -/** - * Decode a packet String (JSON data) - * - * @param {String} str - * @return {Object} packet - * @api private - */ - -function decodeString(str) { - var i = 0; - // look up type - var p = { - type: Number(str.charAt(0)) - }; - - if (null == exports.types[p.type]) { - return error('unknown packet type ' + p.type); - } - - // look up attachments if type binary - if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { - var buf = ''; - while (str.charAt(++i) !== '-') { - buf += str.charAt(i); - if (i == str.length) break; - } - if (buf != Number(buf) || str.charAt(i) !== '-') { - throw new Error('Illegal attachments'); - } - p.attachments = Number(buf); - } - - // look up namespace (if any) - if ('/' === str.charAt(i + 1)) { - p.nsp = ''; - while (++i) { - var c = str.charAt(i); - if (',' === c) break; - p.nsp += c; - if (i === str.length) break; - } - } else { - p.nsp = '/'; - } - - // look up id - var next = str.charAt(i + 1); - if ('' !== next && Number(next) == next) { - p.id = ''; - while (++i) { - var c = str.charAt(i); - if (null == c || Number(c) != c) { - --i; - break; - } - p.id += str.charAt(i); - if (i === str.length) break; - } - p.id = Number(p.id); - } - - // look up json data - if (str.charAt(++i)) { - var payload = tryParse(str.substr(i)); - var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload)); - if (isPayloadValid) { - p.data = payload; - } else { - return error('invalid payload'); - } - } - - debug('decoded %s as %j', str, p); - return p; -} - -function tryParse(str) { - try { - return JSON.parse(str); - } catch(e){ - return false; - } -} - -/** - * Deallocates a parser's resources - * - * @api public - */ - -Decoder.prototype.destroy = function() { - if (this.reconstructor) { - this.reconstructor.finishedReconstruction(); - } -}; - -/** - * A manager of a binary event's 'buffer sequence'. Should - * be constructed whenever a packet of type BINARY_EVENT is - * decoded. - * - * @param {Object} packet - * @return {BinaryReconstructor} initialized reconstructor - * @api private - */ - -function BinaryReconstructor(packet) { - this.reconPack = packet; - this.buffers = []; -} - -/** - * Method to be called when binary data received from connection - * after a BINARY_EVENT packet. - * - * @param {Buffer | ArrayBuffer} binData - the raw binary data received - * @return {null | Object} returns null if more binary data is expected or - * a reconstructed packet object if all buffers have been received. - * @api private - */ - -BinaryReconstructor.prototype.takeBinaryData = function(binData) { - this.buffers.push(binData); - if (this.buffers.length === this.reconPack.attachments) { // done with buffer list - var packet = binary.reconstructPacket(this.reconPack, this.buffers); - this.finishedReconstruction(); - return packet; - } - return null; -}; - -/** - * Cleans up binary packet reconstruction variables. - * - * @api private - */ - -BinaryReconstructor.prototype.finishedReconstruction = function() { - this.reconPack = null; - this.buffers = []; -}; - -function error(msg) { - return { - type: exports.ERROR, - data: 'parser error: ' + msg - }; -} - -},{"./binary":1661,"./is-buffer":1663,"component-emitter":227,"debug":1664,"isarray":1659}],1663:[function(require,module,exports){ -(function (Buffer){ - -module.exports = isBuf; - -var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function'; -var withNativeArrayBuffer = typeof ArrayBuffer === 'function'; - -var isView = function (obj) { - return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer); -}; - -/** - * Returns true if obj is a buffer or an arraybuffer. - * - * @api private - */ - -function isBuf(obj) { - return (withNativeBuffer && Buffer.isBuffer(obj)) || - (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))); -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217}],1664:[function(require,module,exports){ -(function (process){ -/** - * 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. - */ - -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' -]; - -/** - * 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 - */ - -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; - } - - // 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. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * 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); - - 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 - 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; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * 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); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -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 - */ - -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; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -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) {} -} - -}).call(this,require('_process')) -},{"./debug":1665,"_process":1438}],1665:[function(require,module,exports){ - -/** - * 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'); - -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * The currently active debug mode names, and names to skip. - */ - -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". - */ - -exports.formatters = {}; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - 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]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - var prevTime; - - function debug() { - // disabled? - if (!debug.enabled) return; - - 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; - - // 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]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // 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); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // 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); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - exports.instances.push(debug); - - return debug; -} - -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 - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - 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 + '$')); - } - } - - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -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; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - -},{"ms":1666}],1666:[function(require,module,exports){ -arguments[4][1310][0].apply(exports,arguments) -},{"dup":1310}],1667:[function(require,module,exports){ -arguments[4][1089][0].apply(exports,arguments) -},{"./common":1668,"_process":1438,"dup":1089}],1668:[function(require,module,exports){ -arguments[4][1090][0].apply(exports,arguments) -},{"dup":1090,"ms":1669}],1669:[function(require,module,exports){ -arguments[4][250][0].apply(exports,arguments) -},{"dup":250}],1670:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -// socket.io-pull-stream -const Queue = require('data-queue') -const uuid = require('uuid') -const pull = require('pull-stream') -const sioname = (type, name) => 'socket.io-pull-stream.' + type + (name ? '.' + name : '') -const debug = require('debug') -const _log = debug('socket.io-pull-stream') - -function doCodec (codec, data) { - if (data == null) return data - try { - return codec(data) - } catch (e) { - console.error('Codec Error') - console.error(e) - return false - } -} - -const codecs = { - hex: { - encode: v => v.toString('hex'), - decode: v => Buffer.from(v, 'hex') - }, - plain: { - encode: v => v, - decode: v => v - }, - buffer: { // always do Buffer.from because browsers - encode: v => Buffer.from(v), - decode: v => Buffer.from(v) - } -} - -function getCodec (c) { - if (!c) c = 'plain' - if (typeof c === 'object') return c - const co = codecs[c] - if (!co) throw new Error('Invalid codec ' + c) - return co -} - -function SIOSource (sio, id, opt) { - const q = Queue() - const log = sio.sioplog.bind(sio.sioplog, 'source(' + id + ')') - const codec = getCodec(opt.codec).decode - log('create source') - sio.emit(sioname('accept', id)) - - function unlisten () { - sio.removeAllListeners(sioname('error', id)) - sio.removeAllListeners(sioname('queue', id)) - } - - sio.on(sioname('error', id), err => { - if (err === true) log('finish') - else log('error') - unlisten() - q.append({end: err}) - }) - sio.on(sioname('queue', id), data => { - log('queue data') - q.append({data: doCodec(codec, data)}) - }) - sio.once('disconnect', () => { - unlisten() - q.append({end: true}) - }) - return function (end, cb) { - log('reading') - if (end) return cb(end) - q.get((err, data) => { - if (err) return cb(err) - if (data.end) { - q.error(data.end) - return cb(data.end) - } - return cb(null, data.data) - }) - } -} - -function SIOSink (sio, id, opt) { - const q = Queue() - const log = sio.sioplog.bind(sio.sioplog, ' sink(' + id + ')') - const codec = getCodec(opt.codec).encode - let ended - log('create sink') - sio.once(sioname('accept', id), () => { - log('start transmission') - - function loop () { - q.get((_, val) => { - let {data, err} = val || {} - if (_) err = _ - log('send', err && err === true ? 'finish' : err ? 'error' : data ? 'data' : '') - if (err && !_) q.error(err) - if (err) return sio.emit(sioname('error', id), err) - if (data) sio.emit(sioname('queue', id), doCodec(codec, data)) - loop() - }) - } - loop() - }) - - function doErr (end) { - q.append({err: end}) - ended = end - } - - sio.once('disconnect', () => doErr(true)) - - return function (read) { - read(null, function next (end, data) { - if (end) return doErr(end) - if (ended) return read(ended, next) - q.append({data}) - read(null, next) - }) - } -} - -module.exports = function SIOPullStream (sio, opt) { - if (sio.createSink) return - sio.sioplog = sio.id ? _log.bind(_log, '[' + sio.id + ']') : _log - sio.createSink = (id, _) => { - if (!id) id = uuid() - const sink = SIOSink(sio, id, opt || _) - sink.id = id - return sink - } - sio.createSource = (id, _) => { - const source = SIOSource(sio, id, opt || _) - source.id = id - return source - } - sio.createProxy = (id, tsio, _) => { - pull( - sio.createSource(id, _), - tsio.createSink(id, _) - ) - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"data-queue":237,"debug":1667,"pull-stream":1495,"uuid":1777}],1671:[function(require,module,exports){ -'use strict'; -const isPlainObj = require('is-plain-obj'); - -module.exports = (obj, opts) => { - if (!isPlainObj(obj)) { - throw new TypeError('Expected a plain object'); - } - - opts = opts || {}; - - // DEPRECATED - if (typeof opts === 'function') { - throw new TypeError('Specify the compare function as an option instead'); - } - - const deep = opts.deep; - const seenInput = []; - const seenOutput = []; - - const sortKeys = x => { - const seenIndex = seenInput.indexOf(x); - - if (seenIndex !== -1) { - return seenOutput[seenIndex]; - } - - const ret = {}; - const keys = Object.keys(x).sort(opts.compare); - - seenInput.push(x); - seenOutput.push(ret); - - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const val = x[key]; - - if (deep && Array.isArray(val)) { - const retArr = []; - - for (let j = 0; j < val.length; j++) { - retArr[j] = isPlainObj(val[j]) ? sortKeys(val[j]) : val[j]; - } - - ret[key] = retArr; - continue; - } - - ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val; - } - - return ret; - }; - - return sortKeys(obj); -}; - -},{"is-plain-obj":776}],1672:[function(require,module,exports){ -'use strict' - -// JS treats subjects of bitwise operators as SIGNED 32 bit numbers, -// which means the maximum amount of bits we can store inside each byte -// is 7.. -const BITS_PER_BYTE = 7 - -module.exports = class SparseArray { - constructor () { - this._bitArrays = [] - this._data = [] - this._length = 0 - this._changedLength = false - this._changedData = false - } - - set (index, value) { - let pos = this._internalPositionFor(index, false) - if (value === undefined) { - // unsetting - if (pos !== -1) { - // remove item from bit array and array itself - this._unsetInternalPos(pos) - this._unsetBit(index) - this._changedLength = true - this._changedData = true - } - } else { - let needsSort = false - if (pos === -1) { - pos = this._data.length - this._setBit(index) - this._changedData = true - } else { - needsSort = true - } - this._setInternalPos(pos, index, value, needsSort) - this._changedLength = true - } - } - - unset (index) { - this.set(index, undefined) - } - - get (index) { - this._sortData() - const pos = this._internalPositionFor(index, true) - if (pos === -1) { - return undefined - } - return this._data[pos][1] - } - - push (value) { - this.set(this.length, value) - return this.length - } - - get length () { - this._sortData() - if (this._changedLength) { - const last = this._data[this._data.length - 1] - this._length = last ? last[0] + 1 : 0 - this._changedLength = false - } - return this._length - } - - forEach (iterator) { - let i = 0 - while(i < this.length) { - iterator(this.get(i), i, this) - i++ - } - } - - map (iterator) { - let i = 0 - let mapped = new Array(this.length) - while(i < this.length) { - mapped[i] = iterator(this.get(i), i, this) - i++ - } - return mapped - } - - reduce (reducer, initialValue) { - let i = 0 - let acc = initialValue - while(i < this.length) { - const value = this.get(i) - acc = reducer(acc, value, i) - i++ - } - return acc - } - - find (finder) { - let i = 0, found, last - while ((i < this.length) && !found) { - last = this.get(i) - found = finder(last) - i++ - } - return found ? last : undefined - } - - _internalPositionFor (index, noCreate) { - const bytePos = this._bytePosFor(index, noCreate) - if (bytePos >= this._bitArrays.length) { - return -1 - } - const byte = this._bitArrays[bytePos] - const bitPos = index - bytePos * BITS_PER_BYTE - const exists = (byte & (1 << bitPos)) > 0 - if (!exists) { - return -1 - } - const previousPopCount = this._bitArrays.slice(0, bytePos).reduce(popCountReduce, 0) - - const mask = ~(0xffffffff << (bitPos + 1)) - const bytePopCount = popCount(byte & mask) - const arrayPos = previousPopCount + bytePopCount - 1 - return arrayPos - } - - _bytePosFor (index, noCreate) { - const bytePos = Math.floor(index / BITS_PER_BYTE) - const targetLength = bytePos + 1 - while (!noCreate && this._bitArrays.length < targetLength) { - this._bitArrays.push(0) - } - return bytePos - } - - _setBit (index) { - const bytePos = this._bytePosFor(index, false) - this._bitArrays[bytePos] |= (1 << (index - (bytePos * BITS_PER_BYTE))) - } - - _unsetBit(index) { - const bytePos = this._bytePosFor(index, false) - this._bitArrays[bytePos] &= ~(1 << (index - (bytePos * BITS_PER_BYTE))) - } - - _setInternalPos(pos, index, value, needsSort) { - const data =this._data - const elem = [index, value] - if (needsSort) { - this._sortData() - data[pos] = elem - } else { - // new element. just shove it into the array - // but be nice about where we shove it - // in order to make sorting it later easier - if (data.length) { - if (data[data.length - 1][0] >= index) { - data.push(elem) - } else if (data[0][0] <= index) { - data.unshift(elem) - } else { - const randomIndex = Math.round(data.length / 2) - this._data = data.slice(0, randomIndex).concat(elem).concat(data.slice(randomIndex)) - } - } else { - this._data.push(elem) - } - this._changedData = true - this._changedLength = true - } - } - - _unsetInternalPos (pos) { - this._data.splice(pos, 1) - } - - _sortData () { - if (this._changedData) { - this._data.sort(sortInternal) - } - - this._changedData = false - } - - bitField () { - const bytes = [] - let pendingBitsForResultingByte = 8 - let pendingBitsForNewByte = 0 - let resultingByte = 0 - let newByte - const pending = this._bitArrays.slice() - while (pending.length || pendingBitsForNewByte) { - if (pendingBitsForNewByte === 0) { - newByte = pending.shift() - pendingBitsForNewByte = 7 - } - - const usingBits = Math.min(pendingBitsForNewByte, pendingBitsForResultingByte) - const mask = ~(0b11111111 << usingBits) - const masked = newByte & mask - resultingByte |= masked << (8 - pendingBitsForResultingByte) - newByte = newByte >>> usingBits - pendingBitsForNewByte -= usingBits - pendingBitsForResultingByte -= usingBits - - if (!pendingBitsForResultingByte || (!pendingBitsForNewByte && !pending.length)) { - bytes.push(resultingByte) - resultingByte = 0 - pendingBitsForResultingByte = 8 - } - } - - // remove trailing zeroes - for(var i = bytes.length - 1; i > 0; i--) { - const value = bytes[i] - if (value === 0) { - bytes.pop() - } else { - break - } - } - - return bytes - } - - compactArray () { - this._sortData() - return this._data.map(valueOnly) - } -} - -function popCountReduce (count, byte) { - return count + popCount(byte) -} - -function popCount(_v) { - let v = _v - v = v - ((v >> 1) & 0x55555555) // reuse input as temporary - v = (v & 0x33333333) + ((v >> 2) & 0x33333333) // temp - return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24 -} - -function sortInternal (a, b) { - return a[0] - b[0] -} - -function valueOnly (elem) { - return elem[1] -} -},{}],1673:[function(require,module,exports){ -/* -Copyright (c) 2014-2018, Matteo Collina - -Permission to use, copy, modify, and/or 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. -*/ - -'use strict' - -const { Transform } = require('readable-stream') -const { StringDecoder } = require('string_decoder') -const kLast = Symbol('last') -const kDecoder = Symbol('decoder') - -function transform (chunk, enc, cb) { - var list - if (this.overflow) { // Line buffer is full. Skip to start of next line. - var buf = this[kDecoder].write(chunk) - list = buf.split(this.matcher) - - if (list.length === 1) return cb() // Line ending not found. Discard entire chunk. - - // Line ending found. Discard trailing fragment of previous line and reset overflow state. - list.shift() - this.overflow = false - } else { - this[kLast] += this[kDecoder].write(chunk) - list = this[kLast].split(this.matcher) - } - - this[kLast] = list.pop() - - for (var i = 0; i < list.length; i++) { - push(this, this.mapper(list[i])) - } - - this.overflow = this[kLast].length > this.maxLength - if (this.overflow && !this.skipOverflow) return cb(new Error('maximum buffer reached')) - - cb() -} - -function flush (cb) { - // forward any gibberish left in there - this[kLast] += this[kDecoder].end() - - if (this[kLast]) { - push(this, this.mapper(this[kLast])) - } - - cb() -} - -function push (self, val) { - if (val !== undefined) { - self.push(val) - } -} - -function noop (incoming) { - return incoming -} - -function split (matcher, mapper, options) { - // Set defaults for any arguments not supplied. - matcher = matcher || /\r?\n/ - mapper = mapper || noop - options = options || {} - - // Test arguments explicitly. - switch (arguments.length) { - case 1: - // If mapper is only argument. - if (typeof matcher === 'function') { - mapper = matcher - matcher = /\r?\n/ - // If options is only argument. - } else if (typeof matcher === 'object' && !(matcher instanceof RegExp)) { - options = matcher - matcher = /\r?\n/ - } - break - - case 2: - // If mapper and options are arguments. - if (typeof matcher === 'function') { - options = mapper - mapper = matcher - matcher = /\r?\n/ - // If matcher and options are arguments. - } else if (typeof mapper === 'object') { - options = mapper - mapper = noop - } - } - - options = Object.assign({}, options) - options.transform = transform - options.flush = flush - options.readableObjectMode = true - - const stream = new Transform(options) - - stream[kLast] = '' - stream[kDecoder] = new StringDecoder('utf8') - stream.matcher = matcher - stream.mapper = mapper - stream.maxLength = options.maxLength - stream.skipOverflow = options.skipOverflow - stream.overflow = false - - return stream -} - -module.exports = split - -},{"readable-stream":1688,"string_decoder":1741}],1674:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],1675:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],1676:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":1678,"./_stream_writable":1680,"_process":1438,"dup":90,"inherits":453}],1677:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":1679,"dup":91,"inherits":453}],1678:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":1674,"../experimentalWarning":1675,"./_stream_duplex":1676,"./internal/streams/async_iterator":1681,"./internal/streams/buffer_list":1682,"./internal/streams/destroy":1683,"./internal/streams/state":1686,"./internal/streams/stream":1687,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],1679:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":1674,"./_stream_duplex":1676,"dup":93,"inherits":453}],1680:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":1674,"./_stream_duplex":1676,"./internal/streams/destroy":1683,"./internal/streams/state":1686,"./internal/streams/stream":1687,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],1681:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":1684,"_process":1438,"dup":95}],1682:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],1683:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],1684:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":1674,"dup":98}],1685:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":1674,"./end-of-stream":1684,"dup":99}],1686:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":1674,"dup":100}],1687:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],1688:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":1676,"./lib/_stream_passthrough.js":1677,"./lib/_stream_readable.js":1678,"./lib/_stream_transform.js":1679,"./lib/_stream_writable.js":1680,"./lib/internal/streams/end-of-stream.js":1684,"./lib/internal/streams/pipeline.js":1685,"dup":102}],1689:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -var Buffer = require('safer-buffer').Buffer; - -var algInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y'], - sizePart: 'p' - }, - 'rsa': { - parts: ['e', 'n'], - sizePart: 'n' - }, - 'ecdsa': { - parts: ['curve', 'Q'], - sizePart: 'Q' - }, - 'ed25519': { - parts: ['A'], - sizePart: 'A' - } -}; -algInfo['curve25519'] = algInfo['ed25519']; - -var algPrivInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y', 'x'] - }, - 'rsa': { - parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] - }, - 'ecdsa': { - parts: ['curve', 'Q', 'd'] - }, - 'ed25519': { - parts: ['A', 'k'] - } -}; -algPrivInfo['curve25519'] = algPrivInfo['ed25519']; - -var hashAlgs = { - 'md5': true, - 'sha1': true, - 'sha256': true, - 'sha384': true, - 'sha512': true -}; - -/* - * Taken from - * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf - */ -var curves = { - 'nistp256': { - size: 256, - pkcs8oid: '1.2.840.10045.3.1.7', - p: Buffer.from(('00' + - 'ffffffff 00000001 00000000 00000000' + - '00000000 ffffffff ffffffff ffffffff'). - replace(/ /g, ''), 'hex'), - a: Buffer.from(('00' + - 'FFFFFFFF 00000001 00000000 00000000' + - '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(( - '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + - '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'c49d3608 86e70493 6a6678e1 139d26b7' + - '819f7e90'). - replace(/ /g, ''), 'hex'), - n: Buffer.from(('00' + - 'ffffffff 00000000 ffffffff ffffffff' + - 'bce6faad a7179e84 f3b9cac2 fc632551'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + - '77037d81 2deb33a0 f4a13945 d898c296' + - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + - '2bce3357 6b315ece cbb64068 37bf51f5'). - replace(/ /g, ''), 'hex') - }, - 'nistp384': { - size: 384, - pkcs8oid: '1.3.132.0.34', - p: Buffer.from(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffe' + - 'ffffffff 00000000 00000000 ffffffff'). - replace(/ /g, ''), 'hex'), - a: Buffer.from(('00' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + - 'FFFFFFFF 00000000 00000000 FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(( - 'b3312fa7 e23ee7e4 988e056b e3f82d19' + - '181d9c6e fe814112 0314088f 5013875a' + - 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'a335926a a319a27a 1d00896a 6773a482' + - '7acdac73'). - replace(/ /g, ''), 'hex'), - n: Buffer.from(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff c7634d81 f4372ddf' + - '581a0db2 48b0a77a ecec196a ccc52973'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - 'aa87ca22 be8b0537 8eb1c71e f320ad74' + - '6e1d3b62 8ba79b98 59f741e0 82542a38' + - '5502f25d bf55296c 3a545e38 72760ab7' + - '3617de4a 96262c6f 5d9e98bf 9292dc29' + - 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). - replace(/ /g, ''), 'hex') - }, - 'nistp521': { - size: 521, - pkcs8oid: '1.3.132.0.35', - p: Buffer.from(( - '01ffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffff').replace(/ /g, ''), 'hex'), - a: Buffer.from(('01FF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: Buffer.from(('51' + - '953eb961 8e1c9a1f 929a21a0 b68540ee' + - 'a2da725b 99b315f3 b8b48991 8ef109e1' + - '56193951 ec7e937b 1652c0bd 3bb1bf07' + - '3573df88 3d2c34f1 ef451fd4 6b503f00'). - replace(/ /g, ''), 'hex'), - s: Buffer.from(('00' + - 'd09e8800 291cb853 96cc6717 393284aa' + - 'a0da64ba').replace(/ /g, ''), 'hex'), - n: Buffer.from(('01ff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffa' + - '51868783 bf2f966b 7fcc0148 f709a5d0' + - '3bb5c9b8 899c47ae bb6fb71e 91386409'). - replace(/ /g, ''), 'hex'), - G: Buffer.from(('04' + - '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + - '9c648139 053fb521 f828af60 6b4d3dba' + - 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + - '3348b3c1 856a429b f97e7e31 c2e5bd66' + - '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + - '98f54449 579b4468 17afbd17 273e662c' + - '97ee7299 5ef42640 c550b901 3fad0761' + - '353c7086 a272c240 88be9476 9fd16650'). - replace(/ /g, ''), 'hex') - } -}; - -module.exports = { - info: algInfo, - privInfo: algPrivInfo, - hashAlgs: hashAlgs, - curves: curves -}; - -},{"safer-buffer":1594}],1690:[function(require,module,exports){ -// Copyright 2016 Joyent, Inc. - -module.exports = Certificate; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('./algs'); -var crypto = require('crypto'); -var Fingerprint = require('./fingerprint'); -var Signature = require('./signature'); -var errs = require('./errors'); -var util = require('util'); -var utils = require('./utils'); -var Key = require('./key'); -var PrivateKey = require('./private-key'); -var Identity = require('./identity'); - -var formats = {}; -formats['openssh'] = require('./formats/openssh-cert'); -formats['x509'] = require('./formats/x509'); -formats['pem'] = require('./formats/x509-pem'); - -var CertificateParseError = errs.CertificateParseError; -var InvalidAlgorithmError = errs.InvalidAlgorithmError; - -function Certificate(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.subjects, 'options.subjects'); - utils.assertCompatible(opts.subjects[0], Identity, [1, 0], - 'options.subjects'); - utils.assertCompatible(opts.subjectKey, Key, [1, 0], - 'options.subjectKey'); - utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer'); - if (opts.issuerKey !== undefined) { - utils.assertCompatible(opts.issuerKey, Key, [1, 0], - 'options.issuerKey'); - } - assert.object(opts.signatures, 'options.signatures'); - assert.buffer(opts.serial, 'options.serial'); - assert.date(opts.validFrom, 'options.validFrom'); - assert.date(opts.validUntil, 'optons.validUntil'); - - assert.optionalArrayOfString(opts.purposes, 'options.purposes'); - - this._hashCache = {}; - - this.subjects = opts.subjects; - this.issuer = opts.issuer; - this.subjectKey = opts.subjectKey; - this.issuerKey = opts.issuerKey; - this.signatures = opts.signatures; - this.serial = opts.serial; - this.validFrom = opts.validFrom; - this.validUntil = opts.validUntil; - this.purposes = opts.purposes; -} - -Certificate.formats = formats; - -Certificate.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'x509'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); - - return (formats[format].write(this, options)); -}; - -Certificate.prototype.toString = function (format, options) { - if (format === undefined) - format = 'pem'; - return (this.toBuffer(format, options).toString()); -}; - -Certificate.prototype.fingerprint = function (algo) { - if (algo === undefined) - algo = 'sha256'; - assert.string(algo, 'algorithm'); - var opts = { - type: 'certificate', - hash: this.hash(algo), - algorithm: algo - }; - return (new Fingerprint(opts)); -}; - -Certificate.prototype.hash = function (algo) { - assert.string(algo, 'algorithm'); - algo = algo.toLowerCase(); - if (algs.hashAlgs[algo] === undefined) - throw (new InvalidAlgorithmError(algo)); - - if (this._hashCache[algo]) - return (this._hashCache[algo]); - - var hash = crypto.createHash(algo). - update(this.toBuffer('x509')).digest(); - this._hashCache[algo] = hash; - return (hash); -}; - -Certificate.prototype.isExpired = function (when) { - if (when === undefined) - when = new Date(); - return (!((when.getTime() >= this.validFrom.getTime()) && - (when.getTime() < this.validUntil.getTime()))); -}; - -Certificate.prototype.isSignedBy = function (issuerCert) { - utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer'); - - if (!this.issuer.equals(issuerCert.subjects[0])) - return (false); - if (this.issuer.purposes && this.issuer.purposes.length > 0 && - this.issuer.purposes.indexOf('ca') === -1) { - return (false); - } - - return (this.isSignedByKey(issuerCert.subjectKey)); -}; - -Certificate.prototype.getExtension = function (keyOrOid) { - assert.string(keyOrOid, 'keyOrOid'); - var ext = this.getExtensions().filter(function (maybeExt) { - if (maybeExt.format === 'x509') - return (maybeExt.oid === keyOrOid); - if (maybeExt.format === 'openssh') - return (maybeExt.name === keyOrOid); - return (false); - })[0]; - return (ext); -}; - -Certificate.prototype.getExtensions = function () { - var exts = []; - var x509 = this.signatures.x509; - if (x509 && x509.extras && x509.extras.exts) { - x509.extras.exts.forEach(function (ext) { - ext.format = 'x509'; - exts.push(ext); - }); - } - var openssh = this.signatures.openssh; - if (openssh && openssh.exts) { - openssh.exts.forEach(function (ext) { - ext.format = 'openssh'; - exts.push(ext); - }); - } - return (exts); -}; - -Certificate.prototype.isSignedByKey = function (issuerKey) { - utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey'); - - if (this.issuerKey !== undefined) { - return (this.issuerKey. - fingerprint('sha512').matches(issuerKey)); - } - - var fmt = Object.keys(this.signatures)[0]; - var valid = formats[fmt].verify(this, issuerKey); - if (valid) - this.issuerKey = issuerKey; - return (valid); -}; - -Certificate.prototype.signWith = function (key) { - utils.assertCompatible(key, PrivateKey, [1, 2], 'key'); - var fmts = Object.keys(formats); - var didOne = false; - for (var i = 0; i < fmts.length; ++i) { - if (fmts[i] !== 'pem') { - var ret = formats[fmts[i]].sign(this, key); - if (ret === true) - didOne = true; - } - } - if (!didOne) { - throw (new Error('Failed to sign the certificate for any ' + - 'available certificate formats')); - } -}; - -Certificate.createSelfSigned = function (subjectOrSubjects, key, options) { - var subjects; - if (Array.isArray(subjectOrSubjects)) - subjects = subjectOrSubjects; - else - subjects = [subjectOrSubjects]; - - assert.arrayOfObject(subjects); - subjects.forEach(function (subject) { - utils.assertCompatible(subject, Identity, [1, 0], 'subject'); - }); - - utils.assertCompatible(key, PrivateKey, [1, 2], 'private key'); - - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalObject(options.validFrom, 'options.validFrom'); - assert.optionalObject(options.validUntil, 'options.validUntil'); - var validFrom = options.validFrom; - var validUntil = options.validUntil; - if (validFrom === undefined) - validFrom = new Date(); - if (validUntil === undefined) { - assert.optionalNumber(options.lifetime, 'options.lifetime'); - var lifetime = options.lifetime; - if (lifetime === undefined) - lifetime = 10*365*24*3600; - validUntil = new Date(); - validUntil.setTime(validUntil.getTime() + lifetime*1000); - } - assert.optionalBuffer(options.serial, 'options.serial'); - var serial = options.serial; - if (serial === undefined) - serial = Buffer.from('0000000000000001', 'hex'); - - var purposes = options.purposes; - if (purposes === undefined) - purposes = []; - - if (purposes.indexOf('signature') === -1) - purposes.push('signature'); - - /* Self-signed certs are always CAs. */ - if (purposes.indexOf('ca') === -1) - purposes.push('ca'); - if (purposes.indexOf('crl') === -1) - purposes.push('crl'); - - /* - * If we weren't explicitly given any other purposes, do the sensible - * thing and add some basic ones depending on the subject type. - */ - if (purposes.length <= 3) { - var hostSubjects = subjects.filter(function (subject) { - return (subject.type === 'host'); - }); - var userSubjects = subjects.filter(function (subject) { - return (subject.type === 'user'); - }); - if (hostSubjects.length > 0) { - if (purposes.indexOf('serverAuth') === -1) - purposes.push('serverAuth'); - } - if (userSubjects.length > 0) { - if (purposes.indexOf('clientAuth') === -1) - purposes.push('clientAuth'); - } - if (userSubjects.length > 0 || hostSubjects.length > 0) { - if (purposes.indexOf('keyAgreement') === -1) - purposes.push('keyAgreement'); - if (key.type === 'rsa' && - purposes.indexOf('encryption') === -1) - purposes.push('encryption'); - } - } - - var cert = new Certificate({ - subjects: subjects, - issuer: subjects[0], - subjectKey: key.toPublic(), - issuerKey: key.toPublic(), - signatures: {}, - serial: serial, - validFrom: validFrom, - validUntil: validUntil, - purposes: purposes - }); - cert.signWith(key); - - return (cert); -}; - -Certificate.create = - function (subjectOrSubjects, key, issuer, issuerKey, options) { - var subjects; - if (Array.isArray(subjectOrSubjects)) - subjects = subjectOrSubjects; - else - subjects = [subjectOrSubjects]; - - assert.arrayOfObject(subjects); - subjects.forEach(function (subject) { - utils.assertCompatible(subject, Identity, [1, 0], 'subject'); - }); - - utils.assertCompatible(key, Key, [1, 0], 'key'); - if (PrivateKey.isPrivateKey(key)) - key = key.toPublic(); - utils.assertCompatible(issuer, Identity, [1, 0], 'issuer'); - utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key'); - - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalObject(options.validFrom, 'options.validFrom'); - assert.optionalObject(options.validUntil, 'options.validUntil'); - var validFrom = options.validFrom; - var validUntil = options.validUntil; - if (validFrom === undefined) - validFrom = new Date(); - if (validUntil === undefined) { - assert.optionalNumber(options.lifetime, 'options.lifetime'); - var lifetime = options.lifetime; - if (lifetime === undefined) - lifetime = 10*365*24*3600; - validUntil = new Date(); - validUntil.setTime(validUntil.getTime() + lifetime*1000); - } - assert.optionalBuffer(options.serial, 'options.serial'); - var serial = options.serial; - if (serial === undefined) - serial = Buffer.from('0000000000000001', 'hex'); - - var purposes = options.purposes; - if (purposes === undefined) - purposes = []; - - if (purposes.indexOf('signature') === -1) - purposes.push('signature'); - - if (options.ca === true) { - if (purposes.indexOf('ca') === -1) - purposes.push('ca'); - if (purposes.indexOf('crl') === -1) - purposes.push('crl'); - } - - var hostSubjects = subjects.filter(function (subject) { - return (subject.type === 'host'); - }); - var userSubjects = subjects.filter(function (subject) { - return (subject.type === 'user'); - }); - if (hostSubjects.length > 0) { - if (purposes.indexOf('serverAuth') === -1) - purposes.push('serverAuth'); - } - if (userSubjects.length > 0) { - if (purposes.indexOf('clientAuth') === -1) - purposes.push('clientAuth'); - } - if (userSubjects.length > 0 || hostSubjects.length > 0) { - if (purposes.indexOf('keyAgreement') === -1) - purposes.push('keyAgreement'); - if (key.type === 'rsa' && - purposes.indexOf('encryption') === -1) - purposes.push('encryption'); - } - - var cert = new Certificate({ - subjects: subjects, - issuer: issuer, - subjectKey: key, - issuerKey: issuerKey.toPublic(), - signatures: {}, - serial: serial, - validFrom: validFrom, - validUntil: validUntil, - purposes: purposes - }); - cert.signWith(issuerKey); - - return (cert); -}; - -Certificate.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - - assert.object(formats[format], 'formats[format]'); - - try { - var k = formats[format].read(data, options); - return (k); - } catch (e) { - throw (new CertificateParseError(options.filename, format, e)); - } -}; - -Certificate.isCertificate = function (obj, ver) { - return (utils.isCompatible(obj, Certificate, ver)); -}; - -/* - * API versions for Certificate: - * [1,0] -- initial ver - * [1,1] -- openssh format now unpacks extensions - */ -Certificate.prototype._sshpkApiVersion = [1, 1]; - -Certificate._oldVersionDetect = function (obj) { - return ([1, 0]); -}; - -},{"./algs":1689,"./errors":1693,"./fingerprint":1694,"./formats/openssh-cert":1697,"./formats/x509":1706,"./formats/x509-pem":1705,"./identity":1707,"./key":1709,"./private-key":1710,"./signature":1711,"./utils":1713,"assert-plus":77,"crypto":236,"safer-buffer":1594,"util":1776}],1691:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = { - DiffieHellman: DiffieHellman, - generateECDSA: generateECDSA, - generateED25519: generateED25519 -}; - -var assert = require('assert-plus'); -var crypto = require('crypto'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('./algs'); -var utils = require('./utils'); -var nacl = require('tweetnacl'); - -var Key = require('./key'); -var PrivateKey = require('./private-key'); - -var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined); - -var ecdh = require('ecc-jsbn'); -var ec = require('ecc-jsbn/lib/ec'); -var jsbn = require('jsbn').BigInteger; - -function DiffieHellman(key) { - utils.assertCompatible(key, Key, [1, 4], 'key'); - this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]); - this._algo = key.type; - this._curve = key.curve; - this._key = key; - if (key.type === 'dsa') { - if (!CRYPTO_HAVE_ECDH) { - throw (new Error('Due to bugs in the node 0.10 ' + - 'crypto API, node 0.12.x or later is required ' + - 'to use DH')); - } - this._dh = crypto.createDiffieHellman( - key.part.p.data, undefined, - key.part.g.data, undefined); - this._p = key.part.p; - this._g = key.part.g; - if (this._isPriv) - this._dh.setPrivateKey(key.part.x.data); - this._dh.setPublicKey(key.part.y.data); - - } else if (key.type === 'ecdsa') { - if (!CRYPTO_HAVE_ECDH) { - this._ecParams = new X9ECParameters(this._curve); - - if (this._isPriv) { - this._priv = new ECPrivate( - this._ecParams, key.part.d.data); - } - return; - } - - var curve = { - 'nistp256': 'prime256v1', - 'nistp384': 'secp384r1', - 'nistp521': 'secp521r1' - }[key.curve]; - this._dh = crypto.createECDH(curve); - if (typeof (this._dh) !== 'object' || - typeof (this._dh.setPrivateKey) !== 'function') { - CRYPTO_HAVE_ECDH = false; - DiffieHellman.call(this, key); - return; - } - if (this._isPriv) - this._dh.setPrivateKey(key.part.d.data); - this._dh.setPublicKey(key.part.Q.data); - - } else if (key.type === 'curve25519') { - if (this._isPriv) { - utils.assertCompatible(key, PrivateKey, [1, 5], 'key'); - this._priv = key.part.k.data; - } - - } else { - throw (new Error('DH not supported for ' + key.type + ' keys')); - } -} - -DiffieHellman.prototype.getPublicKey = function () { - if (this._isPriv) - return (this._key.toPublic()); - return (this._key); -}; - -DiffieHellman.prototype.getPrivateKey = function () { - if (this._isPriv) - return (this._key); - else - return (undefined); -}; -DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey; - -DiffieHellman.prototype._keyCheck = function (pk, isPub) { - assert.object(pk, 'key'); - if (!isPub) - utils.assertCompatible(pk, PrivateKey, [1, 3], 'key'); - utils.assertCompatible(pk, Key, [1, 4], 'key'); - - if (pk.type !== this._algo) { - throw (new Error('A ' + pk.type + ' key cannot be used in ' + - this._algo + ' Diffie-Hellman')); - } - - if (pk.curve !== this._curve) { - throw (new Error('A key from the ' + pk.curve + ' curve ' + - 'cannot be used with a ' + this._curve + - ' Diffie-Hellman')); - } - - if (pk.type === 'dsa') { - assert.deepEqual(pk.part.p, this._p, - 'DSA key prime does not match'); - assert.deepEqual(pk.part.g, this._g, - 'DSA key generator does not match'); - } -}; - -DiffieHellman.prototype.setKey = function (pk) { - this._keyCheck(pk); - - if (pk.type === 'dsa') { - this._dh.setPrivateKey(pk.part.x.data); - this._dh.setPublicKey(pk.part.y.data); - - } else if (pk.type === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - this._dh.setPrivateKey(pk.part.d.data); - this._dh.setPublicKey(pk.part.Q.data); - } else { - this._priv = new ECPrivate( - this._ecParams, pk.part.d.data); - } - - } else if (pk.type === 'curve25519') { - var k = pk.part.k; - if (!pk.part.k) - k = pk.part.r; - this._priv = k.data; - if (this._priv[0] === 0x00) - this._priv = this._priv.slice(1); - this._priv = this._priv.slice(0, 32); - } - this._key = pk; - this._isPriv = true; -}; -DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey; - -DiffieHellman.prototype.computeSecret = function (otherpk) { - this._keyCheck(otherpk, true); - if (!this._isPriv) - throw (new Error('DH exchange has not been initialized with ' + - 'a private key yet')); - - var pub; - if (this._algo === 'dsa') { - return (this._dh.computeSecret( - otherpk.part.y.data)); - - } else if (this._algo === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - return (this._dh.computeSecret( - otherpk.part.Q.data)); - } else { - pub = new ECPublic( - this._ecParams, otherpk.part.Q.data); - return (this._priv.deriveSharedSecret(pub)); - } - - } else if (this._algo === 'curve25519') { - pub = otherpk.part.A.data; - while (pub[0] === 0x00 && pub.length > 32) - pub = pub.slice(1); - var priv = this._priv; - assert.strictEqual(pub.length, 32); - assert.strictEqual(priv.length, 32); - - var secret = nacl.box.before(new Uint8Array(pub), - new Uint8Array(priv)); - - return (Buffer.from(secret)); - } - - throw (new Error('Invalid algorithm: ' + this._algo)); -}; - -DiffieHellman.prototype.generateKey = function () { - var parts = []; - var priv, pub; - if (this._algo === 'dsa') { - this._dh.generateKeys(); - - parts.push({name: 'p', data: this._p.data}); - parts.push({name: 'q', data: this._key.part.q.data}); - parts.push({name: 'g', data: this._g.data}); - parts.push({name: 'y', data: this._dh.getPublicKey()}); - parts.push({name: 'x', data: this._dh.getPrivateKey()}); - this._key = new PrivateKey({ - type: 'dsa', - parts: parts - }); - this._isPriv = true; - return (this._key); - - } else if (this._algo === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - this._dh.generateKeys(); - - parts.push({name: 'curve', - data: Buffer.from(this._curve)}); - parts.push({name: 'Q', data: this._dh.getPublicKey()}); - parts.push({name: 'd', data: this._dh.getPrivateKey()}); - this._key = new PrivateKey({ - type: 'ecdsa', - curve: this._curve, - parts: parts - }); - this._isPriv = true; - return (this._key); - - } else { - var n = this._ecParams.getN(); - var r = new jsbn(crypto.randomBytes(n.bitLength())); - var n1 = n.subtract(jsbn.ONE); - priv = r.mod(n1).add(jsbn.ONE); - pub = this._ecParams.getG().multiply(priv); - - priv = Buffer.from(priv.toByteArray()); - pub = Buffer.from(this._ecParams.getCurve(). - encodePointHex(pub), 'hex'); - - this._priv = new ECPrivate(this._ecParams, priv); - - parts.push({name: 'curve', - data: Buffer.from(this._curve)}); - parts.push({name: 'Q', data: pub}); - parts.push({name: 'd', data: priv}); - - this._key = new PrivateKey({ - type: 'ecdsa', - curve: this._curve, - parts: parts - }); - this._isPriv = true; - return (this._key); - } - - } else if (this._algo === 'curve25519') { - var pair = nacl.box.keyPair(); - priv = Buffer.from(pair.secretKey); - pub = Buffer.from(pair.publicKey); - priv = Buffer.concat([priv, pub]); - assert.strictEqual(priv.length, 64); - assert.strictEqual(pub.length, 32); - - parts.push({name: 'A', data: pub}); - parts.push({name: 'k', data: priv}); - this._key = new PrivateKey({ - type: 'curve25519', - parts: parts - }); - this._isPriv = true; - return (this._key); - } - - throw (new Error('Invalid algorithm: ' + this._algo)); -}; -DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey; - -/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */ - -function X9ECParameters(name) { - var params = algs.curves[name]; - assert.object(params); - - var p = new jsbn(params.p); - var a = new jsbn(params.a); - var b = new jsbn(params.b); - var n = new jsbn(params.n); - var h = jsbn.ONE; - var curve = new ec.ECCurveFp(p, a, b); - var G = curve.decodePointHex(params.G.toString('hex')); - - this.curve = curve; - this.g = G; - this.n = n; - this.h = h; -} -X9ECParameters.prototype.getCurve = function () { return (this.curve); }; -X9ECParameters.prototype.getG = function () { return (this.g); }; -X9ECParameters.prototype.getN = function () { return (this.n); }; -X9ECParameters.prototype.getH = function () { return (this.h); }; - -function ECPublic(params, buffer) { - this._params = params; - if (buffer[0] === 0x00) - buffer = buffer.slice(1); - this._pub = params.getCurve().decodePointHex(buffer.toString('hex')); -} - -function ECPrivate(params, buffer) { - this._params = params; - this._priv = new jsbn(utils.mpNormalize(buffer)); -} -ECPrivate.prototype.deriveSharedSecret = function (pubKey) { - assert.ok(pubKey instanceof ECPublic); - var S = pubKey._pub.multiply(this._priv); - return (Buffer.from(S.getX().toBigInteger().toByteArray())); -}; - -function generateED25519() { - var pair = nacl.sign.keyPair(); - var priv = Buffer.from(pair.secretKey); - var pub = Buffer.from(pair.publicKey); - assert.strictEqual(priv.length, 64); - assert.strictEqual(pub.length, 32); - - var parts = []; - parts.push({name: 'A', data: pub}); - parts.push({name: 'k', data: priv.slice(0, 32)}); - var key = new PrivateKey({ - type: 'ed25519', - parts: parts - }); - return (key); -} - -/* Generates a new ECDSA private key on a given curve. */ -function generateECDSA(curve) { - var parts = []; - var key; - - if (CRYPTO_HAVE_ECDH) { - /* - * Node crypto doesn't expose key generation directly, but the - * ECDH instances can generate keys. It turns out this just - * calls into the OpenSSL generic key generator, and we can - * read its output happily without doing an actual DH. So we - * use that here. - */ - var osCurve = { - 'nistp256': 'prime256v1', - 'nistp384': 'secp384r1', - 'nistp521': 'secp521r1' - }[curve]; - - var dh = crypto.createECDH(osCurve); - dh.generateKeys(); - - parts.push({name: 'curve', - data: Buffer.from(curve)}); - parts.push({name: 'Q', data: dh.getPublicKey()}); - parts.push({name: 'd', data: dh.getPrivateKey()}); - - key = new PrivateKey({ - type: 'ecdsa', - curve: curve, - parts: parts - }); - return (key); - } else { - - var ecParams = new X9ECParameters(curve); - - /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */ - var n = ecParams.getN(); - /* - * The crypto.randomBytes() function can only give us whole - * bytes, so taking a nod from X9.62, we round up. - */ - var cByteLen = Math.ceil((n.bitLength() + 64) / 8); - var c = new jsbn(crypto.randomBytes(cByteLen)); - - var n1 = n.subtract(jsbn.ONE); - var priv = c.mod(n1).add(jsbn.ONE); - var pub = ecParams.getG().multiply(priv); - - priv = Buffer.from(priv.toByteArray()); - pub = Buffer.from(ecParams.getCurve(). - encodePointHex(pub), 'hex'); - - parts.push({name: 'curve', data: Buffer.from(curve)}); - parts.push({name: 'Q', data: pub}); - parts.push({name: 'd', data: priv}); - - key = new PrivateKey({ - type: 'ecdsa', - curve: curve, - parts: parts - }); - return (key); - } -} - -},{"./algs":1689,"./key":1709,"./private-key":1710,"./utils":1713,"assert-plus":77,"crypto":236,"ecc-jsbn":279,"ecc-jsbn/lib/ec":280,"jsbn":825,"safer-buffer":1594,"tweetnacl":1762}],1692:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - Verifier: Verifier, - Signer: Signer -}; - -var nacl = require('tweetnacl'); -var stream = require('stream'); -var util = require('util'); -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var Signature = require('./signature'); - -function Verifier(key, hashAlgo) { - if (hashAlgo.toLowerCase() !== 'sha512') - throw (new Error('ED25519 only supports the use of ' + - 'SHA-512 hashes')); - - this.key = key; - this.chunks = []; - - stream.Writable.call(this, {}); -} -util.inherits(Verifier, stream.Writable); - -Verifier.prototype._write = function (chunk, enc, cb) { - this.chunks.push(chunk); - cb(); -}; - -Verifier.prototype.update = function (chunk) { - if (typeof (chunk) === 'string') - chunk = Buffer.from(chunk, 'binary'); - this.chunks.push(chunk); -}; - -Verifier.prototype.verify = function (signature, fmt) { - var sig; - if (Signature.isSignature(signature, [2, 0])) { - if (signature.type !== 'ed25519') - return (false); - sig = signature.toBuffer('raw'); - - } else if (typeof (signature) === 'string') { - sig = Buffer.from(signature, 'base64'); - - } else if (Signature.isSignature(signature, [1, 0])) { - throw (new Error('signature was created by too old ' + - 'a version of sshpk and cannot be verified')); - } - - assert.buffer(sig); - return (nacl.sign.detached.verify( - new Uint8Array(Buffer.concat(this.chunks)), - new Uint8Array(sig), - new Uint8Array(this.key.part.A.data))); -}; - -function Signer(key, hashAlgo) { - if (hashAlgo.toLowerCase() !== 'sha512') - throw (new Error('ED25519 only supports the use of ' + - 'SHA-512 hashes')); - - this.key = key; - this.chunks = []; - - stream.Writable.call(this, {}); -} -util.inherits(Signer, stream.Writable); - -Signer.prototype._write = function (chunk, enc, cb) { - this.chunks.push(chunk); - cb(); -}; - -Signer.prototype.update = function (chunk) { - if (typeof (chunk) === 'string') - chunk = Buffer.from(chunk, 'binary'); - this.chunks.push(chunk); -}; - -Signer.prototype.sign = function () { - var sig = nacl.sign.detached( - new Uint8Array(Buffer.concat(this.chunks)), - new Uint8Array(Buffer.concat([ - this.key.part.k.data, this.key.part.A.data]))); - var sigBuf = Buffer.from(sig); - var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw'); - sigObj.hashAlgorithm = 'sha512'; - return (sigObj); -}; - -},{"./signature":1711,"assert-plus":77,"safer-buffer":1594,"stream":1715,"tweetnacl":1762,"util":1776}],1693:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -var assert = require('assert-plus'); -var util = require('util'); - -function FingerprintFormatError(fp, format) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, FingerprintFormatError); - this.name = 'FingerprintFormatError'; - this.fingerprint = fp; - this.format = format; - this.message = 'Fingerprint format is not supported, or is invalid: '; - if (fp !== undefined) - this.message += ' fingerprint = ' + fp; - if (format !== undefined) - this.message += ' format = ' + format; -} -util.inherits(FingerprintFormatError, Error); - -function InvalidAlgorithmError(alg) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, InvalidAlgorithmError); - this.name = 'InvalidAlgorithmError'; - this.algorithm = alg; - this.message = 'Algorithm "' + alg + '" is not supported'; -} -util.inherits(InvalidAlgorithmError, Error); - -function KeyParseError(name, format, innerErr) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, KeyParseError); - this.name = 'KeyParseError'; - this.format = format; - this.keyName = name; - this.innerErr = innerErr; - this.message = 'Failed to parse ' + name + ' as a valid ' + format + - ' format key: ' + innerErr.message; -} -util.inherits(KeyParseError, Error); - -function SignatureParseError(type, format, innerErr) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, SignatureParseError); - this.name = 'SignatureParseError'; - this.type = type; - this.format = format; - this.innerErr = innerErr; - this.message = 'Failed to parse the given data as a ' + type + - ' signature in ' + format + ' format: ' + innerErr.message; -} -util.inherits(SignatureParseError, Error); - -function CertificateParseError(name, format, innerErr) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, CertificateParseError); - this.name = 'CertificateParseError'; - this.format = format; - this.certName = name; - this.innerErr = innerErr; - this.message = 'Failed to parse ' + name + ' as a valid ' + format + - ' format certificate: ' + innerErr.message; -} -util.inherits(CertificateParseError, Error); - -function KeyEncryptedError(name, format) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, KeyEncryptedError); - this.name = 'KeyEncryptedError'; - this.format = format; - this.keyName = name; - this.message = 'The ' + format + ' format key ' + name + ' is ' + - 'encrypted (password-protected), and no passphrase was ' + - 'provided in `options`'; -} -util.inherits(KeyEncryptedError, Error); - -module.exports = { - FingerprintFormatError: FingerprintFormatError, - InvalidAlgorithmError: InvalidAlgorithmError, - KeyParseError: KeyParseError, - SignatureParseError: SignatureParseError, - KeyEncryptedError: KeyEncryptedError, - CertificateParseError: CertificateParseError -}; - -},{"assert-plus":77,"util":1776}],1694:[function(require,module,exports){ -// Copyright 2018 Joyent, Inc. - -module.exports = Fingerprint; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('./algs'); -var crypto = require('crypto'); -var errs = require('./errors'); -var Key = require('./key'); -var PrivateKey = require('./private-key'); -var Certificate = require('./certificate'); -var utils = require('./utils'); - -var FingerprintFormatError = errs.FingerprintFormatError; -var InvalidAlgorithmError = errs.InvalidAlgorithmError; - -function Fingerprint(opts) { - assert.object(opts, 'options'); - assert.string(opts.type, 'options.type'); - assert.buffer(opts.hash, 'options.hash'); - assert.string(opts.algorithm, 'options.algorithm'); - - this.algorithm = opts.algorithm.toLowerCase(); - if (algs.hashAlgs[this.algorithm] !== true) - throw (new InvalidAlgorithmError(this.algorithm)); - - this.hash = opts.hash; - this.type = opts.type; - this.hashType = opts.hashType; -} - -Fingerprint.prototype.toString = function (format) { - if (format === undefined) { - if (this.algorithm === 'md5' || this.hashType === 'spki') - format = 'hex'; - else - format = 'base64'; - } - assert.string(format); - - switch (format) { - case 'hex': - if (this.hashType === 'spki') - return (this.hash.toString('hex')); - return (addColons(this.hash.toString('hex'))); - case 'base64': - if (this.hashType === 'spki') - return (this.hash.toString('base64')); - return (sshBase64Format(this.algorithm, - this.hash.toString('base64'))); - default: - throw (new FingerprintFormatError(undefined, format)); - } -}; - -Fingerprint.prototype.matches = function (other) { - assert.object(other, 'key or certificate'); - if (this.type === 'key' && this.hashType !== 'ssh') { - utils.assertCompatible(other, Key, [1, 7], 'key with spki'); - if (PrivateKey.isPrivateKey(other)) { - utils.assertCompatible(other, PrivateKey, [1, 6], - 'privatekey with spki support'); - } - } else if (this.type === 'key') { - utils.assertCompatible(other, Key, [1, 0], 'key'); - } else { - utils.assertCompatible(other, Certificate, [1, 0], - 'certificate'); - } - - var theirHash = other.hash(this.algorithm, this.hashType); - var theirHash2 = crypto.createHash(this.algorithm). - update(theirHash).digest('base64'); - - if (this.hash2 === undefined) - this.hash2 = crypto.createHash(this.algorithm). - update(this.hash).digest('base64'); - - return (this.hash2 === theirHash2); -}; - -/*JSSTYLED*/ -var base64RE = /^[A-Za-z0-9+\/=]+$/; -/*JSSTYLED*/ -var hexRE = /^[a-fA-F0-9]+$/; - -Fingerprint.parse = function (fp, options) { - assert.string(fp, 'fingerprint'); - - var alg, hash, enAlgs; - if (Array.isArray(options)) { - enAlgs = options; - options = {}; - } - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - if (options.enAlgs !== undefined) - enAlgs = options.enAlgs; - if (options.algorithms !== undefined) - enAlgs = options.algorithms; - assert.optionalArrayOfString(enAlgs, 'algorithms'); - - var hashType = 'ssh'; - if (options.hashType !== undefined) - hashType = options.hashType; - assert.string(hashType, 'options.hashType'); - - var parts = fp.split(':'); - if (parts.length == 2) { - alg = parts[0].toLowerCase(); - if (!base64RE.test(parts[1])) - throw (new FingerprintFormatError(fp)); - try { - hash = Buffer.from(parts[1], 'base64'); - } catch (e) { - throw (new FingerprintFormatError(fp)); - } - } else if (parts.length > 2) { - alg = 'md5'; - if (parts[0].toLowerCase() === 'md5') - parts = parts.slice(1); - parts = parts.map(function (p) { - while (p.length < 2) - p = '0' + p; - if (p.length > 2) - throw (new FingerprintFormatError(fp)); - return (p); - }); - parts = parts.join(''); - if (!hexRE.test(parts) || parts.length % 2 !== 0) - throw (new FingerprintFormatError(fp)); - try { - hash = Buffer.from(parts, 'hex'); - } catch (e) { - throw (new FingerprintFormatError(fp)); - } - } else { - if (hexRE.test(fp)) { - hash = Buffer.from(fp, 'hex'); - } else if (base64RE.test(fp)) { - hash = Buffer.from(fp, 'base64'); - } else { - throw (new FingerprintFormatError(fp)); - } - - switch (hash.length) { - case 32: - alg = 'sha256'; - break; - case 16: - alg = 'md5'; - break; - case 20: - alg = 'sha1'; - break; - case 64: - alg = 'sha512'; - break; - default: - throw (new FingerprintFormatError(fp)); - } - - /* Plain hex/base64: guess it's probably SPKI unless told. */ - if (options.hashType === undefined) - hashType = 'spki'; - } - - if (alg === undefined) - throw (new FingerprintFormatError(fp)); - - if (algs.hashAlgs[alg] === undefined) - throw (new InvalidAlgorithmError(alg)); - - if (enAlgs !== undefined) { - enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); }); - if (enAlgs.indexOf(alg) === -1) - throw (new InvalidAlgorithmError(alg)); - } - - return (new Fingerprint({ - algorithm: alg, - hash: hash, - type: options.type || 'key', - hashType: hashType - })); -}; - -function addColons(s) { - /*JSSTYLED*/ - return (s.replace(/(.{2})(?=.)/g, '$1:')); -} - -function base64Strip(s) { - /*JSSTYLED*/ - return (s.replace(/=*$/, '')); -} - -function sshBase64Format(alg, h) { - return (alg.toUpperCase() + ':' + base64Strip(h)); -} - -Fingerprint.isFingerprint = function (obj, ver) { - return (utils.isCompatible(obj, Fingerprint, ver)); -}; - -/* - * API versions for Fingerprint: - * [1,0] -- initial ver - * [1,1] -- first tagged ver - * [1,2] -- hashType and spki support - */ -Fingerprint.prototype._sshpkApiVersion = [1, 2]; - -Fingerprint._oldVersionDetect = function (obj) { - assert.func(obj.toString); - assert.func(obj.matches); - return ([1, 0]); -}; - -},{"./algs":1689,"./certificate":1690,"./errors":1693,"./key":1709,"./private-key":1710,"./utils":1713,"assert-plus":77,"crypto":236,"safer-buffer":1594}],1695:[function(require,module,exports){ -// Copyright 2018 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); - -var pem = require('./pem'); -var ssh = require('./ssh'); -var rfc4253 = require('./rfc4253'); -var dnssec = require('./dnssec'); -var putty = require('./putty'); - -var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1'; - -function read(buf, options) { - if (typeof (buf) === 'string') { - if (buf.trim().match(/^[-]+[ ]*BEGIN/)) - return (pem.read(buf, options)); - if (buf.match(/^\s*ssh-[a-z]/)) - return (ssh.read(buf, options)); - if (buf.match(/^\s*ecdsa-/)) - return (ssh.read(buf, options)); - if (buf.match(/^putty-user-key-file-2:/i)) - return (putty.read(buf, options)); - if (findDNSSECHeader(buf)) - return (dnssec.read(buf, options)); - buf = Buffer.from(buf, 'binary'); - } else { - assert.buffer(buf); - if (findPEMHeader(buf)) - return (pem.read(buf, options)); - if (findSSHHeader(buf)) - return (ssh.read(buf, options)); - if (findPuTTYHeader(buf)) - return (putty.read(buf, options)); - if (findDNSSECHeader(buf)) - return (dnssec.read(buf, options)); - } - if (buf.readUInt32BE(0) < buf.length) - return (rfc4253.read(buf, options)); - throw (new Error('Failed to auto-detect format of key')); -} - -function findPuTTYHeader(buf) { - var offset = 0; - while (offset < buf.length && - (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) - ++offset; - if (offset + 22 <= buf.length && - buf.slice(offset, offset + 22).toString('ascii').toLowerCase() === - 'putty-user-key-file-2:') - return (true); - return (false); -} - -function findSSHHeader(buf) { - var offset = 0; - while (offset < buf.length && - (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) - ++offset; - if (offset + 4 <= buf.length && - buf.slice(offset, offset + 4).toString('ascii') === 'ssh-') - return (true); - if (offset + 6 <= buf.length && - buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-') - return (true); - return (false); -} - -function findPEMHeader(buf) { - var offset = 0; - while (offset < buf.length && - (buf[offset] === 32 || buf[offset] === 10)) - ++offset; - if (buf[offset] !== 45) - return (false); - while (offset < buf.length && - (buf[offset] === 45)) - ++offset; - while (offset < buf.length && - (buf[offset] === 32)) - ++offset; - if (offset + 5 > buf.length || - buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN') - return (false); - return (true); -} - -function findDNSSECHeader(buf) { - // private case first - if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length) - return (false); - var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length); - if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX) - return (true); - - // public-key RFC3110 ? - // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...' - // skip any comment-lines - if (typeof (buf) !== 'string') { - buf = buf.toString('ascii'); - } - var lines = buf.split('\n'); - var line = 0; - /* JSSTYLED */ - while (lines[line].match(/^\;/)) - line++; - if (lines[line].toString('ascii').match(/\. IN KEY /)) - return (true); - if (lines[line].toString('ascii').match(/\. IN DNSKEY /)) - return (true); - return (false); -} - -function write(key, options) { - throw (new Error('"auto" format cannot be used for writing')); -} - -},{"../key":1709,"../private-key":1710,"../utils":1713,"./dnssec":1696,"./pem":1698,"./putty":1701,"./rfc4253":1702,"./ssh":1704,"assert-plus":77,"safer-buffer":1594}],1696:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var utils = require('../utils'); -var SSHBuffer = require('../ssh-buffer'); -var Dhe = require('../dhe'); - -var supportedAlgos = { - 'rsa-sha1' : 5, - 'rsa-sha256' : 8, - 'rsa-sha512' : 10, - 'ecdsa-p256-sha256' : 13, - 'ecdsa-p384-sha384' : 14 - /* - * ed25519 is hypothetically supported with id 15 - * but the common tools available don't appear to be - * capable of generating/using ed25519 keys - */ -}; - -var supportedAlgosById = {}; -Object.keys(supportedAlgos).forEach(function (k) { - supportedAlgosById[supportedAlgos[k]] = k.toUpperCase(); -}); - -function read(buf, options) { - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } - var lines = buf.split('\n'); - if (lines[0].match(/^Private-key-format\: v1/)) { - var algElems = lines[1].split(' '); - var algoNum = parseInt(algElems[1], 10); - var algoName = algElems[2]; - if (!supportedAlgosById[algoNum]) - throw (new Error('Unsupported algorithm: ' + algoName)); - return (readDNSSECPrivateKey(algoNum, lines.slice(2))); - } - - // skip any comment-lines - var line = 0; - /* JSSTYLED */ - while (lines[line].match(/^\;/)) - line++; - // we should now have *one single* line left with our KEY on it. - if ((lines[line].match(/\. IN KEY /) || - lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) { - return (readRFC3110(lines[line])); - } - throw (new Error('Cannot parse dnssec key')); -} - -function readRFC3110(keyString) { - var elems = keyString.split(' '); - //unused var flags = parseInt(elems[3], 10); - //unused var protocol = parseInt(elems[4], 10); - var algorithm = parseInt(elems[5], 10); - if (!supportedAlgosById[algorithm]) - throw (new Error('Unsupported algorithm: ' + algorithm)); - var base64key = elems.slice(6, elems.length).join(); - var keyBuffer = Buffer.from(base64key, 'base64'); - if (supportedAlgosById[algorithm].match(/^RSA-/)) { - // join the rest of the body into a single base64-blob - var publicExponentLen = keyBuffer.readUInt8(0); - if (publicExponentLen != 3 && publicExponentLen != 1) - throw (new Error('Cannot parse dnssec key: ' + - 'unsupported exponent length')); - - var publicExponent = keyBuffer.slice(1, publicExponentLen+1); - publicExponent = utils.mpNormalize(publicExponent); - var modulus = keyBuffer.slice(1+publicExponentLen); - modulus = utils.mpNormalize(modulus); - // now, make the key - var rsaKey = { - type: 'rsa', - parts: [] - }; - rsaKey.parts.push({ name: 'e', data: publicExponent}); - rsaKey.parts.push({ name: 'n', data: modulus}); - return (new Key(rsaKey)); - } - if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' || - supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') { - var curve = 'nistp384'; - var size = 384; - if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) { - curve = 'nistp256'; - size = 256; - } - - var ecdsaKey = { - type: 'ecdsa', - curve: curve, - size: size, - parts: [ - {name: 'curve', data: Buffer.from(curve) }, - {name: 'Q', data: utils.ecNormalize(keyBuffer) } - ] - }; - return (new Key(ecdsaKey)); - } - throw (new Error('Unsupported algorithm: ' + - supportedAlgosById[algorithm])); -} - -function elementToBuf(e) { - return (Buffer.from(e.split(' ')[1], 'base64')); -} - -function readDNSSECRSAPrivateKey(elements) { - var rsaParams = {}; - elements.forEach(function (element) { - if (element.split(' ')[0] === 'Modulus:') - rsaParams['n'] = elementToBuf(element); - else if (element.split(' ')[0] === 'PublicExponent:') - rsaParams['e'] = elementToBuf(element); - else if (element.split(' ')[0] === 'PrivateExponent:') - rsaParams['d'] = elementToBuf(element); - else if (element.split(' ')[0] === 'Prime1:') - rsaParams['p'] = elementToBuf(element); - else if (element.split(' ')[0] === 'Prime2:') - rsaParams['q'] = elementToBuf(element); - else if (element.split(' ')[0] === 'Exponent1:') - rsaParams['dmodp'] = elementToBuf(element); - else if (element.split(' ')[0] === 'Exponent2:') - rsaParams['dmodq'] = elementToBuf(element); - else if (element.split(' ')[0] === 'Coefficient:') - rsaParams['iqmp'] = elementToBuf(element); - }); - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'e', data: utils.mpNormalize(rsaParams['e'])}, - { name: 'n', data: utils.mpNormalize(rsaParams['n'])}, - { name: 'd', data: utils.mpNormalize(rsaParams['d'])}, - { name: 'p', data: utils.mpNormalize(rsaParams['p'])}, - { name: 'q', data: utils.mpNormalize(rsaParams['q'])}, - { name: 'dmodp', - data: utils.mpNormalize(rsaParams['dmodp'])}, - { name: 'dmodq', - data: utils.mpNormalize(rsaParams['dmodq'])}, - { name: 'iqmp', - data: utils.mpNormalize(rsaParams['iqmp'])} - ] - }; - return (new PrivateKey(key)); -} - -function readDNSSECPrivateKey(alg, elements) { - if (supportedAlgosById[alg].match(/^RSA-/)) { - return (readDNSSECRSAPrivateKey(elements)); - } - if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' || - supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { - var d = Buffer.from(elements[0].split(' ')[1], 'base64'); - var curve = 'nistp384'; - var size = 384; - if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { - curve = 'nistp256'; - size = 256; - } - // DNSSEC generates the public-key on the fly (go calculate it) - var publicKey = utils.publicFromPrivateECDSA(curve, d); - var Q = publicKey.part['Q'].data; - var ecdsaKey = { - type: 'ecdsa', - curve: curve, - size: size, - parts: [ - {name: 'curve', data: Buffer.from(curve) }, - {name: 'd', data: d }, - {name: 'Q', data: Q } - ] - }; - return (new PrivateKey(ecdsaKey)); - } - throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg])); -} - -function dnssecTimestamp(date) { - var year = date.getFullYear() + ''; //stringify - var month = (date.getMonth() + 1); - var timestampStr = year + month + date.getUTCDate(); - timestampStr += '' + date.getUTCHours() + date.getUTCMinutes(); - timestampStr += date.getUTCSeconds(); - return (timestampStr); -} - -function rsaAlgFromOptions(opts) { - if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1') - return ('5 (RSASHA1)'); - else if (opts.hashAlgo === 'sha256') - return ('8 (RSASHA256)'); - else if (opts.hashAlgo === 'sha512') - return ('10 (RSASHA512)'); - else - throw (new Error('Unknown or unsupported hash: ' + - opts.hashAlgo)); -} - -function writeRSA(key, options) { - // if we're missing parts, add them. - if (!key.part.dmodp || !key.part.dmodq) { - utils.addRSAMissing(key); - } - - var out = ''; - out += 'Private-key-format: v1.3\n'; - out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n'; - var n = utils.mpDenormalize(key.part['n'].data); - out += 'Modulus: ' + n.toString('base64') + '\n'; - var e = utils.mpDenormalize(key.part['e'].data); - out += 'PublicExponent: ' + e.toString('base64') + '\n'; - var d = utils.mpDenormalize(key.part['d'].data); - out += 'PrivateExponent: ' + d.toString('base64') + '\n'; - var p = utils.mpDenormalize(key.part['p'].data); - out += 'Prime1: ' + p.toString('base64') + '\n'; - var q = utils.mpDenormalize(key.part['q'].data); - out += 'Prime2: ' + q.toString('base64') + '\n'; - var dmodp = utils.mpDenormalize(key.part['dmodp'].data); - out += 'Exponent1: ' + dmodp.toString('base64') + '\n'; - var dmodq = utils.mpDenormalize(key.part['dmodq'].data); - out += 'Exponent2: ' + dmodq.toString('base64') + '\n'; - var iqmp = utils.mpDenormalize(key.part['iqmp'].data); - out += 'Coefficient: ' + iqmp.toString('base64') + '\n'; - // Assume that we're valid as-of now - var timestamp = new Date(); - out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; - out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; - out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; - return (Buffer.from(out, 'ascii')); -} - -function writeECDSA(key, options) { - var out = ''; - out += 'Private-key-format: v1.3\n'; - - if (key.curve === 'nistp256') { - out += 'Algorithm: 13 (ECDSAP256SHA256)\n'; - } else if (key.curve === 'nistp384') { - out += 'Algorithm: 14 (ECDSAP384SHA384)\n'; - } else { - throw (new Error('Unsupported curve')); - } - var base64Key = key.part['d'].data.toString('base64'); - out += 'PrivateKey: ' + base64Key + '\n'; - - // Assume that we're valid as-of now - var timestamp = new Date(); - out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; - out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; - out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; - - return (Buffer.from(out, 'ascii')); -} - -function write(key, options) { - if (PrivateKey.isPrivateKey(key)) { - if (key.type === 'rsa') { - return (writeRSA(key, options)); - } else if (key.type === 'ecdsa') { - return (writeECDSA(key, options)); - } else { - throw (new Error('Unsupported algorithm: ' + key.type)); - } - } else if (Key.isKey(key)) { - /* - * RFC3110 requires a keyname, and a keytype, which we - * don't really have a mechanism for specifying such - * additional metadata. - */ - throw (new Error('Format "dnssec" only supports ' + - 'writing private keys')); - } else { - throw (new Error('key is not a Key or PrivateKey')); - } -} - -},{"../dhe":1691,"../key":1709,"../private-key":1710,"../ssh-buffer":1712,"../utils":1713,"assert-plus":77,"safer-buffer":1594}],1697:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = { - read: read, - verify: verify, - sign: sign, - signAsync: signAsync, - write: write, - - /* Internal private API */ - fromBuffer: fromBuffer, - toBuffer: toBuffer -}; - -var assert = require('assert-plus'); -var SSHBuffer = require('../ssh-buffer'); -var crypto = require('crypto'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var Identity = require('../identity'); -var rfc4253 = require('./rfc4253'); -var Signature = require('../signature'); -var utils = require('../utils'); -var Certificate = require('../certificate'); - -function verify(cert, key) { - /* - * We always give an issuerKey, so if our verify() is being called then - * there was no signature. Return false. - */ - return (false); -} - -var TYPES = { - 'user': 1, - 'host': 2 -}; -Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; }); - -var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/; - -function read(buf, options) { - if (Buffer.isBuffer(buf)) - buf = buf.toString('ascii'); - var parts = buf.trim().split(/[ \t\n]+/g); - if (parts.length < 2 || parts.length > 3) - throw (new Error('Not a valid SSH certificate line')); - - var algo = parts[0]; - var data = parts[1]; - - data = Buffer.from(data, 'base64'); - return (fromBuffer(data, algo)); -} - -function fromBuffer(data, algo, partial) { - var sshbuf = new SSHBuffer({ buffer: data }); - var innerAlgo = sshbuf.readString(); - if (algo !== undefined && innerAlgo !== algo) - throw (new Error('SSH certificate algorithm mismatch')); - if (algo === undefined) - algo = innerAlgo; - - var cert = {}; - cert.signatures = {}; - cert.signatures.openssh = {}; - - cert.signatures.openssh.nonce = sshbuf.readBuffer(); - - var key = {}; - var parts = (key.parts = []); - key.type = getAlg(algo); - - var partCount = algs.info[key.type].parts.length; - while (parts.length < partCount) - parts.push(sshbuf.readPart()); - assert.ok(parts.length >= 1, 'key must have at least one part'); - - var algInfo = algs.info[key.type]; - if (key.type === 'ecdsa') { - var res = ECDSA_ALGO.exec(algo); - assert.ok(res !== null); - assert.strictEqual(res[1], parts[0].data.toString()); - } - - for (var i = 0; i < algInfo.parts.length; ++i) { - parts[i].name = algInfo.parts[i]; - if (parts[i].name !== 'curve' && - algInfo.normalize !== false) { - var p = parts[i]; - p.data = utils.mpNormalize(p.data); - } - } - - cert.subjectKey = new Key(key); - - cert.serial = sshbuf.readInt64(); - - var type = TYPES[sshbuf.readInt()]; - assert.string(type, 'valid cert type'); - - cert.signatures.openssh.keyId = sshbuf.readString(); - - var principals = []; - var pbuf = sshbuf.readBuffer(); - var psshbuf = new SSHBuffer({ buffer: pbuf }); - while (!psshbuf.atEnd()) - principals.push(psshbuf.readString()); - if (principals.length === 0) - principals = ['*']; - - cert.subjects = principals.map(function (pr) { - if (type === 'user') - return (Identity.forUser(pr)); - else if (type === 'host') - return (Identity.forHost(pr)); - throw (new Error('Unknown identity type ' + type)); - }); - - cert.validFrom = int64ToDate(sshbuf.readInt64()); - cert.validUntil = int64ToDate(sshbuf.readInt64()); - - var exts = []; - var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); - var ext; - while (!extbuf.atEnd()) { - ext = { critical: true }; - ext.name = extbuf.readString(); - ext.data = extbuf.readBuffer(); - exts.push(ext); - } - extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); - while (!extbuf.atEnd()) { - ext = { critical: false }; - ext.name = extbuf.readString(); - ext.data = extbuf.readBuffer(); - exts.push(ext); - } - cert.signatures.openssh.exts = exts; - - /* reserved */ - sshbuf.readBuffer(); - - var signingKeyBuf = sshbuf.readBuffer(); - cert.issuerKey = rfc4253.read(signingKeyBuf); - - /* - * OpenSSH certs don't give the identity of the issuer, just their - * public key. So, we use an Identity that matches anything. The - * isSignedBy() function will later tell you if the key matches. - */ - cert.issuer = Identity.forHost('**'); - - var sigBuf = sshbuf.readBuffer(); - cert.signatures.openssh.signature = - Signature.parse(sigBuf, cert.issuerKey.type, 'ssh'); - - if (partial !== undefined) { - partial.remainder = sshbuf.remainder(); - partial.consumed = sshbuf._offset; - } - - return (new Certificate(cert)); -} - -function int64ToDate(buf) { - var i = buf.readUInt32BE(0) * 4294967296; - i += buf.readUInt32BE(4); - var d = new Date(); - d.setTime(i * 1000); - d.sourceInt64 = buf; - return (d); -} - -function dateToInt64(date) { - if (date.sourceInt64 !== undefined) - return (date.sourceInt64); - var i = Math.round(date.getTime() / 1000); - var upper = Math.floor(i / 4294967296); - var lower = Math.floor(i % 4294967296); - var buf = Buffer.alloc(8); - buf.writeUInt32BE(upper, 0); - buf.writeUInt32BE(lower, 4); - return (buf); -} - -function sign(cert, key) { - if (cert.signatures.openssh === undefined) - cert.signatures.openssh = {}; - try { - var blob = toBuffer(cert, true); - } catch (e) { - delete (cert.signatures.openssh); - return (false); - } - var sig = cert.signatures.openssh; - var hashAlgo = undefined; - if (key.type === 'rsa' || key.type === 'dsa') - hashAlgo = 'sha1'; - var signer = key.createSign(hashAlgo); - signer.write(blob); - sig.signature = signer.sign(); - return (true); -} - -function signAsync(cert, signer, done) { - if (cert.signatures.openssh === undefined) - cert.signatures.openssh = {}; - try { - var blob = toBuffer(cert, true); - } catch (e) { - delete (cert.signatures.openssh); - done(e); - return; - } - var sig = cert.signatures.openssh; - - signer(blob, function (err, signature) { - if (err) { - done(err); - return; - } - try { - /* - * This will throw if the signature isn't of a - * type/algo that can be used for SSH. - */ - signature.toBuffer('ssh'); - } catch (e) { - done(e); - return; - } - sig.signature = signature; - done(); - }); -} - -function write(cert, options) { - if (options === undefined) - options = {}; - - var blob = toBuffer(cert); - var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64'); - if (options.comment) - out = out + ' ' + options.comment; - return (out); -} - - -function toBuffer(cert, noSig) { - assert.object(cert.signatures.openssh, 'signature for openssh format'); - var sig = cert.signatures.openssh; - - if (sig.nonce === undefined) - sig.nonce = crypto.randomBytes(16); - var buf = new SSHBuffer({}); - buf.writeString(getCertType(cert.subjectKey)); - buf.writeBuffer(sig.nonce); - - var key = cert.subjectKey; - var algInfo = algs.info[key.type]; - algInfo.parts.forEach(function (part) { - buf.writePart(key.part[part]); - }); - - buf.writeInt64(cert.serial); - - var type = cert.subjects[0].type; - assert.notStrictEqual(type, 'unknown'); - cert.subjects.forEach(function (id) { - assert.strictEqual(id.type, type); - }); - type = TYPES[type]; - buf.writeInt(type); - - if (sig.keyId === undefined) { - sig.keyId = cert.subjects[0].type + '_' + - (cert.subjects[0].uid || cert.subjects[0].hostname); - } - buf.writeString(sig.keyId); - - var sub = new SSHBuffer({}); - cert.subjects.forEach(function (id) { - if (type === TYPES.host) - sub.writeString(id.hostname); - else if (type === TYPES.user) - sub.writeString(id.uid); - }); - buf.writeBuffer(sub.toBuffer()); - - buf.writeInt64(dateToInt64(cert.validFrom)); - buf.writeInt64(dateToInt64(cert.validUntil)); - - var exts = sig.exts; - if (exts === undefined) - exts = []; - - var extbuf = new SSHBuffer({}); - exts.forEach(function (ext) { - if (ext.critical !== true) - return; - extbuf.writeString(ext.name); - extbuf.writeBuffer(ext.data); - }); - buf.writeBuffer(extbuf.toBuffer()); - - extbuf = new SSHBuffer({}); - exts.forEach(function (ext) { - if (ext.critical === true) - return; - extbuf.writeString(ext.name); - extbuf.writeBuffer(ext.data); - }); - buf.writeBuffer(extbuf.toBuffer()); - - /* reserved */ - buf.writeBuffer(Buffer.alloc(0)); - - sub = rfc4253.write(cert.issuerKey); - buf.writeBuffer(sub); - - if (!noSig) - buf.writeBuffer(sig.signature.toBuffer('ssh')); - - return (buf.toBuffer()); -} - -function getAlg(certType) { - if (certType === 'ssh-rsa-cert-v01@openssh.com') - return ('rsa'); - if (certType === 'ssh-dss-cert-v01@openssh.com') - return ('dsa'); - if (certType.match(ECDSA_ALGO)) - return ('ecdsa'); - if (certType === 'ssh-ed25519-cert-v01@openssh.com') - return ('ed25519'); - throw (new Error('Unsupported cert type ' + certType)); -} - -function getCertType(key) { - if (key.type === 'rsa') - return ('ssh-rsa-cert-v01@openssh.com'); - if (key.type === 'dsa') - return ('ssh-dss-cert-v01@openssh.com'); - if (key.type === 'ecdsa') - return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com'); - if (key.type === 'ed25519') - return ('ssh-ed25519-cert-v01@openssh.com'); - throw (new Error('Unsupported key type ' + key.type)); -} - -},{"../algs":1689,"../certificate":1690,"../identity":1707,"../key":1709,"../private-key":1710,"../signature":1711,"../ssh-buffer":1712,"../utils":1713,"./rfc4253":1702,"assert-plus":77,"crypto":236,"safer-buffer":1594}],1698:[function(require,module,exports){ -// Copyright 2018 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var crypto = require('crypto'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); - -var pkcs1 = require('./pkcs1'); -var pkcs8 = require('./pkcs8'); -var sshpriv = require('./ssh-private'); -var rfc4253 = require('./rfc4253'); - -var errors = require('../errors'); - -var OID_PBES2 = '1.2.840.113549.1.5.13'; -var OID_PBKDF2 = '1.2.840.113549.1.5.12'; - -var OID_TO_CIPHER = { - '1.2.840.113549.3.7': '3des-cbc', - '2.16.840.1.101.3.4.1.2': 'aes128-cbc', - '2.16.840.1.101.3.4.1.42': 'aes256-cbc' -}; -var CIPHER_TO_OID = {}; -Object.keys(OID_TO_CIPHER).forEach(function (k) { - CIPHER_TO_OID[OID_TO_CIPHER[k]] = k; -}); - -var OID_TO_HASH = { - '1.2.840.113549.2.7': 'sha1', - '1.2.840.113549.2.9': 'sha256', - '1.2.840.113549.2.11': 'sha512' -}; -var HASH_TO_OID = {}; -Object.keys(OID_TO_HASH).forEach(function (k) { - HASH_TO_OID[OID_TO_HASH[k]] = k; -}); - -/* - * For reading we support both PKCS#1 and PKCS#8. If we find a private key, - * we just take the public component of it and use that. - */ -function read(buf, options, forceType) { - var input = buf; - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } - - var lines = buf.trim().split(/[\r\n]+/g); - - var m; - var si = -1; - while (!m && si < lines.length) { - m = lines[++si].match(/*JSSTYLED*/ - /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); - } - assert.ok(m, 'invalid PEM header'); - - var m2; - var ei = lines.length; - while (!m2 && ei > 0) { - m2 = lines[--ei].match(/*JSSTYLED*/ - /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); - } - assert.ok(m2, 'invalid PEM footer'); - - /* Begin and end banners must match key type */ - assert.equal(m[2], m2[2]); - var type = m[2].toLowerCase(); - - var alg; - if (m[1]) { - /* They also must match algorithms, if given */ - assert.equal(m[1], m2[1], 'PEM header and footer mismatch'); - alg = m[1].trim(); - } - - lines = lines.slice(si, ei + 1); - - var headers = {}; - while (true) { - lines = lines.slice(1); - m = lines[0].match(/*JSSTYLED*/ - /^([A-Za-z0-9-]+): (.+)$/); - if (!m) - break; - headers[m[1].toLowerCase()] = m[2]; - } - - /* Chop off the first and last lines */ - lines = lines.slice(0, -1).join(''); - buf = Buffer.from(lines, 'base64'); - - var cipher, key, iv; - if (headers['proc-type']) { - var parts = headers['proc-type'].split(','); - if (parts[0] === '4' && parts[1] === 'ENCRYPTED') { - if (typeof (options.passphrase) === 'string') { - options.passphrase = Buffer.from( - options.passphrase, 'utf-8'); - } - if (!Buffer.isBuffer(options.passphrase)) { - throw (new errors.KeyEncryptedError( - options.filename, 'PEM')); - } else { - parts = headers['dek-info'].split(','); - assert.ok(parts.length === 2); - cipher = parts[0].toLowerCase(); - iv = Buffer.from(parts[1], 'hex'); - key = utils.opensslKeyDeriv(cipher, iv, - options.passphrase, 1).key; - } - } - } - - if (alg && alg.toLowerCase() === 'encrypted') { - var eder = new asn1.BerReader(buf); - var pbesEnd; - eder.readSequence(); - - eder.readSequence(); - pbesEnd = eder.offset + eder.length; - - var method = eder.readOID(); - if (method !== OID_PBES2) { - throw (new Error('Unsupported PEM/PKCS8 encryption ' + - 'scheme: ' + method)); - } - - eder.readSequence(); /* PBES2-params */ - - eder.readSequence(); /* keyDerivationFunc */ - var kdfEnd = eder.offset + eder.length; - var kdfOid = eder.readOID(); - if (kdfOid !== OID_PBKDF2) - throw (new Error('Unsupported PBES2 KDF: ' + kdfOid)); - eder.readSequence(); - var salt = eder.readString(asn1.Ber.OctetString, true); - var iterations = eder.readInt(); - var hashAlg = 'sha1'; - if (eder.offset < kdfEnd) { - eder.readSequence(); - var hashAlgOid = eder.readOID(); - hashAlg = OID_TO_HASH[hashAlgOid]; - if (hashAlg === undefined) { - throw (new Error('Unsupported PBKDF2 hash: ' + - hashAlgOid)); - } - } - eder._offset = kdfEnd; - - eder.readSequence(); /* encryptionScheme */ - var cipherOid = eder.readOID(); - cipher = OID_TO_CIPHER[cipherOid]; - if (cipher === undefined) { - throw (new Error('Unsupported PBES2 cipher: ' + - cipherOid)); - } - iv = eder.readString(asn1.Ber.OctetString, true); - - eder._offset = pbesEnd; - buf = eder.readString(asn1.Ber.OctetString, true); - - if (typeof (options.passphrase) === 'string') { - options.passphrase = Buffer.from( - options.passphrase, 'utf-8'); - } - if (!Buffer.isBuffer(options.passphrase)) { - throw (new errors.KeyEncryptedError( - options.filename, 'PEM')); - } - - var cinfo = utils.opensshCipherInfo(cipher); - - cipher = cinfo.opensslName; - key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize, - options.passphrase); - alg = undefined; - } - - if (cipher && key && iv) { - var cipherStream = crypto.createDecipheriv(cipher, key, iv); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - if (e.toString().indexOf('bad decrypt') !== -1) { - throw (new Error('Incorrect passphrase ' + - 'supplied, could not decrypt key')); - } - throw (e); - }); - cipherStream.write(buf); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - buf = Buffer.concat(chunks); - } - - /* The new OpenSSH internal format abuses PEM headers */ - if (alg && alg.toLowerCase() === 'openssh') - return (sshpriv.readSSHPrivate(type, buf, options)); - if (alg && alg.toLowerCase() === 'ssh2') - return (rfc4253.readType(type, buf, options)); - - var der = new asn1.BerReader(buf); - der.originalInput = input; - - /* - * All of the PEM file types start with a sequence tag, so chop it - * off here - */ - der.readSequence(); - - /* PKCS#1 type keys name an algorithm in the banner explicitly */ - if (alg) { - if (forceType) - assert.strictEqual(forceType, 'pkcs1'); - return (pkcs1.readPkcs1(alg, type, der)); - } else { - if (forceType) - assert.strictEqual(forceType, 'pkcs8'); - return (pkcs8.readPkcs8(alg, type, der)); - } -} - -function write(key, options, type) { - assert.object(key); - - var alg = { - 'ecdsa': 'EC', - 'rsa': 'RSA', - 'dsa': 'DSA', - 'ed25519': 'EdDSA' - }[key.type]; - var header; - - var der = new asn1.BerWriter(); - - if (PrivateKey.isPrivateKey(key)) { - if (type && type === 'pkcs8') { - header = 'PRIVATE KEY'; - pkcs8.writePkcs8(der, key); - } else { - if (type) - assert.strictEqual(type, 'pkcs1'); - header = alg + ' PRIVATE KEY'; - pkcs1.writePkcs1(der, key); - } - - } else if (Key.isKey(key)) { - if (type && type === 'pkcs1') { - header = alg + ' PUBLIC KEY'; - pkcs1.writePkcs1(der, key); - } else { - if (type) - assert.strictEqual(type, 'pkcs8'); - header = 'PUBLIC KEY'; - pkcs8.writePkcs8(der, key); - } - - } else { - throw (new Error('key is not a Key or PrivateKey')); - } - - var tmp = der.buffer.toString('base64'); - var len = tmp.length + (tmp.length / 64) + - 18 + 16 + header.length*2 + 10; - var buf = Buffer.alloc(len); - var o = 0; - o += buf.write('-----BEGIN ' + header + '-----\n', o); - for (var i = 0; i < tmp.length; ) { - var limit = i + 64; - if (limit > tmp.length) - limit = tmp.length; - o += buf.write(tmp.slice(i, limit), o); - buf[o++] = 10; - i = limit; - } - o += buf.write('-----END ' + header + '-----\n', o); - - return (buf.slice(0, o)); -} - -},{"../algs":1689,"../errors":1693,"../key":1709,"../private-key":1710,"../utils":1713,"./pkcs1":1699,"./pkcs8":1700,"./rfc4253":1702,"./ssh-private":1703,"asn1":75,"assert-plus":77,"crypto":236,"safer-buffer":1594}],1699:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - read: read, - readPkcs1: readPkcs1, - write: write, - writePkcs1: writePkcs1 -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); - -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var pem = require('./pem'); - -var pkcs8 = require('./pkcs8'); -var readECDSACurve = pkcs8.readECDSACurve; - -function read(buf, options) { - return (pem.read(buf, options, 'pkcs1')); -} - -function write(key, options) { - return (pem.write(key, options, 'pkcs1')); -} - -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); -} - -function readPkcs1(alg, type, der) { - switch (alg) { - case 'RSA': - if (type === 'public') - return (readPkcs1RSAPublic(der)); - else if (type === 'private') - return (readPkcs1RSAPrivate(der)); - throw (new Error('Unknown key type: ' + type)); - case 'DSA': - if (type === 'public') - return (readPkcs1DSAPublic(der)); - else if (type === 'private') - return (readPkcs1DSAPrivate(der)); - throw (new Error('Unknown key type: ' + type)); - case 'EC': - case 'ECDSA': - if (type === 'private') - return (readPkcs1ECDSAPrivate(der)); - else if (type === 'public') - return (readPkcs1ECDSAPublic(der)); - throw (new Error('Unknown key type: ' + type)); - case 'EDDSA': - case 'EdDSA': - if (type === 'private') - return (readPkcs1EdDSAPrivate(der)); - throw (new Error(type + ' keys not supported with EdDSA')); - default: - throw (new Error('Unknown key algo: ' + alg)); - } -} - -function readPkcs1RSAPublic(der) { - // modulus and exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'exponent'); - - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'e', data: e }, - { name: 'n', data: n } - ] - }; - - return (new Key(key)); -} - -function readPkcs1RSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version[0], 0); - - // modulus then public exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'public exponent'); - var d = readMPInt(der, 'private exponent'); - var p = readMPInt(der, 'prime1'); - var q = readMPInt(der, 'prime2'); - var dmodp = readMPInt(der, 'exponent1'); - var dmodq = readMPInt(der, 'exponent2'); - var iqmp = readMPInt(der, 'iqmp'); - - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'n', data: n }, - { name: 'e', data: e }, - { name: 'd', data: d }, - { name: 'iqmp', data: iqmp }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'dmodp', data: dmodp }, - { name: 'dmodq', data: dmodq } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs1DSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version.readUInt8(0), 0); - - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); - var y = readMPInt(der, 'y'); - var x = readMPInt(der, 'x'); - - // now, make the key - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y }, - { name: 'x', data: x } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs1EdDSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version.readUInt8(0), 1); - - // private key - var k = der.readString(asn1.Ber.OctetString, true); - - der.readSequence(0xa0); - var oid = der.readOID(); - assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier'); - - der.readSequence(0xa1); - var A = utils.readBitString(der); - - var key = { - type: 'ed25519', - parts: [ - { name: 'A', data: utils.zeroPadToLength(A, 32) }, - { name: 'k', data: k } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs1DSAPublic(der) { - var y = readMPInt(der, 'y'); - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); - - var key = { - type: 'dsa', - parts: [ - { name: 'y', data: y }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g } - ] - }; - - return (new Key(key)); -} - -function readPkcs1ECDSAPublic(der) { - der.readSequence(); - - var oid = der.readOID(); - assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); - - var curveOid = der.readOID(); - - var curve; - var curves = Object.keys(algs.curves); - for (var j = 0; j < curves.length; ++j) { - var c = curves[j]; - var cd = algs.curves[c]; - if (cd.pkcs8oid === curveOid) { - curve = c; - break; - } - } - assert.string(curve, 'a known ECDSA named curve'); - - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); - - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: Buffer.from(curve) }, - { name: 'Q', data: Q } - ] - }; - - return (new Key(key)); -} - -function readPkcs1ECDSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version.readUInt8(0), 1); - - // private key - var d = der.readString(asn1.Ber.OctetString, true); - - der.readSequence(0xa0); - var curve = readECDSACurve(der); - assert.string(curve, 'a known elliptic curve'); - - der.readSequence(0xa1); - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); - - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: Buffer.from(curve) }, - { name: 'Q', data: Q }, - { name: 'd', data: d } - ] - }; - - return (new PrivateKey(key)); -} - -function writePkcs1(der, key) { - der.startSequence(); - - switch (key.type) { - case 'rsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1RSAPrivate(der, key); - else - writePkcs1RSAPublic(der, key); - break; - case 'dsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1DSAPrivate(der, key); - else - writePkcs1DSAPublic(der, key); - break; - case 'ecdsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1ECDSAPrivate(der, key); - else - writePkcs1ECDSAPublic(der, key); - break; - case 'ed25519': - if (PrivateKey.isPrivateKey(key)) - writePkcs1EdDSAPrivate(der, key); - else - writePkcs1EdDSAPublic(der, key); - break; - default: - throw (new Error('Unknown key algo: ' + key.type)); - } - - der.endSequence(); -} - -function writePkcs1RSAPublic(der, key) { - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); -} - -function writePkcs1RSAPrivate(der, key) { - var ver = Buffer.from([0]); - der.writeBuffer(ver, asn1.Ber.Integer); - - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.writeBuffer(key.part.d.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - if (!key.part.dmodp || !key.part.dmodq) - utils.addRSAMissing(key); - der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); - der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); - der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); -} - -function writePkcs1DSAPrivate(der, key) { - var ver = Buffer.from([0]); - der.writeBuffer(ver, asn1.Ber.Integer); - - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.writeBuffer(key.part.x.data, asn1.Ber.Integer); -} - -function writePkcs1DSAPublic(der, key) { - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); -} - -function writePkcs1ECDSAPublic(der, key) { - der.startSequence(); - - der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ - var curve = key.part.curve.data.toString(); - var curveOid = algs.curves[curve].pkcs8oid; - assert.string(curveOid, 'a known ECDSA named curve'); - der.writeOID(curveOid); - - der.endSequence(); - - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); -} - -function writePkcs1ECDSAPrivate(der, key) { - var ver = Buffer.from([1]); - der.writeBuffer(ver, asn1.Ber.Integer); - - der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); - - der.startSequence(0xa0); - var curve = key.part.curve.data.toString(); - var curveOid = algs.curves[curve].pkcs8oid; - assert.string(curveOid, 'a known ECDSA named curve'); - der.writeOID(curveOid); - der.endSequence(); - - der.startSequence(0xa1); - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); - der.endSequence(); -} - -function writePkcs1EdDSAPrivate(der, key) { - var ver = Buffer.from([1]); - der.writeBuffer(ver, asn1.Ber.Integer); - - der.writeBuffer(key.part.k.data, asn1.Ber.OctetString); - - der.startSequence(0xa0); - der.writeOID('1.3.101.112'); - der.endSequence(); - - der.startSequence(0xa1); - utils.writeBitString(der, key.part.A.data); - der.endSequence(); -} - -function writePkcs1EdDSAPublic(der, key) { - throw (new Error('Public keys are not supported for EdDSA PKCS#1')); -} - -},{"../algs":1689,"../key":1709,"../private-key":1710,"../utils":1713,"./pem":1698,"./pkcs8":1700,"asn1":75,"assert-plus":77,"safer-buffer":1594}],1700:[function(require,module,exports){ -// Copyright 2018 Joyent, Inc. - -module.exports = { - read: read, - readPkcs8: readPkcs8, - write: write, - writePkcs8: writePkcs8, - pkcs8ToBuffer: pkcs8ToBuffer, - - readECDSACurve: readECDSACurve, - writeECDSACurve: writeECDSACurve -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var pem = require('./pem'); - -function read(buf, options) { - return (pem.read(buf, options, 'pkcs8')); -} - -function write(key, options) { - return (pem.write(key, options, 'pkcs8')); -} - -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); -} - -function readPkcs8(alg, type, der) { - /* Private keys in pkcs#8 format have a weird extra int */ - if (der.peek() === asn1.Ber.Integer) { - assert.strictEqual(type, 'private', - 'unexpected Integer at start of public key'); - der.readString(asn1.Ber.Integer, true); - } - - der.readSequence(); - var next = der.offset + der.length; - - var oid = der.readOID(); - switch (oid) { - case '1.2.840.113549.1.1.1': - der._offset = next; - if (type === 'public') - return (readPkcs8RSAPublic(der)); - else - return (readPkcs8RSAPrivate(der)); - case '1.2.840.10040.4.1': - if (type === 'public') - return (readPkcs8DSAPublic(der)); - else - return (readPkcs8DSAPrivate(der)); - case '1.2.840.10045.2.1': - if (type === 'public') - return (readPkcs8ECDSAPublic(der)); - else - return (readPkcs8ECDSAPrivate(der)); - case '1.3.101.112': - if (type === 'public') { - return (readPkcs8EdDSAPublic(der)); - } else { - return (readPkcs8EdDSAPrivate(der)); - } - case '1.3.101.110': - if (type === 'public') { - return (readPkcs8X25519Public(der)); - } else { - return (readPkcs8X25519Private(der)); - } - default: - throw (new Error('Unknown key type OID ' + oid)); - } -} - -function readPkcs8RSAPublic(der) { - // bit string sequence - der.readSequence(asn1.Ber.BitString); - der.readByte(); - der.readSequence(); - - // modulus - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'exponent'); - - // now, make the key - var key = { - type: 'rsa', - source: der.originalInput, - parts: [ - { name: 'e', data: e }, - { name: 'n', data: n } - ] - }; - - return (new Key(key)); -} - -function readPkcs8RSAPrivate(der) { - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - - var ver = readMPInt(der, 'version'); - assert.equal(ver[0], 0x0, 'unknown RSA private key version'); - - // modulus then public exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'public exponent'); - var d = readMPInt(der, 'private exponent'); - var p = readMPInt(der, 'prime1'); - var q = readMPInt(der, 'prime2'); - var dmodp = readMPInt(der, 'exponent1'); - var dmodq = readMPInt(der, 'exponent2'); - var iqmp = readMPInt(der, 'iqmp'); - - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'n', data: n }, - { name: 'e', data: e }, - { name: 'd', data: d }, - { name: 'iqmp', data: iqmp }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'dmodp', data: dmodp }, - { name: 'dmodq', data: dmodq } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs8DSAPublic(der) { - der.readSequence(); - - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); - - // bit string sequence - der.readSequence(asn1.Ber.BitString); - der.readByte(); - - var y = readMPInt(der, 'y'); - - // now, make the key - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y } - ] - }; - - return (new Key(key)); -} - -function readPkcs8DSAPrivate(der) { - der.readSequence(); - - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); - - der.readSequence(asn1.Ber.OctetString); - var x = readMPInt(der, 'x'); - - /* The pkcs#8 format does not include the public key */ - var y = utils.calculateDSAPublic(g, p, x); - - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y }, - { name: 'x', data: x } - ] - }; - - return (new PrivateKey(key)); -} - -function readECDSACurve(der) { - var curveName, curveNames; - var j, c, cd; - - if (der.peek() === asn1.Ber.OID) { - var oid = der.readOID(); - - curveNames = Object.keys(algs.curves); - for (j = 0; j < curveNames.length; ++j) { - c = curveNames[j]; - cd = algs.curves[c]; - if (cd.pkcs8oid === oid) { - curveName = c; - break; - } - } - - } else { - // ECParameters sequence - der.readSequence(); - var version = der.readString(asn1.Ber.Integer, true); - assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); - - var curve = {}; - - // FieldID sequence - der.readSequence(); - var fieldTypeOid = der.readOID(); - assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', - 'ECDSA key is not from a prime-field'); - var p = curve.p = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - /* - * p always starts with a 1 bit, so count the zeros to get its - * real size. - */ - curve.size = p.length * 8 - utils.countZeros(p); - - // Curve sequence - der.readSequence(); - curve.a = utils.mpNormalize( - der.readString(asn1.Ber.OctetString, true)); - curve.b = utils.mpNormalize( - der.readString(asn1.Ber.OctetString, true)); - if (der.peek() === asn1.Ber.BitString) - curve.s = der.readString(asn1.Ber.BitString, true); - - // Combined Gx and Gy - curve.G = der.readString(asn1.Ber.OctetString, true); - assert.strictEqual(curve.G[0], 0x4, - 'uncompressed G is required'); - - curve.n = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - curve.h = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + - 'required'); - - curveNames = Object.keys(algs.curves); - var ks = Object.keys(curve); - for (j = 0; j < curveNames.length; ++j) { - c = curveNames[j]; - cd = algs.curves[c]; - var equal = true; - for (var i = 0; i < ks.length; ++i) { - var k = ks[i]; - if (cd[k] === undefined) - continue; - if (typeof (cd[k]) === 'object' && - cd[k].equals !== undefined) { - if (!cd[k].equals(curve[k])) { - equal = false; - break; - } - } else if (Buffer.isBuffer(cd[k])) { - if (cd[k].toString('binary') - !== curve[k].toString('binary')) { - equal = false; - break; - } - } else { - if (cd[k] !== curve[k]) { - equal = false; - break; - } - } - } - if (equal) { - curveName = c; - break; - } - } - } - return (curveName); -} - -function readPkcs8ECDSAPrivate(der) { - var curveName = readECDSACurve(der); - assert.string(curveName, 'a known elliptic curve'); - - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - - var version = readMPInt(der, 'version'); - assert.equal(version[0], 1, 'unknown version of ECDSA key'); - - var d = der.readString(asn1.Ber.OctetString, true); - var Q; - - if (der.peek() == 0xa0) { - der.readSequence(0xa0); - der._offset += der.length; - } - if (der.peek() == 0xa1) { - der.readSequence(0xa1); - Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); - } - - if (Q === undefined) { - var pub = utils.publicFromPrivateECDSA(curveName, d); - Q = pub.part.Q.data; - } - - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: Buffer.from(curveName) }, - { name: 'Q', data: Q }, - { name: 'd', data: d } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs8ECDSAPublic(der) { - var curveName = readECDSACurve(der); - assert.string(curveName, 'a known elliptic curve'); - - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); - - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: Buffer.from(curveName) }, - { name: 'Q', data: Q } - ] - }; - - return (new Key(key)); -} - -function readPkcs8EdDSAPublic(der) { - if (der.peek() === 0x00) - der.readByte(); - - var A = utils.readBitString(der); - - var key = { - type: 'ed25519', - parts: [ - { name: 'A', data: utils.zeroPadToLength(A, 32) } - ] - }; - - return (new Key(key)); -} - -function readPkcs8X25519Public(der) { - var A = utils.readBitString(der); - - var key = { - type: 'curve25519', - parts: [ - { name: 'A', data: utils.zeroPadToLength(A, 32) } - ] - }; - - return (new Key(key)); -} - -function readPkcs8EdDSAPrivate(der) { - if (der.peek() === 0x00) - der.readByte(); - - der.readSequence(asn1.Ber.OctetString); - var k = der.readString(asn1.Ber.OctetString, true); - k = utils.zeroPadToLength(k, 32); - - var A; - if (der.peek() === asn1.Ber.BitString) { - A = utils.readBitString(der); - A = utils.zeroPadToLength(A, 32); - } else { - A = utils.calculateED25519Public(k); - } - - var key = { - type: 'ed25519', - parts: [ - { name: 'A', data: utils.zeroPadToLength(A, 32) }, - { name: 'k', data: utils.zeroPadToLength(k, 32) } - ] - }; - - return (new PrivateKey(key)); -} - -function readPkcs8X25519Private(der) { - if (der.peek() === 0x00) - der.readByte(); - - der.readSequence(asn1.Ber.OctetString); - var k = der.readString(asn1.Ber.OctetString, true); - k = utils.zeroPadToLength(k, 32); - - var A = utils.calculateX25519Public(k); - - var key = { - type: 'curve25519', - parts: [ - { name: 'A', data: utils.zeroPadToLength(A, 32) }, - { name: 'k', data: utils.zeroPadToLength(k, 32) } - ] - }; - - return (new PrivateKey(key)); -} - -function pkcs8ToBuffer(key) { - var der = new asn1.BerWriter(); - writePkcs8(der, key); - return (der.buffer); -} - -function writePkcs8(der, key) { - der.startSequence(); - - if (PrivateKey.isPrivateKey(key)) { - var sillyInt = Buffer.from([0]); - der.writeBuffer(sillyInt, asn1.Ber.Integer); - } - - der.startSequence(); - switch (key.type) { - case 'rsa': - der.writeOID('1.2.840.113549.1.1.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8RSAPrivate(key, der); - else - writePkcs8RSAPublic(key, der); - break; - case 'dsa': - der.writeOID('1.2.840.10040.4.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8DSAPrivate(key, der); - else - writePkcs8DSAPublic(key, der); - break; - case 'ecdsa': - der.writeOID('1.2.840.10045.2.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8ECDSAPrivate(key, der); - else - writePkcs8ECDSAPublic(key, der); - break; - case 'ed25519': - der.writeOID('1.3.101.112'); - if (PrivateKey.isPrivateKey(key)) - throw (new Error('Ed25519 private keys in pkcs8 ' + - 'format are not supported')); - writePkcs8EdDSAPublic(key, der); - break; - default: - throw (new Error('Unsupported key type: ' + key.type)); - } - - der.endSequence(); -} - -function writePkcs8RSAPrivate(key, der) { - der.writeNull(); - der.endSequence(); - - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - - var version = Buffer.from([0]); - der.writeBuffer(version, asn1.Ber.Integer); - - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.writeBuffer(key.part.d.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - if (!key.part.dmodp || !key.part.dmodq) - utils.addRSAMissing(key); - der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); - der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); - der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); - - der.endSequence(); - der.endSequence(); -} - -function writePkcs8RSAPublic(key, der) { - der.writeNull(); - der.endSequence(); - - der.startSequence(asn1.Ber.BitString); - der.writeByte(0x00); - - der.startSequence(); - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.endSequence(); - - der.endSequence(); -} - -function writePkcs8DSAPrivate(key, der) { - der.startSequence(); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.endSequence(); - - der.endSequence(); - - der.startSequence(asn1.Ber.OctetString); - der.writeBuffer(key.part.x.data, asn1.Ber.Integer); - der.endSequence(); -} - -function writePkcs8DSAPublic(key, der) { - der.startSequence(); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.endSequence(); - der.endSequence(); - - der.startSequence(asn1.Ber.BitString); - der.writeByte(0x00); - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.endSequence(); -} - -function writeECDSACurve(key, der) { - var curve = algs.curves[key.curve]; - if (curve.pkcs8oid) { - /* This one has a name in pkcs#8, so just write the oid */ - der.writeOID(curve.pkcs8oid); - - } else { - // ECParameters sequence - der.startSequence(); - - var version = Buffer.from([1]); - der.writeBuffer(version, asn1.Ber.Integer); - - // FieldID sequence - der.startSequence(); - der.writeOID('1.2.840.10045.1.1'); // prime-field - der.writeBuffer(curve.p, asn1.Ber.Integer); - der.endSequence(); - - // Curve sequence - der.startSequence(); - var a = curve.p; - if (a[0] === 0x0) - a = a.slice(1); - der.writeBuffer(a, asn1.Ber.OctetString); - der.writeBuffer(curve.b, asn1.Ber.OctetString); - der.writeBuffer(curve.s, asn1.Ber.BitString); - der.endSequence(); - - der.writeBuffer(curve.G, asn1.Ber.OctetString); - der.writeBuffer(curve.n, asn1.Ber.Integer); - var h = curve.h; - if (!h) { - h = Buffer.from([1]); - } - der.writeBuffer(h, asn1.Ber.Integer); - - // ECParameters - der.endSequence(); - } -} - -function writePkcs8ECDSAPublic(key, der) { - writeECDSACurve(key, der); - der.endSequence(); - - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); -} - -function writePkcs8ECDSAPrivate(key, der) { - writeECDSACurve(key, der); - der.endSequence(); - - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - - var version = Buffer.from([1]); - der.writeBuffer(version, asn1.Ber.Integer); - - der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); - - der.startSequence(0xa1); - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); - der.endSequence(); - - der.endSequence(); - der.endSequence(); -} - -function writePkcs8EdDSAPublic(key, der) { - der.endSequence(); - - utils.writeBitString(der, key.part.A.data); -} - -function writePkcs8EdDSAPrivate(key, der) { - der.endSequence(); - - var k = utils.mpNormalize(key.part.k.data, true); - der.startSequence(asn1.Ber.OctetString); - der.writeBuffer(k, asn1.Ber.OctetString); - der.endSequence(); -} - -},{"../algs":1689,"../key":1709,"../private-key":1710,"../utils":1713,"./pem":1698,"asn1":75,"assert-plus":77,"safer-buffer":1594}],1701:[function(require,module,exports){ -// Copyright 2018 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var rfc4253 = require('./rfc4253'); -var Key = require('../key'); - -var errors = require('../errors'); - -function read(buf, options) { - var lines = buf.toString('ascii').split(/[\r\n]+/); - var found = false; - var parts; - var si = 0; - while (si < lines.length) { - parts = splitHeader(lines[si++]); - if (parts && - parts[0].toLowerCase() === 'putty-user-key-file-2') { - found = true; - break; - } - } - if (!found) { - throw (new Error('No PuTTY format first line found')); - } - var alg = parts[1]; - - parts = splitHeader(lines[si++]); - assert.equal(parts[0].toLowerCase(), 'encryption'); - - parts = splitHeader(lines[si++]); - assert.equal(parts[0].toLowerCase(), 'comment'); - var comment = parts[1]; - - parts = splitHeader(lines[si++]); - assert.equal(parts[0].toLowerCase(), 'public-lines'); - var publicLines = parseInt(parts[1], 10); - if (!isFinite(publicLines) || publicLines < 0 || - publicLines > lines.length) { - throw (new Error('Invalid public-lines count')); - } - - var publicBuf = Buffer.from( - lines.slice(si, si + publicLines).join(''), 'base64'); - var keyType = rfc4253.algToKeyType(alg); - var key = rfc4253.read(publicBuf); - if (key.type !== keyType) { - throw (new Error('Outer key algorithm mismatch')); - } - key.comment = comment; - return (key); -} - -function splitHeader(line) { - var idx = line.indexOf(':'); - if (idx === -1) - return (null); - var header = line.slice(0, idx); - ++idx; - while (line[idx] === ' ') - ++idx; - var rest = line.slice(idx); - return ([header, rest]); -} - -function write(key, options) { - assert.object(key); - if (!Key.isKey(key)) - throw (new Error('Must be a public key')); - - var alg = rfc4253.keyTypeToAlg(key); - var buf = rfc4253.write(key); - var comment = key.comment || ''; - - var b64 = buf.toString('base64'); - var lines = wrap(b64, 64); - - lines.unshift('Public-Lines: ' + lines.length); - lines.unshift('Comment: ' + comment); - lines.unshift('Encryption: none'); - lines.unshift('PuTTY-User-Key-File-2: ' + alg); - - return (Buffer.from(lines.join('\n') + '\n')); -} - -function wrap(txt, len) { - var lines = []; - var pos = 0; - while (pos < txt.length) { - lines.push(txt.slice(pos, pos + 64)); - pos += 64; - } - return (lines); -} - -},{"../errors":1693,"../key":1709,"./rfc4253":1702,"assert-plus":77,"safer-buffer":1594}],1702:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - read: read.bind(undefined, false, undefined), - readType: read.bind(undefined, false), - write: write, - /* semi-private api, used by sshpk-agent */ - readPartial: read.bind(undefined, true), - - /* shared with ssh format */ - readInternal: read, - keyTypeToAlg: keyTypeToAlg, - algToKeyType: algToKeyType -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var SSHBuffer = require('../ssh-buffer'); - -function algToKeyType(alg) { - assert.string(alg); - if (alg === 'ssh-dss') - return ('dsa'); - else if (alg === 'ssh-rsa') - return ('rsa'); - else if (alg === 'ssh-ed25519') - return ('ed25519'); - else if (alg === 'ssh-curve25519') - return ('curve25519'); - else if (alg.match(/^ecdsa-sha2-/)) - return ('ecdsa'); - else - throw (new Error('Unknown algorithm ' + alg)); -} - -function keyTypeToAlg(key) { - assert.object(key); - if (key.type === 'dsa') - return ('ssh-dss'); - else if (key.type === 'rsa') - return ('ssh-rsa'); - else if (key.type === 'ed25519') - return ('ssh-ed25519'); - else if (key.type === 'curve25519') - return ('ssh-curve25519'); - else if (key.type === 'ecdsa') - return ('ecdsa-sha2-' + key.part.curve.data.toString()); - else - throw (new Error('Unknown key type ' + key.type)); -} - -function read(partial, type, buf, options) { - if (typeof (buf) === 'string') - buf = Buffer.from(buf); - assert.buffer(buf, 'buf'); - - var key = {}; - - var parts = key.parts = []; - var sshbuf = new SSHBuffer({buffer: buf}); - - var alg = sshbuf.readString(); - assert.ok(!sshbuf.atEnd(), 'key must have at least one part'); - - key.type = algToKeyType(alg); - - var partCount = algs.info[key.type].parts.length; - if (type && type === 'private') - partCount = algs.privInfo[key.type].parts.length; - - while (!sshbuf.atEnd() && parts.length < partCount) - parts.push(sshbuf.readPart()); - while (!partial && !sshbuf.atEnd()) - parts.push(sshbuf.readPart()); - - assert.ok(parts.length >= 1, - 'key must have at least one part'); - assert.ok(partial || sshbuf.atEnd(), - 'leftover bytes at end of key'); - - var Constructor = Key; - var algInfo = algs.info[key.type]; - if (type === 'private' || algInfo.parts.length !== parts.length) { - algInfo = algs.privInfo[key.type]; - Constructor = PrivateKey; - } - assert.strictEqual(algInfo.parts.length, parts.length); - - if (key.type === 'ecdsa') { - var res = /^ecdsa-sha2-(.+)$/.exec(alg); - assert.ok(res !== null); - assert.strictEqual(res[1], parts[0].data.toString()); - } - - var normalized = true; - for (var i = 0; i < algInfo.parts.length; ++i) { - var p = parts[i]; - p.name = algInfo.parts[i]; - /* - * OpenSSH stores ed25519 "private" keys as seed + public key - * concat'd together (k followed by A). We want to keep them - * separate for other formats that don't do this. - */ - if (key.type === 'ed25519' && p.name === 'k') - p.data = p.data.slice(0, 32); - - if (p.name !== 'curve' && algInfo.normalize !== false) { - var nd; - if (key.type === 'ed25519') { - nd = utils.zeroPadToLength(p.data, 32); - } else { - nd = utils.mpNormalize(p.data); - } - if (nd.toString('binary') !== - p.data.toString('binary')) { - p.data = nd; - normalized = false; - } - } - } - - if (normalized) - key._rfc4253Cache = sshbuf.toBuffer(); - - if (partial && typeof (partial) === 'object') { - partial.remainder = sshbuf.remainder(); - partial.consumed = sshbuf._offset; - } - - return (new Constructor(key)); -} - -function write(key, options) { - assert.object(key); - - var alg = keyTypeToAlg(key); - var i; - - var algInfo = algs.info[key.type]; - if (PrivateKey.isPrivateKey(key)) - algInfo = algs.privInfo[key.type]; - var parts = algInfo.parts; - - var buf = new SSHBuffer({}); - - buf.writeString(alg); - - for (i = 0; i < parts.length; ++i) { - var data = key.part[parts[i]].data; - if (algInfo.normalize !== false) { - if (key.type === 'ed25519') - data = utils.zeroPadToLength(data, 32); - else - data = utils.mpNormalize(data); - } - if (key.type === 'ed25519' && parts[i] === 'k') - data = Buffer.concat([data, key.part.A.data]); - buf.writeBuffer(data); - } - - return (buf.toBuffer()); -} - -},{"../algs":1689,"../key":1709,"../private-key":1710,"../ssh-buffer":1712,"../utils":1713,"assert-plus":77,"safer-buffer":1594}],1703:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - read: read, - readSSHPrivate: readSSHPrivate, - write: write -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var crypto = require('crypto'); - -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var pem = require('./pem'); -var rfc4253 = require('./rfc4253'); -var SSHBuffer = require('../ssh-buffer'); -var errors = require('../errors'); - -var bcrypt; - -function read(buf, options) { - return (pem.read(buf, options)); -} - -var MAGIC = 'openssh-key-v1'; - -function readSSHPrivate(type, buf, options) { - buf = new SSHBuffer({buffer: buf}); - - var magic = buf.readCString(); - assert.strictEqual(magic, MAGIC, 'bad magic string'); - - var cipher = buf.readString(); - var kdf = buf.readString(); - var kdfOpts = buf.readBuffer(); - - var nkeys = buf.readInt(); - if (nkeys !== 1) { - throw (new Error('OpenSSH-format key file contains ' + - 'multiple keys: this is unsupported.')); - } - - var pubKey = buf.readBuffer(); - - if (type === 'public') { - assert.ok(buf.atEnd(), 'excess bytes left after key'); - return (rfc4253.read(pubKey)); - } - - var privKeyBlob = buf.readBuffer(); - assert.ok(buf.atEnd(), 'excess bytes left after key'); - - var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts }); - switch (kdf) { - case 'none': - if (cipher !== 'none') { - throw (new Error('OpenSSH-format key uses KDF "none" ' + - 'but specifies a cipher other than "none"')); - } - break; - case 'bcrypt': - var salt = kdfOptsBuf.readBuffer(); - var rounds = kdfOptsBuf.readInt(); - var cinf = utils.opensshCipherInfo(cipher); - if (bcrypt === undefined) { - bcrypt = require('bcrypt-pbkdf'); - } - - if (typeof (options.passphrase) === 'string') { - options.passphrase = Buffer.from(options.passphrase, - 'utf-8'); - } - if (!Buffer.isBuffer(options.passphrase)) { - throw (new errors.KeyEncryptedError( - options.filename, 'OpenSSH')); - } - - var pass = new Uint8Array(options.passphrase); - var salti = new Uint8Array(salt); - /* Use the pbkdf to derive both the key and the IV. */ - var out = new Uint8Array(cinf.keySize + cinf.blockSize); - var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, - out, out.length, rounds); - if (res !== 0) { - throw (new Error('bcrypt_pbkdf function returned ' + - 'failure, parameters invalid')); - } - out = Buffer.from(out); - var ckey = out.slice(0, cinf.keySize); - var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); - var cipherStream = crypto.createDecipheriv(cinf.opensslName, - ckey, iv); - cipherStream.setAutoPadding(false); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - if (e.toString().indexOf('bad decrypt') !== -1) { - throw (new Error('Incorrect passphrase ' + - 'supplied, could not decrypt key')); - } - throw (e); - }); - cipherStream.write(privKeyBlob); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - privKeyBlob = Buffer.concat(chunks); - break; - default: - throw (new Error( - 'OpenSSH-format key uses unknown KDF "' + kdf + '"')); - } - - buf = new SSHBuffer({buffer: privKeyBlob}); - - var checkInt1 = buf.readInt(); - var checkInt2 = buf.readInt(); - if (checkInt1 !== checkInt2) { - throw (new Error('Incorrect passphrase supplied, could not ' + - 'decrypt key')); - } - - var ret = {}; - var key = rfc4253.readInternal(ret, 'private', buf.remainder()); - - buf.skip(ret.consumed); - - var comment = buf.readString(); - key.comment = comment; - - return (key); -} - -function write(key, options) { - var pubKey; - if (PrivateKey.isPrivateKey(key)) - pubKey = key.toPublic(); - else - pubKey = key; - - var cipher = 'none'; - var kdf = 'none'; - var kdfopts = Buffer.alloc(0); - var cinf = { blockSize: 8 }; - var passphrase; - if (options !== undefined) { - passphrase = options.passphrase; - if (typeof (passphrase) === 'string') - passphrase = Buffer.from(passphrase, 'utf-8'); - if (passphrase !== undefined) { - assert.buffer(passphrase, 'options.passphrase'); - assert.optionalString(options.cipher, 'options.cipher'); - cipher = options.cipher; - if (cipher === undefined) - cipher = 'aes128-ctr'; - cinf = utils.opensshCipherInfo(cipher); - kdf = 'bcrypt'; - } - } - - var privBuf; - if (PrivateKey.isPrivateKey(key)) { - privBuf = new SSHBuffer({}); - var checkInt = crypto.randomBytes(4).readUInt32BE(0); - privBuf.writeInt(checkInt); - privBuf.writeInt(checkInt); - privBuf.write(key.toBuffer('rfc4253')); - privBuf.writeString(key.comment || ''); - - var n = 1; - while (privBuf._offset % cinf.blockSize !== 0) - privBuf.writeChar(n++); - privBuf = privBuf.toBuffer(); - } - - switch (kdf) { - case 'none': - break; - case 'bcrypt': - var salt = crypto.randomBytes(16); - var rounds = 16; - var kdfssh = new SSHBuffer({}); - kdfssh.writeBuffer(salt); - kdfssh.writeInt(rounds); - kdfopts = kdfssh.toBuffer(); - - if (bcrypt === undefined) { - bcrypt = require('bcrypt-pbkdf'); - } - var pass = new Uint8Array(passphrase); - var salti = new Uint8Array(salt); - /* Use the pbkdf to derive both the key and the IV. */ - var out = new Uint8Array(cinf.keySize + cinf.blockSize); - var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, - out, out.length, rounds); - if (res !== 0) { - throw (new Error('bcrypt_pbkdf function returned ' + - 'failure, parameters invalid')); - } - out = Buffer.from(out); - var ckey = out.slice(0, cinf.keySize); - var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); - - var cipherStream = crypto.createCipheriv(cinf.opensslName, - ckey, iv); - cipherStream.setAutoPadding(false); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - throw (e); - }); - cipherStream.write(privBuf); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - privBuf = Buffer.concat(chunks); - break; - default: - throw (new Error('Unsupported kdf ' + kdf)); - } - - var buf = new SSHBuffer({}); - - buf.writeCString(MAGIC); - buf.writeString(cipher); /* cipher */ - buf.writeString(kdf); /* kdf */ - buf.writeBuffer(kdfopts); /* kdfoptions */ - - buf.writeInt(1); /* nkeys */ - buf.writeBuffer(pubKey.toBuffer('rfc4253')); - - if (privBuf) - buf.writeBuffer(privBuf); - - buf = buf.toBuffer(); - - var header; - if (PrivateKey.isPrivateKey(key)) - header = 'OPENSSH PRIVATE KEY'; - else - header = 'OPENSSH PUBLIC KEY'; - - var tmp = buf.toString('base64'); - var len = tmp.length + (tmp.length / 70) + - 18 + 16 + header.length*2 + 10; - buf = Buffer.alloc(len); - var o = 0; - o += buf.write('-----BEGIN ' + header + '-----\n', o); - for (var i = 0; i < tmp.length; ) { - var limit = i + 70; - if (limit > tmp.length) - limit = tmp.length; - o += buf.write(tmp.slice(i, limit), o); - buf[o++] = 10; - i = limit; - } - o += buf.write('-----END ' + header + '-----\n', o); - - return (buf.slice(0, o)); -} - -},{"../algs":1689,"../errors":1693,"../key":1709,"../private-key":1710,"../ssh-buffer":1712,"../utils":1713,"./pem":1698,"./rfc4253":1702,"asn1":75,"assert-plus":77,"bcrypt-pbkdf":163,"crypto":236,"safer-buffer":1594}],1704:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var rfc4253 = require('./rfc4253'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); - -var sshpriv = require('./ssh-private'); - -/*JSSTYLED*/ -var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/; -/*JSSTYLED*/ -var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/; - -function read(buf, options) { - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } - - var trimmed = buf.trim().replace(/[\\\r]/g, ''); - var m = trimmed.match(SSHKEY_RE); - if (!m) - m = trimmed.match(SSHKEY_RE2); - assert.ok(m, 'key must match regex'); - - var type = rfc4253.algToKeyType(m[1]); - var kbuf = Buffer.from(m[2], 'base64'); - - /* - * This is a bit tricky. If we managed to parse the key and locate the - * key comment with the regex, then do a non-partial read and assert - * that we have consumed all bytes. If we couldn't locate the key - * comment, though, there may be whitespace shenanigans going on that - * have conjoined the comment to the rest of the key. We do a partial - * read in this case to try to make the best out of a sorry situation. - */ - var key; - var ret = {}; - if (m[4]) { - try { - key = rfc4253.read(kbuf); - - } catch (e) { - m = trimmed.match(SSHKEY_RE2); - assert.ok(m, 'key must match regex'); - kbuf = Buffer.from(m[2], 'base64'); - key = rfc4253.readInternal(ret, 'public', kbuf); - } - } else { - key = rfc4253.readInternal(ret, 'public', kbuf); - } - - assert.strictEqual(type, key.type); - - if (m[4] && m[4].length > 0) { - key.comment = m[4]; - - } else if (ret.consumed) { - /* - * Now the magic: trying to recover the key comment when it's - * gotten conjoined to the key or otherwise shenanigan'd. - * - * Work out how much base64 we used, then drop all non-base64 - * chars from the beginning up to this point in the the string. - * Then offset in this and try to make up for missing = chars. - */ - var data = m[2] + (m[3] ? m[3] : ''); - var realOffset = Math.ceil(ret.consumed / 3) * 4; - data = data.slice(0, realOffset - 2). /*JSSTYLED*/ - replace(/[^a-zA-Z0-9+\/=]/g, '') + - data.slice(realOffset - 2); - - var padding = ret.consumed % 3; - if (padding > 0 && - data.slice(realOffset - 1, realOffset) !== '=') - realOffset--; - while (data.slice(realOffset, realOffset + 1) === '=') - realOffset++; - - /* Finally, grab what we think is the comment & clean it up. */ - var trailer = data.slice(realOffset); - trailer = trailer.replace(/[\r\n]/g, ' '). - replace(/^\s+/, ''); - if (trailer.match(/^[a-zA-Z0-9]/)) - key.comment = trailer; - } - - return (key); -} - -function write(key, options) { - assert.object(key); - if (!Key.isKey(key)) - throw (new Error('Must be a public key')); - - var parts = []; - var alg = rfc4253.keyTypeToAlg(key); - parts.push(alg); - - var buf = rfc4253.write(key); - parts.push(buf.toString('base64')); - - if (key.comment) - parts.push(key.comment); - - return (Buffer.from(parts.join(' '))); -} - -},{"../key":1709,"../private-key":1710,"../utils":1713,"./rfc4253":1702,"./ssh-private":1703,"assert-plus":77,"safer-buffer":1594}],1705:[function(require,module,exports){ -// Copyright 2016 Joyent, Inc. - -var x509 = require('./x509'); - -module.exports = { - read: read, - verify: x509.verify, - sign: x509.sign, - write: write -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var pem = require('./pem'); -var Identity = require('../identity'); -var Signature = require('../signature'); -var Certificate = require('../certificate'); - -function read(buf, options) { - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } - - var lines = buf.trim().split(/[\r\n]+/g); - - var m; - var si = -1; - while (!m && si < lines.length) { - m = lines[++si].match(/*JSSTYLED*/ - /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/); - } - assert.ok(m, 'invalid PEM header'); - - var m2; - var ei = lines.length; - while (!m2 && ei > 0) { - m2 = lines[--ei].match(/*JSSTYLED*/ - /[-]+[ ]*END CERTIFICATE[ ]*[-]+/); - } - assert.ok(m2, 'invalid PEM footer'); - - lines = lines.slice(si, ei + 1); - - var headers = {}; - while (true) { - lines = lines.slice(1); - m = lines[0].match(/*JSSTYLED*/ - /^([A-Za-z0-9-]+): (.+)$/); - if (!m) - break; - headers[m[1].toLowerCase()] = m[2]; - } - - /* Chop off the first and last lines */ - lines = lines.slice(0, -1).join(''); - buf = Buffer.from(lines, 'base64'); - - return (x509.read(buf, options)); -} - -function write(cert, options) { - var dbuf = x509.write(cert, options); - - var header = 'CERTIFICATE'; - var tmp = dbuf.toString('base64'); - var len = tmp.length + (tmp.length / 64) + - 18 + 16 + header.length*2 + 10; - var buf = Buffer.alloc(len); - var o = 0; - o += buf.write('-----BEGIN ' + header + '-----\n', o); - for (var i = 0; i < tmp.length; ) { - var limit = i + 64; - if (limit > tmp.length) - limit = tmp.length; - o += buf.write(tmp.slice(i, limit), o); - buf[o++] = 10; - i = limit; - } - o += buf.write('-----END ' + header + '-----\n', o); - - return (buf.slice(0, o)); -} - -},{"../algs":1689,"../certificate":1690,"../identity":1707,"../key":1709,"../private-key":1710,"../signature":1711,"../utils":1713,"./pem":1698,"./x509":1706,"asn1":75,"assert-plus":77,"safer-buffer":1594}],1706:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = { - read: read, - verify: verify, - sign: sign, - signAsync: signAsync, - write: write -}; - -var assert = require('assert-plus'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('../algs'); -var utils = require('../utils'); -var Key = require('../key'); -var PrivateKey = require('../private-key'); -var pem = require('./pem'); -var Identity = require('../identity'); -var Signature = require('../signature'); -var Certificate = require('../certificate'); -var pkcs8 = require('./pkcs8'); - -/* - * This file is based on RFC5280 (X.509). - */ - -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); -} - -function verify(cert, key) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); - - var algParts = sig.algo.split('-'); - if (algParts[0] !== key.type) - return (false); - - var blob = sig.cache; - if (blob === undefined) { - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - blob = der.buffer; - } - - var verifier = key.createVerify(algParts[1]); - verifier.write(blob); - return (verifier.verify(sig.signature)); -} - -function Local(i) { - return (asn1.Ber.Context | asn1.Ber.Constructor | i); -} - -function Context(i) { - return (asn1.Ber.Context | i); -} - -var SIGN_ALGS = { - 'rsa-md5': '1.2.840.113549.1.1.4', - 'rsa-sha1': '1.2.840.113549.1.1.5', - 'rsa-sha256': '1.2.840.113549.1.1.11', - 'rsa-sha384': '1.2.840.113549.1.1.12', - 'rsa-sha512': '1.2.840.113549.1.1.13', - 'dsa-sha1': '1.2.840.10040.4.3', - 'dsa-sha256': '2.16.840.1.101.3.4.3.2', - 'ecdsa-sha1': '1.2.840.10045.4.1', - 'ecdsa-sha256': '1.2.840.10045.4.3.2', - 'ecdsa-sha384': '1.2.840.10045.4.3.3', - 'ecdsa-sha512': '1.2.840.10045.4.3.4', - 'ed25519-sha512': '1.3.101.112' -}; -Object.keys(SIGN_ALGS).forEach(function (k) { - SIGN_ALGS[SIGN_ALGS[k]] = k; -}); -SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5'; -SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1'; - -var EXTS = { - 'issuerKeyId': '2.5.29.35', - 'altName': '2.5.29.17', - 'basicConstraints': '2.5.29.19', - 'keyUsage': '2.5.29.15', - 'extKeyUsage': '2.5.29.37' -}; - -function read(buf, options) { - if (typeof (buf) === 'string') { - buf = Buffer.from(buf, 'binary'); - } - assert.buffer(buf, 'buf'); - - var der = new asn1.BerReader(buf); - - der.readSequence(); - if (Math.abs(der.length - der.remain) > 1) { - throw (new Error('DER sequence does not contain whole byte ' + - 'stream')); - } - - var tbsStart = der.offset; - der.readSequence(); - var sigOffset = der.offset + der.length; - var tbsEnd = sigOffset; - - if (der.peek() === Local(0)) { - der.readSequence(Local(0)); - var version = der.readInt(); - assert.ok(version <= 3, - 'only x.509 versions up to v3 supported'); - } - - var cert = {}; - cert.signatures = {}; - var sig = (cert.signatures.x509 = {}); - sig.extras = {}; - - cert.serial = readMPInt(der, 'serial'); - - der.readSequence(); - var after = der.offset + der.length; - var certAlgOid = der.readOID(); - var certAlg = SIGN_ALGS[certAlgOid]; - if (certAlg === undefined) - throw (new Error('unknown signature algorithm ' + certAlgOid)); - - der._offset = after; - cert.issuer = Identity.parseAsn1(der); - - der.readSequence(); - cert.validFrom = readDate(der); - cert.validUntil = readDate(der); - - cert.subjects = [Identity.parseAsn1(der)]; - - der.readSequence(); - after = der.offset + der.length; - cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der); - der._offset = after; - - /* issuerUniqueID */ - if (der.peek() === Local(1)) { - der.readSequence(Local(1)); - sig.extras.issuerUniqueID = - buf.slice(der.offset, der.offset + der.length); - der._offset += der.length; - } - - /* subjectUniqueID */ - if (der.peek() === Local(2)) { - der.readSequence(Local(2)); - sig.extras.subjectUniqueID = - buf.slice(der.offset, der.offset + der.length); - der._offset += der.length; - } - - /* extensions */ - if (der.peek() === Local(3)) { - der.readSequence(Local(3)); - var extEnd = der.offset + der.length; - der.readSequence(); - - while (der.offset < extEnd) - readExtension(cert, buf, der); - - assert.strictEqual(der.offset, extEnd); - } - - assert.strictEqual(der.offset, sigOffset); - - der.readSequence(); - after = der.offset + der.length; - var sigAlgOid = der.readOID(); - var sigAlg = SIGN_ALGS[sigAlgOid]; - if (sigAlg === undefined) - throw (new Error('unknown signature algorithm ' + sigAlgOid)); - der._offset = after; - - var sigData = der.readString(asn1.Ber.BitString, true); - if (sigData[0] === 0) - sigData = sigData.slice(1); - var algParts = sigAlg.split('-'); - - sig.signature = Signature.parse(sigData, algParts[0], 'asn1'); - sig.signature.hashAlgorithm = algParts[1]; - sig.algo = sigAlg; - sig.cache = buf.slice(tbsStart, tbsEnd); - - return (new Certificate(cert)); -} - -function readDate(der) { - if (der.peek() === asn1.Ber.UTCTime) { - return (utcTimeToDate(der.readString(asn1.Ber.UTCTime))); - } else if (der.peek() === asn1.Ber.GeneralizedTime) { - return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime))); - } else { - throw (new Error('Unsupported date format')); - } -} - -function writeDate(der, date) { - if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) { - der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime); - } else { - der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime); - } -} - -/* RFC5280, section 4.2.1.6 (GeneralName type) */ -var ALTNAME = { - OtherName: Local(0), - RFC822Name: Context(1), - DNSName: Context(2), - X400Address: Local(3), - DirectoryName: Local(4), - EDIPartyName: Local(5), - URI: Context(6), - IPAddress: Context(7), - OID: Context(8) -}; - -/* RFC5280, section 4.2.1.12 (KeyPurposeId) */ -var EXTPURPOSE = { - 'serverAuth': '1.3.6.1.5.5.7.3.1', - 'clientAuth': '1.3.6.1.5.5.7.3.2', - 'codeSigning': '1.3.6.1.5.5.7.3.3', - - /* See https://github.com/joyent/oid-docs/blob/master/root.md */ - 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1', - 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2' -}; -var EXTPURPOSE_REV = {}; -Object.keys(EXTPURPOSE).forEach(function (k) { - EXTPURPOSE_REV[EXTPURPOSE[k]] = k; -}); - -var KEYUSEBITS = [ - 'signature', 'identity', 'keyEncryption', - 'encryption', 'keyAgreement', 'ca', 'crl' -]; - -function readExtension(cert, buf, der) { - der.readSequence(); - var after = der.offset + der.length; - var extId = der.readOID(); - var id; - var sig = cert.signatures.x509; - if (!sig.extras.exts) - sig.extras.exts = []; - - var critical; - if (der.peek() === asn1.Ber.Boolean) - critical = der.readBoolean(); - - switch (extId) { - case (EXTS.basicConstraints): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - var bcEnd = der.offset + der.length; - var ca = false; - if (der.peek() === asn1.Ber.Boolean) - ca = der.readBoolean(); - if (cert.purposes === undefined) - cert.purposes = []; - if (ca === true) - cert.purposes.push('ca'); - var bc = { oid: extId, critical: critical }; - if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer) - bc.pathLen = der.readInt(); - sig.extras.exts.push(bc); - break; - case (EXTS.extKeyUsage): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - if (cert.purposes === undefined) - cert.purposes = []; - var ekEnd = der.offset + der.length; - while (der.offset < ekEnd) { - var oid = der.readOID(); - cert.purposes.push(EXTPURPOSE_REV[oid] || oid); - } - /* - * This is a bit of a hack: in the case where we have a cert - * that's only allowed to do serverAuth or clientAuth (and not - * the other), we want to make sure all our Subjects are of - * the right type. But we already parsed our Subjects and - * decided if they were hosts or users earlier (since it appears - * first in the cert). - * - * So we go through and mutate them into the right kind here if - * it doesn't match. This might not be hugely beneficial, as it - * seems that single-purpose certs are not often seen in the - * wild. - */ - if (cert.purposes.indexOf('serverAuth') !== -1 && - cert.purposes.indexOf('clientAuth') === -1) { - cert.subjects.forEach(function (ide) { - if (ide.type !== 'host') { - ide.type = 'host'; - ide.hostname = ide.uid || - ide.email || - ide.components[0].value; - } - }); - } else if (cert.purposes.indexOf('clientAuth') !== -1 && - cert.purposes.indexOf('serverAuth') === -1) { - cert.subjects.forEach(function (ide) { - if (ide.type !== 'user') { - ide.type = 'user'; - ide.uid = ide.hostname || - ide.email || - ide.components[0].value; - } - }); - } - sig.extras.exts.push({ oid: extId, critical: critical }); - break; - case (EXTS.keyUsage): - der.readSequence(asn1.Ber.OctetString); - var bits = der.readString(asn1.Ber.BitString, true); - var setBits = readBitField(bits, KEYUSEBITS); - setBits.forEach(function (bit) { - if (cert.purposes === undefined) - cert.purposes = []; - if (cert.purposes.indexOf(bit) === -1) - cert.purposes.push(bit); - }); - sig.extras.exts.push({ oid: extId, critical: critical, - bits: bits }); - break; - case (EXTS.altName): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - var aeEnd = der.offset + der.length; - while (der.offset < aeEnd) { - switch (der.peek()) { - case ALTNAME.OtherName: - case ALTNAME.EDIPartyName: - der.readSequence(); - der._offset += der.length; - break; - case ALTNAME.OID: - der.readOID(ALTNAME.OID); - break; - case ALTNAME.RFC822Name: - /* RFC822 specifies email addresses */ - var email = der.readString(ALTNAME.RFC822Name); - id = Identity.forEmail(email); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - case ALTNAME.DirectoryName: - der.readSequence(ALTNAME.DirectoryName); - id = Identity.parseAsn1(der); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - case ALTNAME.DNSName: - var host = der.readString( - ALTNAME.DNSName); - id = Identity.forHost(host); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - default: - der.readString(der.peek()); - break; - } - } - sig.extras.exts.push({ oid: extId, critical: critical }); - break; - default: - sig.extras.exts.push({ - oid: extId, - critical: critical, - data: der.readString(asn1.Ber.OctetString, true) - }); - break; - } - - der._offset = after; -} - -var UTCTIME_RE = - /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; -function utcTimeToDate(t) { - var m = t.match(UTCTIME_RE); - assert.ok(m, 'timestamps must be in UTC'); - var d = new Date(); - - var thisYear = d.getUTCFullYear(); - var century = Math.floor(thisYear / 100) * 100; - - var year = parseInt(m[1], 10); - if (thisYear % 100 < 50 && year >= 60) - year += (century - 1); - else - year += century; - d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10)); - d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); - if (m[6] && m[6].length > 0) - d.setUTCSeconds(parseInt(m[6], 10)); - return (d); -} - -var GTIME_RE = - /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; -function gTimeToDate(t) { - var m = t.match(GTIME_RE); - assert.ok(m); - var d = new Date(); - - d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, - parseInt(m[3], 10)); - d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); - if (m[6] && m[6].length > 0) - d.setUTCSeconds(parseInt(m[6], 10)); - return (d); -} - -function zeroPad(n, m) { - if (m === undefined) - m = 2; - var s = '' + n; - while (s.length < m) - s = '0' + s; - return (s); -} - -function dateToUTCTime(d) { - var s = ''; - s += zeroPad(d.getUTCFullYear() % 100); - s += zeroPad(d.getUTCMonth() + 1); - s += zeroPad(d.getUTCDate()); - s += zeroPad(d.getUTCHours()); - s += zeroPad(d.getUTCMinutes()); - s += zeroPad(d.getUTCSeconds()); - s += 'Z'; - return (s); -} - -function dateToGTime(d) { - var s = ''; - s += zeroPad(d.getUTCFullYear(), 4); - s += zeroPad(d.getUTCMonth() + 1); - s += zeroPad(d.getUTCDate()); - s += zeroPad(d.getUTCHours()); - s += zeroPad(d.getUTCMinutes()); - s += zeroPad(d.getUTCSeconds()); - s += 'Z'; - return (s); -} - -function sign(cert, key) { - if (cert.signatures.x509 === undefined) - cert.signatures.x509 = {}; - var sig = cert.signatures.x509; - - sig.algo = key.type + '-' + key.defaultHashAlgorithm(); - if (SIGN_ALGS[sig.algo] === undefined) - return (false); - - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - var blob = der.buffer; - sig.cache = blob; - - var signer = key.createSign(); - signer.write(blob); - cert.signatures.x509.signature = signer.sign(); - - return (true); -} - -function signAsync(cert, signer, done) { - if (cert.signatures.x509 === undefined) - cert.signatures.x509 = {}; - var sig = cert.signatures.x509; - - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - var blob = der.buffer; - sig.cache = blob; - - signer(blob, function (err, signature) { - if (err) { - done(err); - return; - } - sig.algo = signature.type + '-' + signature.hashAlgorithm; - if (SIGN_ALGS[sig.algo] === undefined) { - done(new Error('Invalid signing algorithm "' + - sig.algo + '"')); - return; - } - sig.signature = signature; - done(); - }); -} - -function write(cert, options) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); - - var der = new asn1.BerWriter(); - der.startSequence(); - if (sig.cache) { - der._ensure(sig.cache.length); - sig.cache.copy(der._buf, der._offset); - der._offset += sig.cache.length; - } else { - writeTBSCert(cert, der); - } - - der.startSequence(); - der.writeOID(SIGN_ALGS[sig.algo]); - if (sig.algo.match(/^rsa-/)) - der.writeNull(); - der.endSequence(); - - var sigData = sig.signature.toBuffer('asn1'); - var data = Buffer.alloc(sigData.length + 1); - data[0] = 0; - sigData.copy(data, 1); - der.writeBuffer(data, asn1.Ber.BitString); - der.endSequence(); - - return (der.buffer); -} - -function writeTBSCert(cert, der) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); - - der.startSequence(); - - der.startSequence(Local(0)); - der.writeInt(2); - der.endSequence(); - - der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer); - - der.startSequence(); - der.writeOID(SIGN_ALGS[sig.algo]); - if (sig.algo.match(/^rsa-/)) - der.writeNull(); - der.endSequence(); - - cert.issuer.toAsn1(der); - - der.startSequence(); - writeDate(der, cert.validFrom); - writeDate(der, cert.validUntil); - der.endSequence(); - - var subject = cert.subjects[0]; - var altNames = cert.subjects.slice(1); - subject.toAsn1(der); - - pkcs8.writePkcs8(der, cert.subjectKey); - - if (sig.extras && sig.extras.issuerUniqueID) { - der.writeBuffer(sig.extras.issuerUniqueID, Local(1)); - } - - if (sig.extras && sig.extras.subjectUniqueID) { - der.writeBuffer(sig.extras.subjectUniqueID, Local(2)); - } - - if (altNames.length > 0 || subject.type === 'host' || - (cert.purposes !== undefined && cert.purposes.length > 0) || - (sig.extras && sig.extras.exts)) { - der.startSequence(Local(3)); - der.startSequence(); - - var exts = []; - if (cert.purposes !== undefined && cert.purposes.length > 0) { - exts.push({ - oid: EXTS.basicConstraints, - critical: true - }); - exts.push({ - oid: EXTS.keyUsage, - critical: true - }); - exts.push({ - oid: EXTS.extKeyUsage, - critical: true - }); - } - exts.push({ oid: EXTS.altName }); - if (sig.extras && sig.extras.exts) - exts = sig.extras.exts; - - for (var i = 0; i < exts.length; ++i) { - der.startSequence(); - der.writeOID(exts[i].oid); - - if (exts[i].critical !== undefined) - der.writeBoolean(exts[i].critical); - - if (exts[i].oid === EXTS.altName) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - if (subject.type === 'host') { - der.writeString(subject.hostname, - Context(2)); - } - for (var j = 0; j < altNames.length; ++j) { - if (altNames[j].type === 'host') { - der.writeString( - altNames[j].hostname, - ALTNAME.DNSName); - } else if (altNames[j].type === - 'email') { - der.writeString( - altNames[j].email, - ALTNAME.RFC822Name); - } else { - /* - * Encode anything else as a - * DN style name for now. - */ - der.startSequence( - ALTNAME.DirectoryName); - altNames[j].toAsn1(der); - der.endSequence(); - } - } - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.basicConstraints) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - var ca = (cert.purposes.indexOf('ca') !== -1); - var pathLen = exts[i].pathLen; - der.writeBoolean(ca); - if (pathLen !== undefined) - der.writeInt(pathLen); - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.extKeyUsage) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - cert.purposes.forEach(function (purpose) { - if (purpose === 'ca') - return; - if (KEYUSEBITS.indexOf(purpose) !== -1) - return; - var oid = purpose; - if (EXTPURPOSE[purpose] !== undefined) - oid = EXTPURPOSE[purpose]; - der.writeOID(oid); - }); - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.keyUsage) { - der.startSequence(asn1.Ber.OctetString); - /* - * If we parsed this certificate from a byte - * stream (i.e. we didn't generate it in sshpk) - * then we'll have a ".bits" property on the - * ext with the original raw byte contents. - * - * If we have this, use it here instead of - * regenerating it. This guarantees we output - * the same data we parsed, so signatures still - * validate. - */ - if (exts[i].bits !== undefined) { - der.writeBuffer(exts[i].bits, - asn1.Ber.BitString); - } else { - var bits = writeBitField(cert.purposes, - KEYUSEBITS); - der.writeBuffer(bits, - asn1.Ber.BitString); - } - der.endSequence(); - } else { - der.writeBuffer(exts[i].data, - asn1.Ber.OctetString); - } - - der.endSequence(); - } - - der.endSequence(); - der.endSequence(); - } - - der.endSequence(); -} - -/* - * Reads an ASN.1 BER bitfield out of the Buffer produced by doing - * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw - * contents of the BitString tag, which is a count of unused bits followed by - * the bits as a right-padded byte string. - * - * `bits` is the Buffer, `bitIndex` should contain an array of string names - * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec. - * - * Returns an array of Strings, the names of the bits that were set to 1. - */ -function readBitField(bits, bitIndex) { - var bitLen = 8 * (bits.length - 1) - bits[0]; - var setBits = {}; - for (var i = 0; i < bitLen; ++i) { - var byteN = 1 + Math.floor(i / 8); - var bit = 7 - (i % 8); - var mask = 1 << bit; - var bitVal = ((bits[byteN] & mask) !== 0); - var name = bitIndex[i]; - if (bitVal && typeof (name) === 'string') { - setBits[name] = true; - } - } - return (Object.keys(setBits)); -} - -/* - * `setBits` is an array of strings, containing the names for each bit that - * sould be set to 1. `bitIndex` is same as in `readBitField()`. - * - * Returns a Buffer, ready to be written out with `BerWriter#writeString()`. - */ -function writeBitField(setBits, bitIndex) { - var bitLen = bitIndex.length; - var blen = Math.ceil(bitLen / 8); - var unused = blen * 8 - bitLen; - var bits = Buffer.alloc(1 + blen); // zero-filled - bits[0] = unused; - for (var i = 0; i < bitLen; ++i) { - var byteN = 1 + Math.floor(i / 8); - var bit = 7 - (i % 8); - var mask = 1 << bit; - var name = bitIndex[i]; - if (name === undefined) - continue; - var bitVal = (setBits.indexOf(name) !== -1); - if (bitVal) { - bits[byteN] |= mask; - } - } - return (bits); -} - -},{"../algs":1689,"../certificate":1690,"../identity":1707,"../key":1709,"../private-key":1710,"../signature":1711,"../utils":1713,"./pem":1698,"./pkcs8":1700,"asn1":75,"assert-plus":77,"safer-buffer":1594}],1707:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = Identity; - -var assert = require('assert-plus'); -var algs = require('./algs'); -var crypto = require('crypto'); -var Fingerprint = require('./fingerprint'); -var Signature = require('./signature'); -var errs = require('./errors'); -var util = require('util'); -var utils = require('./utils'); -var asn1 = require('asn1'); -var Buffer = require('safer-buffer').Buffer; - -/*JSSTYLED*/ -var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i; - -var oids = {}; -oids.cn = '2.5.4.3'; -oids.o = '2.5.4.10'; -oids.ou = '2.5.4.11'; -oids.l = '2.5.4.7'; -oids.s = '2.5.4.8'; -oids.c = '2.5.4.6'; -oids.sn = '2.5.4.4'; -oids.postalCode = '2.5.4.17'; -oids.serialNumber = '2.5.4.5'; -oids.street = '2.5.4.9'; -oids.x500UniqueIdentifier = '2.5.4.45'; -oids.role = '2.5.4.72'; -oids.telephoneNumber = '2.5.4.20'; -oids.description = '2.5.4.13'; -oids.dc = '0.9.2342.19200300.100.1.25'; -oids.uid = '0.9.2342.19200300.100.1.1'; -oids.mail = '0.9.2342.19200300.100.1.3'; -oids.title = '2.5.4.12'; -oids.gn = '2.5.4.42'; -oids.initials = '2.5.4.43'; -oids.pseudonym = '2.5.4.65'; -oids.emailAddress = '1.2.840.113549.1.9.1'; - -var unoids = {}; -Object.keys(oids).forEach(function (k) { - unoids[oids[k]] = k; -}); - -function Identity(opts) { - var self = this; - assert.object(opts, 'options'); - assert.arrayOfObject(opts.components, 'options.components'); - this.components = opts.components; - this.componentLookup = {}; - this.components.forEach(function (c) { - if (c.name && !c.oid) - c.oid = oids[c.name]; - if (c.oid && !c.name) - c.name = unoids[c.oid]; - if (self.componentLookup[c.name] === undefined) - self.componentLookup[c.name] = []; - self.componentLookup[c.name].push(c); - }); - if (this.componentLookup.cn && this.componentLookup.cn.length > 0) { - this.cn = this.componentLookup.cn[0].value; - } - assert.optionalString(opts.type, 'options.type'); - if (opts.type === undefined) { - if (this.components.length === 1 && - this.componentLookup.cn && - this.componentLookup.cn.length === 1 && - this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { - this.type = 'host'; - this.hostname = this.componentLookup.cn[0].value; - - } else if (this.componentLookup.dc && - this.components.length === this.componentLookup.dc.length) { - this.type = 'host'; - this.hostname = this.componentLookup.dc.map( - function (c) { - return (c.value); - }).join('.'); - - } else if (this.componentLookup.uid && - this.components.length === - this.componentLookup.uid.length) { - this.type = 'user'; - this.uid = this.componentLookup.uid[0].value; - - } else if (this.componentLookup.cn && - this.componentLookup.cn.length === 1 && - this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { - this.type = 'host'; - this.hostname = this.componentLookup.cn[0].value; - - } else if (this.componentLookup.uid && - this.componentLookup.uid.length === 1) { - this.type = 'user'; - this.uid = this.componentLookup.uid[0].value; - - } else if (this.componentLookup.mail && - this.componentLookup.mail.length === 1) { - this.type = 'email'; - this.email = this.componentLookup.mail[0].value; - - } else if (this.componentLookup.cn && - this.componentLookup.cn.length === 1) { - this.type = 'user'; - this.uid = this.componentLookup.cn[0].value; - - } else { - this.type = 'unknown'; - } - } else { - this.type = opts.type; - if (this.type === 'host') - this.hostname = opts.hostname; - else if (this.type === 'user') - this.uid = opts.uid; - else if (this.type === 'email') - this.email = opts.email; - else - throw (new Error('Unknown type ' + this.type)); - } -} - -Identity.prototype.toString = function () { - return (this.components.map(function (c) { - var n = c.name.toUpperCase(); - /*JSSTYLED*/ - n = n.replace(/=/g, '\\='); - var v = c.value; - /*JSSTYLED*/ - v = v.replace(/,/g, '\\,'); - return (n + '=' + v); - }).join(', ')); -}; - -Identity.prototype.get = function (name, asArray) { - assert.string(name, 'name'); - var arr = this.componentLookup[name]; - if (arr === undefined || arr.length === 0) - return (undefined); - if (!asArray && arr.length > 1) - throw (new Error('Multiple values for attribute ' + name)); - if (!asArray) - return (arr[0].value); - return (arr.map(function (c) { - return (c.value); - })); -}; - -Identity.prototype.toArray = function (idx) { - return (this.components.map(function (c) { - return ({ - name: c.name, - value: c.value - }); - })); -}; - -/* - * These are from X.680 -- PrintableString allowed chars are in section 37.4 - * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to - * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006 - * (the basic ASCII character set). - */ -/* JSSTYLED */ -var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/; -/* JSSTYLED */ -var NOT_IA5 = /[^\x00-\x7f]/; - -Identity.prototype.toAsn1 = function (der, tag) { - der.startSequence(tag); - this.components.forEach(function (c) { - der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set); - der.startSequence(); - der.writeOID(c.oid); - /* - * If we fit in a PrintableString, use that. Otherwise use an - * IA5String or UTF8String. - * - * If this identity was parsed from a DN, use the ASN.1 types - * from the original representation (otherwise this might not - * be a full match for the original in some validators). - */ - if (c.asn1type === asn1.Ber.Utf8String || - c.value.match(NOT_IA5)) { - var v = Buffer.from(c.value, 'utf8'); - der.writeBuffer(v, asn1.Ber.Utf8String); - - } else if (c.asn1type === asn1.Ber.IA5String || - c.value.match(NOT_PRINTABLE)) { - der.writeString(c.value, asn1.Ber.IA5String); - - } else { - var type = asn1.Ber.PrintableString; - if (c.asn1type !== undefined) - type = c.asn1type; - der.writeString(c.value, type); - } - der.endSequence(); - der.endSequence(); - }); - der.endSequence(); -}; - -function globMatch(a, b) { - if (a === '**' || b === '**') - return (true); - var aParts = a.split('.'); - var bParts = b.split('.'); - if (aParts.length !== bParts.length) - return (false); - for (var i = 0; i < aParts.length; ++i) { - if (aParts[i] === '*' || bParts[i] === '*') - continue; - if (aParts[i] !== bParts[i]) - return (false); - } - return (true); -} - -Identity.prototype.equals = function (other) { - if (!Identity.isIdentity(other, [1, 0])) - return (false); - if (other.components.length !== this.components.length) - return (false); - for (var i = 0; i < this.components.length; ++i) { - if (this.components[i].oid !== other.components[i].oid) - return (false); - if (!globMatch(this.components[i].value, - other.components[i].value)) { - return (false); - } - } - return (true); -}; - -Identity.forHost = function (hostname) { - assert.string(hostname, 'hostname'); - return (new Identity({ - type: 'host', - hostname: hostname, - components: [ { name: 'cn', value: hostname } ] - })); -}; - -Identity.forUser = function (uid) { - assert.string(uid, 'uid'); - return (new Identity({ - type: 'user', - uid: uid, - components: [ { name: 'uid', value: uid } ] - })); -}; - -Identity.forEmail = function (email) { - assert.string(email, 'email'); - return (new Identity({ - type: 'email', - email: email, - components: [ { name: 'mail', value: email } ] - })); -}; - -Identity.parseDN = function (dn) { - assert.string(dn, 'dn'); - var parts = ['']; - var idx = 0; - var rem = dn; - while (rem.length > 0) { - var m; - /*JSSTYLED*/ - if ((m = /^,/.exec(rem)) !== null) { - parts[++idx] = ''; - rem = rem.slice(m[0].length); - /*JSSTYLED*/ - } else if ((m = /^\\,/.exec(rem)) !== null) { - parts[idx] += ','; - rem = rem.slice(m[0].length); - /*JSSTYLED*/ - } else if ((m = /^\\./.exec(rem)) !== null) { - parts[idx] += m[0]; - rem = rem.slice(m[0].length); - /*JSSTYLED*/ - } else if ((m = /^[^\\,]+/.exec(rem)) !== null) { - parts[idx] += m[0]; - rem = rem.slice(m[0].length); - } else { - throw (new Error('Failed to parse DN')); - } - } - var cmps = parts.map(function (c) { - c = c.trim(); - var eqPos = c.indexOf('='); - while (eqPos > 0 && c.charAt(eqPos - 1) === '\\') - eqPos = c.indexOf('=', eqPos + 1); - if (eqPos === -1) { - throw (new Error('Failed to parse DN')); - } - /*JSSTYLED*/ - var name = c.slice(0, eqPos).toLowerCase().replace(/\\=/g, '='); - var value = c.slice(eqPos + 1); - return ({ name: name, value: value }); - }); - return (new Identity({ components: cmps })); -}; - -Identity.fromArray = function (components) { - assert.arrayOfObject(components, 'components'); - components.forEach(function (cmp) { - assert.object(cmp, 'component'); - assert.string(cmp.name, 'component.name'); - if (!Buffer.isBuffer(cmp.value) && - !(typeof (cmp.value) === 'string')) { - throw (new Error('Invalid component value')); - } - }); - return (new Identity({ components: components })); -}; - -Identity.parseAsn1 = function (der, top) { - var components = []; - der.readSequence(top); - var end = der.offset + der.length; - while (der.offset < end) { - der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set); - var after = der.offset + der.length; - der.readSequence(); - var oid = der.readOID(); - var type = der.peek(); - var value; - switch (type) { - case asn1.Ber.PrintableString: - case asn1.Ber.IA5String: - case asn1.Ber.OctetString: - case asn1.Ber.T61String: - value = der.readString(type); - break; - case asn1.Ber.Utf8String: - value = der.readString(type, true); - value = value.toString('utf8'); - break; - case asn1.Ber.CharacterString: - case asn1.Ber.BMPString: - value = der.readString(type, true); - value = value.toString('utf16le'); - break; - default: - throw (new Error('Unknown asn1 type ' + type)); - } - components.push({ oid: oid, asn1type: type, value: value }); - der._offset = after; - } - der._offset = end; - return (new Identity({ - components: components - })); -}; - -Identity.isIdentity = function (obj, ver) { - return (utils.isCompatible(obj, Identity, ver)); -}; - -/* - * API versions for Identity: - * [1,0] -- initial ver - */ -Identity.prototype._sshpkApiVersion = [1, 0]; - -Identity._oldVersionDetect = function (obj) { - return ([1, 0]); -}; - -},{"./algs":1689,"./errors":1693,"./fingerprint":1694,"./signature":1711,"./utils":1713,"asn1":75,"assert-plus":77,"crypto":236,"safer-buffer":1594,"util":1776}],1708:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -var Key = require('./key'); -var Fingerprint = require('./fingerprint'); -var Signature = require('./signature'); -var PrivateKey = require('./private-key'); -var Certificate = require('./certificate'); -var Identity = require('./identity'); -var errs = require('./errors'); - -module.exports = { - /* top-level classes */ - Key: Key, - parseKey: Key.parse, - Fingerprint: Fingerprint, - parseFingerprint: Fingerprint.parse, - Signature: Signature, - parseSignature: Signature.parse, - PrivateKey: PrivateKey, - parsePrivateKey: PrivateKey.parse, - generatePrivateKey: PrivateKey.generate, - Certificate: Certificate, - parseCertificate: Certificate.parse, - createSelfSignedCertificate: Certificate.createSelfSigned, - createCertificate: Certificate.create, - Identity: Identity, - identityFromDN: Identity.parseDN, - identityForHost: Identity.forHost, - identityForUser: Identity.forUser, - identityForEmail: Identity.forEmail, - identityFromArray: Identity.fromArray, - - /* errors */ - FingerprintFormatError: errs.FingerprintFormatError, - InvalidAlgorithmError: errs.InvalidAlgorithmError, - KeyParseError: errs.KeyParseError, - SignatureParseError: errs.SignatureParseError, - KeyEncryptedError: errs.KeyEncryptedError, - CertificateParseError: errs.CertificateParseError -}; - -},{"./certificate":1690,"./errors":1693,"./fingerprint":1694,"./identity":1707,"./key":1709,"./private-key":1710,"./signature":1711}],1709:[function(require,module,exports){ -(function (Buffer){ -// Copyright 2018 Joyent, Inc. - -module.exports = Key; - -var assert = require('assert-plus'); -var algs = require('./algs'); -var crypto = require('crypto'); -var Fingerprint = require('./fingerprint'); -var Signature = require('./signature'); -var DiffieHellman = require('./dhe').DiffieHellman; -var errs = require('./errors'); -var utils = require('./utils'); -var PrivateKey = require('./private-key'); -var edCompat; - -try { - edCompat = require('./ed-compat'); -} catch (e) { - /* Just continue through, and bail out if we try to use it. */ -} - -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; - -var formats = {}; -formats['auto'] = require('./formats/auto'); -formats['pem'] = require('./formats/pem'); -formats['pkcs1'] = require('./formats/pkcs1'); -formats['pkcs8'] = require('./formats/pkcs8'); -formats['rfc4253'] = require('./formats/rfc4253'); -formats['ssh'] = require('./formats/ssh'); -formats['ssh-private'] = require('./formats/ssh-private'); -formats['openssh'] = formats['ssh-private']; -formats['dnssec'] = require('./formats/dnssec'); -formats['putty'] = require('./formats/putty'); -formats['ppk'] = formats['putty']; - -function Key(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.parts, 'options.parts'); - assert.string(opts.type, 'options.type'); - assert.optionalString(opts.comment, 'options.comment'); - - var algInfo = algs.info[opts.type]; - if (typeof (algInfo) !== 'object') - throw (new InvalidAlgorithmError(opts.type)); - - var partLookup = {}; - for (var i = 0; i < opts.parts.length; ++i) { - var part = opts.parts[i]; - partLookup[part.name] = part; - } - - this.type = opts.type; - this.parts = opts.parts; - this.part = partLookup; - this.comment = undefined; - this.source = opts.source; - - /* for speeding up hashing/fingerprint operations */ - this._rfc4253Cache = opts._rfc4253Cache; - this._hashCache = {}; - - var sz; - this.curve = undefined; - if (this.type === 'ecdsa') { - var curve = this.part.curve.data.toString(); - this.curve = curve; - sz = algs.curves[curve].size; - } else if (this.type === 'ed25519' || this.type === 'curve25519') { - sz = 256; - this.curve = 'curve25519'; - } else { - var szPart = this.part[algInfo.sizePart]; - sz = szPart.data.length; - sz = sz * 8 - utils.countZeros(szPart.data); - } - this.size = sz; -} - -Key.formats = formats; - -Key.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'ssh'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); - - if (format === 'rfc4253') { - if (this._rfc4253Cache === undefined) - this._rfc4253Cache = formats['rfc4253'].write(this); - return (this._rfc4253Cache); - } - - return (formats[format].write(this, options)); -}; - -Key.prototype.toString = function (format, options) { - return (this.toBuffer(format, options).toString()); -}; - -Key.prototype.hash = function (algo, type) { - assert.string(algo, 'algorithm'); - assert.optionalString(type, 'type'); - if (type === undefined) - type = 'ssh'; - algo = algo.toLowerCase(); - if (algs.hashAlgs[algo] === undefined) - throw (new InvalidAlgorithmError(algo)); - - var cacheKey = algo + '||' + type; - if (this._hashCache[cacheKey]) - return (this._hashCache[cacheKey]); - - var buf; - if (type === 'ssh') { - buf = this.toBuffer('rfc4253'); - } else if (type === 'spki') { - buf = formats.pkcs8.pkcs8ToBuffer(this); - } else { - throw (new Error('Hash type ' + type + ' not supported')); - } - var hash = crypto.createHash(algo).update(buf).digest(); - this._hashCache[cacheKey] = hash; - return (hash); -}; - -Key.prototype.fingerprint = function (algo, type) { - if (algo === undefined) - algo = 'sha256'; - if (type === undefined) - type = 'ssh'; - assert.string(algo, 'algorithm'); - assert.string(type, 'type'); - var opts = { - type: 'key', - hash: this.hash(algo, type), - algorithm: algo, - hashType: type - }; - return (new Fingerprint(opts)); -}; - -Key.prototype.defaultHashAlgorithm = function () { - var hashAlgo = 'sha1'; - if (this.type === 'rsa') - hashAlgo = 'sha256'; - if (this.type === 'dsa' && this.size > 1024) - hashAlgo = 'sha256'; - if (this.type === 'ed25519') - hashAlgo = 'sha512'; - if (this.type === 'ecdsa') { - if (this.size <= 256) - hashAlgo = 'sha256'; - else if (this.size <= 384) - hashAlgo = 'sha384'; - else - hashAlgo = 'sha512'; - } - return (hashAlgo); -}; - -Key.prototype.createVerify = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); - - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Verifier(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); - - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldVerify = v.verify.bind(v); - var key = this.toBuffer('pkcs8'); - var curve = this.curve; - var self = this; - v.verify = function (signature, fmt) { - if (Signature.isSignature(signature, [2, 0])) { - if (signature.type !== self.type) - return (false); - if (signature.hashAlgorithm && - signature.hashAlgorithm !== hashAlgo) - return (false); - if (signature.curve && self.type === 'ecdsa' && - signature.curve !== curve) - return (false); - return (oldVerify(key, signature.toBuffer('asn1'))); - - } else if (typeof (signature) === 'string' || - Buffer.isBuffer(signature)) { - return (oldVerify(key, signature, fmt)); - - /* - * Avoid doing this on valid arguments, walking the prototype - * chain can be quite slow. - */ - } else if (Signature.isSignature(signature, [1, 0])) { - throw (new Error('signature was created by too old ' + - 'a version of sshpk and cannot be verified')); - - } else { - throw (new TypeError('signature must be a string, ' + - 'Buffer, or Signature object')); - } - }; - return (v); -}; - -Key.prototype.createDiffieHellman = function () { - if (this.type === 'rsa') - throw (new Error('RSA keys do not support Diffie-Hellman')); - - return (new DiffieHellman(this)); -}; -Key.prototype.createDH = Key.prototype.createDiffieHellman; - -Key.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - - assert.object(formats[format], 'formats[format]'); - - try { - var k = formats[format].read(data, options); - if (k instanceof PrivateKey) - k = k.toPublic(); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } -}; - -Key.isKey = function (obj, ver) { - return (utils.isCompatible(obj, Key, ver)); -}; - -/* - * API versions for Key: - * [1,0] -- initial ver, may take Signature for createVerify or may not - * [1,1] -- added pkcs1, pkcs8 formats - * [1,2] -- added auto, ssh-private, openssh formats - * [1,3] -- added defaultHashAlgorithm - * [1,4] -- added ed support, createDH - * [1,5] -- first explicitly tagged version - * [1,6] -- changed ed25519 part names - * [1,7] -- spki hash types - */ -Key.prototype._sshpkApiVersion = [1, 7]; - -Key._oldVersionDetect = function (obj) { - assert.func(obj.toBuffer); - assert.func(obj.fingerprint); - if (obj.createDH) - return ([1, 4]); - if (obj.defaultHashAlgorithm) - return ([1, 3]); - if (obj.formats['auto']) - return ([1, 2]); - if (obj.formats['pkcs1']) - return ([1, 1]); - return ([1, 0]); -}; - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"./algs":1689,"./dhe":1691,"./ed-compat":1692,"./errors":1693,"./fingerprint":1694,"./formats/auto":1695,"./formats/dnssec":1696,"./formats/pem":1698,"./formats/pkcs1":1699,"./formats/pkcs8":1700,"./formats/putty":1701,"./formats/rfc4253":1702,"./formats/ssh":1704,"./formats/ssh-private":1703,"./private-key":1710,"./signature":1711,"./utils":1713,"assert-plus":77,"crypto":236}],1710:[function(require,module,exports){ -// Copyright 2017 Joyent, Inc. - -module.exports = PrivateKey; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('./algs'); -var crypto = require('crypto'); -var Fingerprint = require('./fingerprint'); -var Signature = require('./signature'); -var errs = require('./errors'); -var util = require('util'); -var utils = require('./utils'); -var dhe = require('./dhe'); -var generateECDSA = dhe.generateECDSA; -var generateED25519 = dhe.generateED25519; -var edCompat = require('./ed-compat'); -var nacl = require('tweetnacl'); - -var Key = require('./key'); - -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; -var KeyEncryptedError = errs.KeyEncryptedError; - -var formats = {}; -formats['auto'] = require('./formats/auto'); -formats['pem'] = require('./formats/pem'); -formats['pkcs1'] = require('./formats/pkcs1'); -formats['pkcs8'] = require('./formats/pkcs8'); -formats['rfc4253'] = require('./formats/rfc4253'); -formats['ssh-private'] = require('./formats/ssh-private'); -formats['openssh'] = formats['ssh-private']; -formats['ssh'] = formats['ssh-private']; -formats['dnssec'] = require('./formats/dnssec'); - -function PrivateKey(opts) { - assert.object(opts, 'options'); - Key.call(this, opts); - - this._pubCache = undefined; -} -util.inherits(PrivateKey, Key); - -PrivateKey.formats = formats; - -PrivateKey.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'pkcs1'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); - - return (formats[format].write(this, options)); -}; - -PrivateKey.prototype.hash = function (algo, type) { - return (this.toPublic().hash(algo, type)); -}; - -PrivateKey.prototype.fingerprint = function (algo, type) { - return (this.toPublic().fingerprint(algo, type)); -}; - -PrivateKey.prototype.toPublic = function () { - if (this._pubCache) - return (this._pubCache); - - var algInfo = algs.info[this.type]; - var pubParts = []; - for (var i = 0; i < algInfo.parts.length; ++i) { - var p = algInfo.parts[i]; - pubParts.push(this.part[p]); - } - - this._pubCache = new Key({ - type: this.type, - source: this, - parts: pubParts - }); - if (this.comment) - this._pubCache.comment = this.comment; - return (this._pubCache); -}; - -PrivateKey.prototype.derive = function (newType) { - assert.string(newType, 'type'); - var priv, pub, pair; - - if (this.type === 'ed25519' && newType === 'curve25519') { - priv = this.part.k.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - - pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); - pub = Buffer.from(pair.publicKey); - - return (new PrivateKey({ - type: 'curve25519', - parts: [ - { name: 'A', data: utils.mpNormalize(pub) }, - { name: 'k', data: utils.mpNormalize(priv) } - ] - })); - } else if (this.type === 'curve25519' && newType === 'ed25519') { - priv = this.part.k.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - - pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); - pub = Buffer.from(pair.publicKey); - - return (new PrivateKey({ - type: 'ed25519', - parts: [ - { name: 'A', data: utils.mpNormalize(pub) }, - { name: 'k', data: utils.mpNormalize(priv) } - ] - })); - } - throw (new Error('Key derivation not supported from ' + this.type + - ' to ' + newType)); -}; - -PrivateKey.prototype.createVerify = function (hashAlgo) { - return (this.toPublic().createVerify(hashAlgo)); -}; - -PrivateKey.prototype.createSign = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); - - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Signer(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); - - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldSign = v.sign.bind(v); - var key = this.toBuffer('pkcs1'); - var type = this.type; - var curve = this.curve; - v.sign = function () { - var sig = oldSign(key); - if (typeof (sig) === 'string') - sig = Buffer.from(sig, 'binary'); - sig = Signature.parse(sig, type, 'asn1'); - sig.hashAlgorithm = hashAlgo; - sig.curve = curve; - return (sig); - }; - return (v); -}; - -PrivateKey.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - - assert.object(formats[format], 'formats[format]'); - - try { - var k = formats[format].read(data, options); - assert.ok(k instanceof PrivateKey, 'key is not a private key'); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } -}; - -PrivateKey.isPrivateKey = function (obj, ver) { - return (utils.isCompatible(obj, PrivateKey, ver)); -}; - -PrivateKey.generate = function (type, options) { - if (options === undefined) - options = {}; - assert.object(options, 'options'); - - switch (type) { - case 'ecdsa': - if (options.curve === undefined) - options.curve = 'nistp256'; - assert.string(options.curve, 'options.curve'); - return (generateECDSA(options.curve)); - case 'ed25519': - return (generateED25519()); - default: - throw (new Error('Key generation not supported with key ' + - 'type "' + type + '"')); - } -}; - -/* - * API versions for PrivateKey: - * [1,0] -- initial ver - * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats - * [1,2] -- added defaultHashAlgorithm - * [1,3] -- added derive, ed, createDH - * [1,4] -- first tagged version - * [1,5] -- changed ed25519 part names and format - * [1,6] -- type arguments for hash() and fingerprint() - */ -PrivateKey.prototype._sshpkApiVersion = [1, 6]; - -PrivateKey._oldVersionDetect = function (obj) { - assert.func(obj.toPublic); - assert.func(obj.createSign); - if (obj.derive) - return ([1, 3]); - if (obj.defaultHashAlgorithm) - return ([1, 2]); - if (obj.formats['auto']) - return ([1, 1]); - return ([1, 0]); -}; - -},{"./algs":1689,"./dhe":1691,"./ed-compat":1692,"./errors":1693,"./fingerprint":1694,"./formats/auto":1695,"./formats/dnssec":1696,"./formats/pem":1698,"./formats/pkcs1":1699,"./formats/pkcs8":1700,"./formats/rfc4253":1702,"./formats/ssh-private":1703,"./key":1709,"./signature":1711,"./utils":1713,"assert-plus":77,"crypto":236,"safer-buffer":1594,"tweetnacl":1762,"util":1776}],1711:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = Signature; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var algs = require('./algs'); -var crypto = require('crypto'); -var errs = require('./errors'); -var utils = require('./utils'); -var asn1 = require('asn1'); -var SSHBuffer = require('./ssh-buffer'); - -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var SignatureParseError = errs.SignatureParseError; - -function Signature(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.parts, 'options.parts'); - assert.string(opts.type, 'options.type'); - - var partLookup = {}; - for (var i = 0; i < opts.parts.length; ++i) { - var part = opts.parts[i]; - partLookup[part.name] = part; - } - - this.type = opts.type; - this.hashAlgorithm = opts.hashAlgo; - this.curve = opts.curve; - this.parts = opts.parts; - this.part = partLookup; -} - -Signature.prototype.toBuffer = function (format) { - if (format === undefined) - format = 'asn1'; - assert.string(format, 'format'); - - var buf; - var stype = 'ssh-' + this.type; - - switch (this.type) { - case 'rsa': - switch (this.hashAlgorithm) { - case 'sha256': - stype = 'rsa-sha2-256'; - break; - case 'sha512': - stype = 'rsa-sha2-512'; - break; - case 'sha1': - case undefined: - break; - default: - throw (new Error('SSH signature ' + - 'format does not support hash ' + - 'algorithm ' + this.hashAlgorithm)); - } - if (format === 'ssh') { - buf = new SSHBuffer({}); - buf.writeString(stype); - buf.writePart(this.part.sig); - return (buf.toBuffer()); - } else { - return (this.part.sig.data); - } - break; - - case 'ed25519': - if (format === 'ssh') { - buf = new SSHBuffer({}); - buf.writeString(stype); - buf.writePart(this.part.sig); - return (buf.toBuffer()); - } else { - return (this.part.sig.data); - } - break; - - case 'dsa': - case 'ecdsa': - var r, s; - if (format === 'asn1') { - var der = new asn1.BerWriter(); - der.startSequence(); - r = utils.mpNormalize(this.part.r.data); - s = utils.mpNormalize(this.part.s.data); - der.writeBuffer(r, asn1.Ber.Integer); - der.writeBuffer(s, asn1.Ber.Integer); - der.endSequence(); - return (der.buffer); - } else if (format === 'ssh' && this.type === 'dsa') { - buf = new SSHBuffer({}); - buf.writeString('ssh-dss'); - r = this.part.r.data; - if (r.length > 20 && r[0] === 0x00) - r = r.slice(1); - s = this.part.s.data; - if (s.length > 20 && s[0] === 0x00) - s = s.slice(1); - if ((this.hashAlgorithm && - this.hashAlgorithm !== 'sha1') || - r.length + s.length !== 40) { - throw (new Error('OpenSSH only supports ' + - 'DSA signatures with SHA1 hash')); - } - buf.writeBuffer(Buffer.concat([r, s])); - return (buf.toBuffer()); - } else if (format === 'ssh' && this.type === 'ecdsa') { - var inner = new SSHBuffer({}); - r = this.part.r.data; - inner.writeBuffer(r); - inner.writePart(this.part.s); - - buf = new SSHBuffer({}); - /* XXX: find a more proper way to do this? */ - var curve; - if (r[0] === 0x00) - r = r.slice(1); - var sz = r.length * 8; - if (sz === 256) - curve = 'nistp256'; - else if (sz === 384) - curve = 'nistp384'; - else if (sz === 528) - curve = 'nistp521'; - buf.writeString('ecdsa-sha2-' + curve); - buf.writeBuffer(inner.toBuffer()); - return (buf.toBuffer()); - } - throw (new Error('Invalid signature format')); - default: - throw (new Error('Invalid signature data')); - } -}; - -Signature.prototype.toString = function (format) { - assert.optionalString(format, 'format'); - return (this.toBuffer(format).toString('base64')); -}; - -Signature.parse = function (data, type, format) { - if (typeof (data) === 'string') - data = Buffer.from(data, 'base64'); - assert.buffer(data, 'data'); - assert.string(format, 'format'); - assert.string(type, 'type'); - - var opts = {}; - opts.type = type.toLowerCase(); - opts.parts = []; - - try { - assert.ok(data.length > 0, 'signature must not be empty'); - switch (opts.type) { - case 'rsa': - return (parseOneNum(data, type, format, opts)); - case 'ed25519': - return (parseOneNum(data, type, format, opts)); - - case 'dsa': - case 'ecdsa': - if (format === 'asn1') - return (parseDSAasn1(data, type, format, opts)); - else if (opts.type === 'dsa') - return (parseDSA(data, type, format, opts)); - else - return (parseECDSA(data, type, format, opts)); - - default: - throw (new InvalidAlgorithmError(type)); - } - - } catch (e) { - if (e instanceof InvalidAlgorithmError) - throw (e); - throw (new SignatureParseError(type, format, e)); - } -}; - -function parseOneNum(data, type, format, opts) { - if (format === 'ssh') { - try { - var buf = new SSHBuffer({buffer: data}); - var head = buf.readString(); - } catch (e) { - /* fall through */ - } - if (buf !== undefined) { - var msg = 'SSH signature does not match expected ' + - 'type (expected ' + type + ', got ' + head + ')'; - switch (head) { - case 'ssh-rsa': - assert.strictEqual(type, 'rsa', msg); - opts.hashAlgo = 'sha1'; - break; - case 'rsa-sha2-256': - assert.strictEqual(type, 'rsa', msg); - opts.hashAlgo = 'sha256'; - break; - case 'rsa-sha2-512': - assert.strictEqual(type, 'rsa', msg); - opts.hashAlgo = 'sha512'; - break; - case 'ssh-ed25519': - assert.strictEqual(type, 'ed25519', msg); - opts.hashAlgo = 'sha512'; - break; - default: - throw (new Error('Unknown SSH signature ' + - 'type: ' + head)); - } - var sig = buf.readPart(); - assert.ok(buf.atEnd(), 'extra trailing bytes'); - sig.name = 'sig'; - opts.parts.push(sig); - return (new Signature(opts)); - } - } - opts.parts.push({name: 'sig', data: data}); - return (new Signature(opts)); -} - -function parseDSAasn1(data, type, format, opts) { - var der = new asn1.BerReader(data); - der.readSequence(); - var r = der.readString(asn1.Ber.Integer, true); - var s = der.readString(asn1.Ber.Integer, true); - - opts.parts.push({name: 'r', data: utils.mpNormalize(r)}); - opts.parts.push({name: 's', data: utils.mpNormalize(s)}); - - return (new Signature(opts)); -} - -function parseDSA(data, type, format, opts) { - if (data.length != 40) { - var buf = new SSHBuffer({buffer: data}); - var d = buf.readBuffer(); - if (d.toString('ascii') === 'ssh-dss') - d = buf.readBuffer(); - assert.ok(buf.atEnd(), 'extra trailing bytes'); - assert.strictEqual(d.length, 40, 'invalid inner length'); - data = d; - } - opts.parts.push({name: 'r', data: data.slice(0, 20)}); - opts.parts.push({name: 's', data: data.slice(20, 40)}); - return (new Signature(opts)); -} - -function parseECDSA(data, type, format, opts) { - var buf = new SSHBuffer({buffer: data}); - - var r, s; - var inner = buf.readBuffer(); - var stype = inner.toString('ascii'); - if (stype.slice(0, 6) === 'ecdsa-') { - var parts = stype.split('-'); - assert.strictEqual(parts[0], 'ecdsa'); - assert.strictEqual(parts[1], 'sha2'); - opts.curve = parts[2]; - switch (opts.curve) { - case 'nistp256': - opts.hashAlgo = 'sha256'; - break; - case 'nistp384': - opts.hashAlgo = 'sha384'; - break; - case 'nistp521': - opts.hashAlgo = 'sha512'; - break; - default: - throw (new Error('Unsupported ECDSA curve: ' + - opts.curve)); - } - inner = buf.readBuffer(); - assert.ok(buf.atEnd(), 'extra trailing bytes on outer'); - buf = new SSHBuffer({buffer: inner}); - r = buf.readPart(); - } else { - r = {data: inner}; - } - - s = buf.readPart(); - assert.ok(buf.atEnd(), 'extra trailing bytes'); - - r.name = 'r'; - s.name = 's'; - - opts.parts.push(r); - opts.parts.push(s); - return (new Signature(opts)); -} - -Signature.isSignature = function (obj, ver) { - return (utils.isCompatible(obj, Signature, ver)); -}; - -/* - * API versions for Signature: - * [1,0] -- initial ver - * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent - * hashAlgorithm property - * [2,1] -- first tagged version - */ -Signature.prototype._sshpkApiVersion = [2, 1]; - -Signature._oldVersionDetect = function (obj) { - assert.func(obj.toBuffer); - if (obj.hasOwnProperty('hashAlgorithm')) - return ([2, 0]); - return ([1, 0]); -}; - -},{"./algs":1689,"./errors":1693,"./ssh-buffer":1712,"./utils":1713,"asn1":75,"assert-plus":77,"crypto":236,"safer-buffer":1594}],1712:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = SSHBuffer; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; - -function SSHBuffer(opts) { - assert.object(opts, 'options'); - if (opts.buffer !== undefined) - assert.buffer(opts.buffer, 'options.buffer'); - - this._size = opts.buffer ? opts.buffer.length : 1024; - this._buffer = opts.buffer || Buffer.alloc(this._size); - this._offset = 0; -} - -SSHBuffer.prototype.toBuffer = function () { - return (this._buffer.slice(0, this._offset)); -}; - -SSHBuffer.prototype.atEnd = function () { - return (this._offset >= this._buffer.length); -}; - -SSHBuffer.prototype.remainder = function () { - return (this._buffer.slice(this._offset)); -}; - -SSHBuffer.prototype.skip = function (n) { - this._offset += n; -}; - -SSHBuffer.prototype.expand = function () { - this._size *= 2; - var buf = Buffer.alloc(this._size); - this._buffer.copy(buf, 0); - this._buffer = buf; -}; - -SSHBuffer.prototype.readPart = function () { - return ({data: this.readBuffer()}); -}; - -SSHBuffer.prototype.readBuffer = function () { - var len = this._buffer.readUInt32BE(this._offset); - this._offset += 4; - assert.ok(this._offset + len <= this._buffer.length, - 'length out of bounds at +0x' + this._offset.toString(16) + - ' (data truncated?)'); - var buf = this._buffer.slice(this._offset, this._offset + len); - this._offset += len; - return (buf); -}; - -SSHBuffer.prototype.readString = function () { - return (this.readBuffer().toString()); -}; - -SSHBuffer.prototype.readCString = function () { - var offset = this._offset; - while (offset < this._buffer.length && - this._buffer[offset] !== 0x00) - offset++; - assert.ok(offset < this._buffer.length, 'c string does not terminate'); - var str = this._buffer.slice(this._offset, offset).toString(); - this._offset = offset + 1; - return (str); -}; - -SSHBuffer.prototype.readInt = function () { - var v = this._buffer.readUInt32BE(this._offset); - this._offset += 4; - return (v); -}; - -SSHBuffer.prototype.readInt64 = function () { - assert.ok(this._offset + 8 < this._buffer.length, - 'buffer not long enough to read Int64'); - var v = this._buffer.slice(this._offset, this._offset + 8); - this._offset += 8; - return (v); -}; - -SSHBuffer.prototype.readChar = function () { - var v = this._buffer[this._offset++]; - return (v); -}; - -SSHBuffer.prototype.writeBuffer = function (buf) { - while (this._offset + 4 + buf.length > this._size) - this.expand(); - this._buffer.writeUInt32BE(buf.length, this._offset); - this._offset += 4; - buf.copy(this._buffer, this._offset); - this._offset += buf.length; -}; - -SSHBuffer.prototype.writeString = function (str) { - this.writeBuffer(Buffer.from(str, 'utf8')); -}; - -SSHBuffer.prototype.writeCString = function (str) { - while (this._offset + 1 + str.length > this._size) - this.expand(); - this._buffer.write(str, this._offset); - this._offset += str.length; - this._buffer[this._offset++] = 0; -}; - -SSHBuffer.prototype.writeInt = function (v) { - while (this._offset + 4 > this._size) - this.expand(); - this._buffer.writeUInt32BE(v, this._offset); - this._offset += 4; -}; - -SSHBuffer.prototype.writeInt64 = function (v) { - assert.buffer(v, 'value'); - if (v.length > 8) { - var lead = v.slice(0, v.length - 8); - for (var i = 0; i < lead.length; ++i) { - assert.strictEqual(lead[i], 0, - 'must fit in 64 bits of precision'); - } - v = v.slice(v.length - 8, v.length); - } - while (this._offset + 8 > this._size) - this.expand(); - v.copy(this._buffer, this._offset); - this._offset += 8; -}; - -SSHBuffer.prototype.writeChar = function (v) { - while (this._offset + 1 > this._size) - this.expand(); - this._buffer[this._offset++] = v; -}; - -SSHBuffer.prototype.writePart = function (p) { - this.writeBuffer(p.data); -}; - -SSHBuffer.prototype.write = function (buf) { - while (this._offset + buf.length > this._size) - this.expand(); - buf.copy(this._buffer, this._offset); - this._offset += buf.length; -}; - -},{"assert-plus":77,"safer-buffer":1594}],1713:[function(require,module,exports){ -// Copyright 2015 Joyent, Inc. - -module.exports = { - bufferSplit: bufferSplit, - addRSAMissing: addRSAMissing, - calculateDSAPublic: calculateDSAPublic, - calculateED25519Public: calculateED25519Public, - calculateX25519Public: calculateX25519Public, - mpNormalize: mpNormalize, - mpDenormalize: mpDenormalize, - ecNormalize: ecNormalize, - countZeros: countZeros, - assertCompatible: assertCompatible, - isCompatible: isCompatible, - opensslKeyDeriv: opensslKeyDeriv, - opensshCipherInfo: opensshCipherInfo, - publicFromPrivateECDSA: publicFromPrivateECDSA, - zeroPadToLength: zeroPadToLength, - writeBitString: writeBitString, - readBitString: readBitString, - pbkdf2: pbkdf2 -}; - -var assert = require('assert-plus'); -var Buffer = require('safer-buffer').Buffer; -var PrivateKey = require('./private-key'); -var Key = require('./key'); -var crypto = require('crypto'); -var algs = require('./algs'); -var asn1 = require('asn1'); - -var ec = require('ecc-jsbn/lib/ec'); -var jsbn = require('jsbn').BigInteger; -var nacl = require('tweetnacl'); - -var MAX_CLASS_DEPTH = 3; - -function isCompatible(obj, klass, needVer) { - if (obj === null || typeof (obj) !== 'object') - return (false); - if (needVer === undefined) - needVer = klass.prototype._sshpkApiVersion; - if (obj instanceof klass && - klass.prototype._sshpkApiVersion[0] == needVer[0]) - return (true); - var proto = Object.getPrototypeOf(obj); - var depth = 0; - while (proto.constructor.name !== klass.name) { - proto = Object.getPrototypeOf(proto); - if (!proto || ++depth > MAX_CLASS_DEPTH) - return (false); - } - if (proto.constructor.name !== klass.name) - return (false); - var ver = proto._sshpkApiVersion; - if (ver === undefined) - ver = klass._oldVersionDetect(obj); - if (ver[0] != needVer[0] || ver[1] < needVer[1]) - return (false); - return (true); -} - -function assertCompatible(obj, klass, needVer, name) { - if (name === undefined) - name = 'object'; - assert.ok(obj, name + ' must not be null'); - assert.object(obj, name + ' must be an object'); - if (needVer === undefined) - needVer = klass.prototype._sshpkApiVersion; - if (obj instanceof klass && - klass.prototype._sshpkApiVersion[0] == needVer[0]) - return; - var proto = Object.getPrototypeOf(obj); - var depth = 0; - while (proto.constructor.name !== klass.name) { - proto = Object.getPrototypeOf(proto); - assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, - name + ' must be a ' + klass.name + ' instance'); - } - assert.strictEqual(proto.constructor.name, klass.name, - name + ' must be a ' + klass.name + ' instance'); - var ver = proto._sshpkApiVersion; - if (ver === undefined) - ver = klass._oldVersionDetect(obj); - assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], - name + ' must be compatible with ' + klass.name + ' klass ' + - 'version ' + needVer[0] + '.' + needVer[1]); -} - -var CIPHER_LEN = { - 'des-ede3-cbc': { key: 24, iv: 8 }, - 'aes-128-cbc': { key: 16, iv: 16 }, - 'aes-256-cbc': { key: 32, iv: 16 } -}; -var PKCS5_SALT_LEN = 8; - -function opensslKeyDeriv(cipher, salt, passphrase, count) { - assert.buffer(salt, 'salt'); - assert.buffer(passphrase, 'passphrase'); - assert.number(count, 'iteration count'); - - var clen = CIPHER_LEN[cipher]; - assert.object(clen, 'supported cipher'); - - salt = salt.slice(0, PKCS5_SALT_LEN); - - var D, D_prev, bufs; - var material = Buffer.alloc(0); - while (material.length < clen.key + clen.iv) { - bufs = []; - if (D_prev) - bufs.push(D_prev); - bufs.push(passphrase); - bufs.push(salt); - D = Buffer.concat(bufs); - for (var j = 0; j < count; ++j) - D = crypto.createHash('md5').update(D).digest(); - material = Buffer.concat([material, D]); - D_prev = D; - } - - return ({ - key: material.slice(0, clen.key), - iv: material.slice(clen.key, clen.key + clen.iv) - }); -} - -/* See: RFC2898 */ -function pbkdf2(hashAlg, salt, iterations, size, passphrase) { - var hkey = Buffer.alloc(salt.length + 4); - salt.copy(hkey); - - var gen = 0, ts = []; - var i = 1; - while (gen < size) { - var t = T(i++); - gen += t.length; - ts.push(t); - } - return (Buffer.concat(ts).slice(0, size)); - - function T(I) { - hkey.writeUInt32BE(I, hkey.length - 4); - - var hmac = crypto.createHmac(hashAlg, passphrase); - hmac.update(hkey); - - var Ti = hmac.digest(); - var Uc = Ti; - var c = 1; - while (c++ < iterations) { - hmac = crypto.createHmac(hashAlg, passphrase); - hmac.update(Uc); - Uc = hmac.digest(); - for (var x = 0; x < Ti.length; ++x) - Ti[x] ^= Uc[x]; - } - return (Ti); - } -} - -/* Count leading zero bits on a buffer */ -function countZeros(buf) { - var o = 0, obit = 8; - while (o < buf.length) { - var mask = (1 << obit); - if ((buf[o] & mask) === mask) - break; - obit--; - if (obit < 0) { - o++; - obit = 8; - } - } - return (o*8 + (8 - obit) - 1); -} - -function bufferSplit(buf, chr) { - assert.buffer(buf); - assert.string(chr); - - var parts = []; - var lastPart = 0; - var matches = 0; - for (var i = 0; i < buf.length; ++i) { - if (buf[i] === chr.charCodeAt(matches)) - ++matches; - else if (buf[i] === chr.charCodeAt(0)) - matches = 1; - else - matches = 0; - - if (matches >= chr.length) { - var newPart = i + 1; - parts.push(buf.slice(lastPart, newPart - matches)); - lastPart = newPart; - matches = 0; - } - } - if (lastPart <= buf.length) - parts.push(buf.slice(lastPart, buf.length)); - - return (parts); -} - -function ecNormalize(buf, addZero) { - assert.buffer(buf); - if (buf[0] === 0x00 && buf[1] === 0x04) { - if (addZero) - return (buf); - return (buf.slice(1)); - } else if (buf[0] === 0x04) { - if (!addZero) - return (buf); - } else { - while (buf[0] === 0x00) - buf = buf.slice(1); - if (buf[0] === 0x02 || buf[0] === 0x03) - throw (new Error('Compressed elliptic curve points ' + - 'are not supported')); - if (buf[0] !== 0x04) - throw (new Error('Not a valid elliptic curve point')); - if (!addZero) - return (buf); - } - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x0; - buf.copy(b, 1); - return (b); -} - -function readBitString(der, tag) { - if (tag === undefined) - tag = asn1.Ber.BitString; - var buf = der.readString(tag, true); - assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' + - 'not supported (0x' + buf[0].toString(16) + ')'); - return (buf.slice(1)); -} - -function writeBitString(der, buf, tag) { - if (tag === undefined) - tag = asn1.Ber.BitString; - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - der.writeBuffer(b, tag); -} - -function mpNormalize(buf) { - assert.buffer(buf); - while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00) - buf = buf.slice(1); - if ((buf[0] & 0x80) === 0x80) { - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - buf = b; - } - return (buf); -} - -function mpDenormalize(buf) { - assert.buffer(buf); - while (buf.length > 1 && buf[0] === 0x00) - buf = buf.slice(1); - return (buf); -} - -function zeroPadToLength(buf, len) { - assert.buffer(buf); - assert.number(len); - while (buf.length > len) { - assert.equal(buf[0], 0x00); - buf = buf.slice(1); - } - while (buf.length < len) { - var b = Buffer.alloc(buf.length + 1); - b[0] = 0x00; - buf.copy(b, 1); - buf = b; - } - return (buf); -} - -function bigintToMpBuf(bigint) { - var buf = Buffer.from(bigint.toByteArray()); - buf = mpNormalize(buf); - return (buf); -} - -function calculateDSAPublic(g, p, x) { - assert.buffer(g); - assert.buffer(p); - assert.buffer(x); - g = new jsbn(g); - p = new jsbn(p); - x = new jsbn(x); - var y = g.modPow(x, p); - var ybuf = bigintToMpBuf(y); - return (ybuf); -} - -function calculateED25519Public(k) { - assert.buffer(k); - - var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k)); - return (Buffer.from(kp.publicKey)); -} - -function calculateX25519Public(k) { - assert.buffer(k); - - var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k)); - return (Buffer.from(kp.publicKey)); -} - -function addRSAMissing(key) { - assert.object(key); - assertCompatible(key, PrivateKey, [1, 1]); - - var d = new jsbn(key.part.d.data); - var buf; - - if (!key.part.dmodp) { - var p = new jsbn(key.part.p.data); - var dmodp = d.mod(p.subtract(1)); - - buf = bigintToMpBuf(dmodp); - key.part.dmodp = {name: 'dmodp', data: buf}; - key.parts.push(key.part.dmodp); - } - if (!key.part.dmodq) { - var q = new jsbn(key.part.q.data); - var dmodq = d.mod(q.subtract(1)); - - buf = bigintToMpBuf(dmodq); - key.part.dmodq = {name: 'dmodq', data: buf}; - key.parts.push(key.part.dmodq); - } -} - -function publicFromPrivateECDSA(curveName, priv) { - assert.string(curveName, 'curveName'); - assert.buffer(priv); - var params = algs.curves[curveName]; - var p = new jsbn(params.p); - var a = new jsbn(params.a); - var b = new jsbn(params.b); - var curve = new ec.ECCurveFp(p, a, b); - var G = curve.decodePointHex(params.G.toString('hex')); - - var d = new jsbn(mpNormalize(priv)); - var pub = G.multiply(d); - pub = Buffer.from(curve.encodePointHex(pub), 'hex'); - - var parts = []; - parts.push({name: 'curve', data: Buffer.from(curveName)}); - parts.push({name: 'Q', data: pub}); - - var key = new Key({type: 'ecdsa', curve: curve, parts: parts}); - return (key); -} - -function opensshCipherInfo(cipher) { - var inf = {}; - switch (cipher) { - case '3des-cbc': - inf.keySize = 24; - inf.blockSize = 8; - inf.opensslName = 'des-ede3-cbc'; - break; - case 'blowfish-cbc': - inf.keySize = 16; - inf.blockSize = 8; - inf.opensslName = 'bf-cbc'; - break; - case 'aes128-cbc': - case 'aes128-ctr': - case 'aes128-gcm@openssh.com': - inf.keySize = 16; - inf.blockSize = 16; - inf.opensslName = 'aes-128-' + cipher.slice(7, 10); - break; - case 'aes192-cbc': - case 'aes192-ctr': - case 'aes192-gcm@openssh.com': - inf.keySize = 24; - inf.blockSize = 16; - inf.opensslName = 'aes-192-' + cipher.slice(7, 10); - break; - case 'aes256-cbc': - case 'aes256-ctr': - case 'aes256-gcm@openssh.com': - inf.keySize = 32; - inf.blockSize = 16; - inf.opensslName = 'aes-256-' + cipher.slice(7, 10); - break; - default: - throw (new Error( - 'Unsupported openssl cipher "' + cipher + '"')); - } - return (inf); -} - -},{"./algs":1689,"./key":1709,"./private-key":1710,"asn1":75,"assert-plus":77,"crypto":236,"ecc-jsbn/lib/ec":280,"jsbn":825,"safer-buffer":1594,"tweetnacl":1762}],1714:[function(require,module,exports){ -//! stable.js 0.1.8, https://github.com/Two-Screen/stable -//! © 2018 Angry Bytes and contributors. MIT licensed. - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.stable = factory()); -}(this, (function () { 'use strict'; - - // A stable array sort, because `Array#sort()` is not guaranteed stable. - // This is an implementation of merge sort, without recursion. - - var stable = function (arr, comp) { - return exec(arr.slice(), comp) - }; - - stable.inplace = function (arr, comp) { - var result = exec(arr, comp); - - // This simply copies back if the result isn't in the original array, - // which happens on an odd number of passes. - if (result !== arr) { - pass(result, null, arr.length, arr); - } - - return arr - }; - - // Execute the sort using the input array and a second buffer as work space. - // Returns one of those two, containing the final result. - function exec(arr, comp) { - if (typeof(comp) !== 'function') { - comp = function (a, b) { - return String(a).localeCompare(b) - }; - } - - // Short-circuit when there's nothing to sort. - var len = arr.length; - if (len <= 1) { - return arr - } - - // Rather than dividing input, simply iterate chunks of 1, 2, 4, 8, etc. - // Chunks are the size of the left or right hand in merge sort. - // Stop when the left-hand covers all of the array. - var buffer = new Array(len); - for (var chk = 1; chk < len; chk *= 2) { - pass(arr, comp, chk, buffer); - - var tmp = arr; - arr = buffer; - buffer = tmp; - } - - return arr - } - - // Run a single pass with the given chunk size. - var pass = function (arr, comp, chk, result) { - var len = arr.length; - var i = 0; - // Step size / double chunk size. - var dbl = chk * 2; - // Bounds of the left and right chunks. - var l, r, e; - // Iterators over the left and right chunk. - var li, ri; - - // Iterate over pairs of chunks. - for (l = 0; l < len; l += dbl) { - r = l + chk; - e = r + chk; - if (r > len) r = len; - if (e > len) e = len; - - // Iterate both chunks in parallel. - li = l; - ri = r; - while (true) { - // Compare the chunks. - if (li < r && ri < e) { - // This works for a regular `sort()` compatible comparator, - // but also for a simple comparator like: `a > b` - if (comp(arr[li], arr[ri]) <= 0) { - result[i++] = arr[li++]; - } - else { - result[i++] = arr[ri++]; - } - } - // Nothing to compare, just flush what's left. - else if (li < r) { - result[i++] = arr[li++]; - } - else if (ri < e) { - result[i++] = arr[ri++]; - } - // Both iterators are at the chunk ends. - else { - break - } - } - } - }; - - return stable; - -}))); - -},{}],1715:[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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/readable.js'); -Stream.Writable = require('readable-stream/writable.js'); -Stream.Duplex = require('readable-stream/duplex.js'); -Stream.Transform = require('readable-stream/transform.js'); -Stream.PassThrough = require('readable-stream/passthrough.js'); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":370,"inherits":453,"readable-stream/duplex.js":1557,"readable-stream/passthrough.js":1568,"readable-stream/readable.js":1569,"readable-stream/transform.js":1570,"readable-stream/writable.js":1571}],1716:[function(require,module,exports){ +},{"./lib/_stream_writable.js":1466}],1474:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":1371}],1475:[function(require,module,exports){ (function (global){ var ClientRequest = require('./lib/request') var response = require('./lib/response') @@ -225790,7 +161567,7 @@ http.METHODS = [ 'UNSUBSCRIBE' ] }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./lib/request":1718,"./lib/response":1719,"builtin-status-codes":218,"url":1769,"xtend":1860}],1717:[function(require,module,exports){ +},{"./lib/request":1477,"./lib/response":1478,"builtin-status-codes":182,"url":1507,"xtend":1496}],1476:[function(require,module,exports){ (function (global){ exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) @@ -225853,7 +161630,7 @@ function isFunction (value) { xhr = null // Help gc }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1718:[function(require,module,exports){ +},{}],1477:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') @@ -226172,7 +161949,7 @@ var unsafeHeaders = [ ] }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./capability":1717,"./response":1719,"_process":1438,"buffer":217,"inherits":453,"readable-stream":1734}],1719:[function(require,module,exports){ +},{"./capability":1476,"./response":1478,"_process":1258,"buffer":181,"inherits":317,"readable-stream":1493}],1478:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') @@ -226210,7 +161987,7 @@ var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, f self.url = response.url self.statusCode = response.status self.statusMessage = response.statusText - + response.headers.forEach(function (header, key){ self.headers[key.toLowerCase()] = header self.rawHeaders.push(key, header) @@ -226383,37 +162160,43 @@ IncomingMessage.prototype._onXHRProgress = function () { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./capability":1717,"_process":1438,"buffer":217,"inherits":453,"readable-stream":1734}],1720:[function(require,module,exports){ -arguments[4][88][0].apply(exports,arguments) -},{"dup":88}],1721:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"_process":1438,"dup":89}],1722:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"./_stream_readable":1724,"./_stream_writable":1726,"_process":1438,"dup":90,"inherits":453}],1723:[function(require,module,exports){ -arguments[4][91][0].apply(exports,arguments) -},{"./_stream_transform":1725,"dup":91,"inherits":453}],1724:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"../errors":1720,"../experimentalWarning":1721,"./_stream_duplex":1722,"./internal/streams/async_iterator":1727,"./internal/streams/buffer_list":1728,"./internal/streams/destroy":1729,"./internal/streams/state":1732,"./internal/streams/stream":1733,"_process":1438,"buffer":217,"dup":92,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],1725:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"../errors":1720,"./_stream_duplex":1722,"dup":93,"inherits":453}],1726:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"../errors":1720,"./_stream_duplex":1722,"./internal/streams/destroy":1729,"./internal/streams/state":1732,"./internal/streams/stream":1733,"_process":1438,"buffer":217,"dup":94,"inherits":453,"util-deprecate":1773}],1727:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"./end-of-stream":1730,"_process":1438,"dup":95}],1728:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"buffer":217,"dup":96,"util":182}],1729:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"_process":1438,"dup":97}],1730:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"../../../errors":1720,"dup":98}],1731:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"../../../errors":1720,"./end-of-stream":1730,"dup":99}],1732:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"../../../errors":1720,"dup":100}],1733:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"dup":101,"events":370}],1734:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":1722,"./lib/_stream_passthrough.js":1723,"./lib/_stream_readable.js":1724,"./lib/_stream_transform.js":1725,"./lib/_stream_writable.js":1726,"./lib/internal/streams/end-of-stream.js":1730,"./lib/internal/streams/pipeline.js":1731,"dup":102}],1735:[function(require,module,exports){ +},{"./capability":1476,"_process":1258,"buffer":181,"inherits":317,"readable-stream":1493}],1479:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],1480:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"_process":1258,"dup":37}],1481:[function(require,module,exports){ +arguments[4][38][0].apply(exports,arguments) +},{"./_stream_readable":1483,"./_stream_writable":1485,"_process":1258,"dup":38,"inherits":317}],1482:[function(require,module,exports){ +arguments[4][39][0].apply(exports,arguments) +},{"./_stream_transform":1484,"dup":39,"inherits":317}],1483:[function(require,module,exports){ +arguments[4][40][0].apply(exports,arguments) +},{"../errors":1479,"../experimentalWarning":1480,"./_stream_duplex":1481,"./internal/streams/async_iterator":1486,"./internal/streams/buffer_list":1487,"./internal/streams/destroy":1488,"./internal/streams/state":1491,"./internal/streams/stream":1492,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":1495,"util":146}],1484:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"../errors":1479,"./_stream_duplex":1481,"dup":41,"inherits":317}],1485:[function(require,module,exports){ +arguments[4][42][0].apply(exports,arguments) +},{"../errors":1479,"./_stream_duplex":1481,"./internal/streams/destroy":1488,"./internal/streams/state":1491,"./internal/streams/stream":1492,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],1486:[function(require,module,exports){ +arguments[4][43][0].apply(exports,arguments) +},{"./end-of-stream":1489,"_process":1258,"dup":43}],1487:[function(require,module,exports){ +arguments[4][44][0].apply(exports,arguments) +},{"buffer":181,"dup":44,"util":146}],1488:[function(require,module,exports){ +arguments[4][45][0].apply(exports,arguments) +},{"_process":1258,"dup":45}],1489:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"../../../errors":1479,"dup":46}],1490:[function(require,module,exports){ +arguments[4][47][0].apply(exports,arguments) +},{"../../../errors":1479,"./end-of-stream":1489,"dup":47}],1491:[function(require,module,exports){ +arguments[4][48][0].apply(exports,arguments) +},{"../../../errors":1479,"dup":48}],1492:[function(require,module,exports){ +arguments[4][49][0].apply(exports,arguments) +},{"dup":49,"events":272}],1493:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"./lib/_stream_duplex.js":1481,"./lib/_stream_passthrough.js":1482,"./lib/_stream_readable.js":1483,"./lib/_stream_transform.js":1484,"./lib/_stream_writable.js":1485,"./lib/internal/streams/end-of-stream.js":1489,"./lib/internal/streams/pipeline.js":1490,"dup":50}],1494:[function(require,module,exports){ +arguments[4][51][0].apply(exports,arguments) +},{"buffer":181,"dup":51}],1495:[function(require,module,exports){ +arguments[4][52][0].apply(exports,arguments) +},{"dup":52,"safe-buffer":1494}],1496:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],1497:[function(require,module,exports){ (function (process){ var pull = require('pull-stream/pull') var looper = require('looper') @@ -226639,100 +162422,7 @@ exports.transform = function (stream) { }).call(this,require('_process')) -},{"_process":1438,"looper":1294,"pull-stream/pull":1496}],1736:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase(); - }); -}; - -},{}],1737:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var ES = require('es-abstract/es5'); -var replace = bind.call(Function.call, String.prototype.replace); - -/* eslint-disable no-control-regex */ -var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/; -var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/; -/* eslint-enable no-control-regex */ - -module.exports = function trim() { - var S = ES.ToString(ES.CheckObjectCoercible(this)); - return replace(replace(S, leftWhitespace, ''), rightWhitespace, ''); -}; - -},{"es-abstract/es5":319,"function-bind":386}],1738:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -var boundTrim = bind.call(Function.call, getPolyfill()); - -define(boundTrim, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = boundTrim; - -},{"./implementation":1737,"./polyfill":1739,"./shim":1740,"define-properties":263,"function-bind":386}],1739:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -var zeroWidthSpace = '\u200b'; - -module.exports = function getPolyfill() { - if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) { - return String.prototype.trim; - } - return implementation; -}; - -},{"./implementation":1737}],1740:[function(require,module,exports){ -'use strict'; - -var define = require('define-properties'); -var getPolyfill = require('./polyfill'); - -module.exports = function shimStringTrim() { - var polyfill = getPolyfill(); - define(String.prototype, { trim: polyfill }, { - trim: function testTrim() { - return String.prototype.trim !== polyfill; - } - }); - return polyfill; -}; - -},{"./polyfill":1739,"define-properties":263}],1741:[function(require,module,exports){ -arguments[4][1567][0].apply(exports,arguments) -},{"dup":1567,"safe-buffer":1593}],1742:[function(require,module,exports){ -var isHexPrefixed = require('is-hex-prefixed'); - -/** - * Removes '0x' from a given `String` is present - * @param {String} str the string value - * @return {String|Optional} a string by pass if necessary - */ -module.exports = function stripHexPrefix(str) { - if (typeof str !== 'string') { - return str; - } - - return isHexPrefixed(str) ? str.slice(2) : str; -} - -},{"is-hex-prefixed":773}],1743:[function(require,module,exports){ +},{"_process":1258,"looper":1123,"pull-stream/pull":1312}],1498:[function(require,module,exports){ (function (process){ 'use strict'; @@ -227987,822 +163677,7 @@ exports.StructError = StructError; }).call(this,require('_process')) -},{"_process":1438}],1744:[function(require,module,exports){ -var unavailable = function unavailable() { - throw "This swarm.js function isn't available on the browser."; -}; - -var fs = { - readFile: unavailable -}; -var files = { - download: unavailable, - safeDownloadArchived: unavailable, - directoryTree: unavailable -}; -var os = { - platform: unavailable, - arch: unavailable -}; -var path = { - join: unavailable, - slice: unavailable -}; -var child_process = { - spawn: unavailable -}; -var mimetype = { - lookup: unavailable -}; -var defaultArchives = {}; -var downloadUrl = null; - -var request = require("xhr-request-promise"); - -var bytes = require("eth-lib/lib/bytes"); - -var hash = require("./swarm-hash.js"); - -var pick = require("./pick.js"); - -var swarm = require("./swarm"); - -module.exports = swarm({ - fs: fs, - files: files, - os: os, - path: path, - child_process: child_process, - defaultArchives: defaultArchives, - mimetype: mimetype, - request: request, - downloadUrl: downloadUrl, - bytes: bytes, - hash: hash, - pick: pick -}); -},{"./pick.js":1745,"./swarm":1747,"./swarm-hash.js":1746,"eth-lib/lib/bytes":333,"xhr-request-promise":1845}],1745:[function(require,module,exports){ -var picker = function picker(type) { - return function () { - return new Promise(function (resolve, reject) { - var fileLoader = function fileLoader(e) { - var directory = {}; - var totalFiles = e.target.files.length; - var loadedFiles = 0; - [].map.call(e.target.files, function (file) { - var reader = new FileReader(); - - reader.onload = function (e) { - var data = new Uint8Array(e.target.result); - - if (type === "directory") { - var path = file.webkitRelativePath; - directory[path.slice(path.indexOf("/") + 1)] = { - type: "text/plain", - data: data - }; - if (++loadedFiles === totalFiles) resolve(directory); - } else if (type === "file") { - var _path = file.webkitRelativePath; - resolve({ - "type": mimetype.lookup(_path), - "data": data - }); - } else { - resolve(data); - } - }; - - reader.readAsArrayBuffer(file); - }); - }; - - var fileInput; - - if (type === "directory") { - fileInput = document.createElement("input"); - fileInput.addEventListener("change", fileLoader); - fileInput.type = "file"; - fileInput.webkitdirectory = true; - fileInput.mozdirectory = true; - fileInput.msdirectory = true; - fileInput.odirectory = true; - fileInput.directory = true; - } else { - fileInput = document.createElement("input"); - fileInput.addEventListener("change", fileLoader); - fileInput.type = "file"; - } - - ; - var mouseEvent = document.createEvent("MouseEvents"); - mouseEvent.initEvent("click", true, false); - fileInput.dispatchEvent(mouseEvent); - }); - }; -}; - -module.exports = { - data: picker("data"), - file: picker("file"), - directory: picker("directory") -}; -},{}],1746:[function(require,module,exports){ -// Thanks https://github.com/axic/swarmhash -var keccak = require("eth-lib/lib/hash").keccak256; - -var Bytes = require("eth-lib/lib/bytes"); - -var swarmHashBlock = function swarmHashBlock(length, data) { - var lengthEncoded = Bytes.reverse(Bytes.pad(6, Bytes.fromNumber(length))); - var bytes = Bytes.flatten([lengthEncoded, "0x0000", data]); - return keccak(bytes).slice(2); -}; // (Bytes | Uint8Array | String) -> String - - -var swarmHash = function swarmHash(data) { - if (typeof data === "string" && data.slice(0, 2) !== "0x") { - data = Bytes.fromString(data); - } else if (typeof data !== "string" && data.length !== undefined) { - data = Bytes.fromUint8Array(data); - } - - var length = Bytes.length(data); - - if (length <= 4096) { - return swarmHashBlock(length, data); - } - - var maxSize = 4096; - - while (maxSize * (4096 / 32) < length) { - maxSize *= 4096 / 32; - } - - var innerNodes = []; - - for (var i = 0; i < length; i += maxSize) { - var size = maxSize < length - i ? maxSize : length - i; - innerNodes.push(swarmHash(Bytes.slice(data, i, i + size))); - } - - return swarmHashBlock(length, Bytes.flatten(innerNodes)); -}; - -module.exports = swarmHash; -},{"eth-lib/lib/bytes":333,"eth-lib/lib/hash":334}],1747:[function(require,module,exports){ -// TODO: this is a temporary fix to hide those libraries from the browser. A -// slightly better long-term solution would be to split this file into two, -// separating the functions that are used on Node.js from the functions that -// are used only on the browser. -module.exports = function (_ref) { - var fs = _ref.fs, - files = _ref.files, - os = _ref.os, - path = _ref.path, - child_process = _ref.child_process, - mimetype = _ref.mimetype, - defaultArchives = _ref.defaultArchives, - request = _ref.request, - downloadUrl = _ref.downloadUrl, - bytes = _ref.bytes, - hash = _ref.hash, - pick = _ref.pick; - - // ∀ a . String -> JSON -> Map String a -o Map String a - // Inserts a key/val pair in an object impurely. - var impureInsert = function impureInsert(key) { - return function (val) { - return function (map) { - return map[key] = val, map; - }; - }; - }; // String -> JSON -> Map String JSON - // Merges an array of keys and an array of vals into an object. - - - var toMap = function toMap(keys) { - return function (vals) { - var map = {}; - - for (var i = 0, l = keys.length; i < l; ++i) { - map[keys[i]] = vals[i]; - } - - return map; - }; - }; // ∀ a . Map String a -> Map String a -> Map String a - // Merges two maps into one. - - - var merge = function merge(a) { - return function (b) { - var map = {}; - - for (var key in a) { - map[key] = a[key]; - } - - for (var _key in b) { - map[_key] = b[_key]; - } - - return map; - }; - }; // ∀ a . [a] -> [a] -> Bool - - - var equals = function equals(a) { - return function (b) { - if (a.length !== b.length) { - return false; - } else { - for (var i = 0, l = a.length; i < l; ++i) { - if (a[i] !== b[i]) return false; - } - } - - return true; - }; - }; // String -> String -> String - - - var rawUrl = function rawUrl(swarmUrl) { - return function (hash) { - return "".concat(swarmUrl, "/bzzr:/").concat(hash); - }; - }; // String -> String -> Promise Uint8Array - // Gets the raw contents of a Swarm hash address. - - - var downloadData = function downloadData(swarmUrl) { - return function (hash) { - return request(rawUrl(swarmUrl)(hash), { - responseType: "arraybuffer" - }).then(function (arrayBuffer) { - var uint8Array = new Uint8Array(arrayBuffer); - var error404 = [52, 48, 52, 32, 112, 97, 103, 101, 32, 110, 111, 116, 32, 102, 111, 117, 110, 100, 10]; - if (equals(uint8Array)(error404)) throw "Error 404."; - return uint8Array; - }); - }; - }; // type Entry = {"type": String, "hash": String} - // type File = {"type": String, "data": Uint8Array} - // String -> String -> Promise (Map String Entry) - // Solves the manifest of a Swarm address recursively. - // Returns a map from full paths to entries. - - - var downloadEntries = function downloadEntries(swarmUrl) { - return function (hash) { - var search = function search(hash) { - return function (path) { - return function (routes) { - // Formats an entry to the Swarm.js type. - var format = function format(entry) { - return { - type: entry.contentType, - hash: entry.hash - }; - }; // To download a single entry: - // if type is bzz-manifest, go deeper - // if not, add it to the routing table - - - var downloadEntry = function downloadEntry(entry) { - if (entry.path === undefined) { - return Promise.resolve(); - } else { - return entry.contentType === "application/bzz-manifest+json" ? search(entry.hash)(path + entry.path)(routes) : Promise.resolve(impureInsert(path + entry.path)(format(entry))(routes)); - } - }; // Downloads the initial manifest and then each entry. - - - return downloadData(swarmUrl)(hash).then(function (text) { - return JSON.parse(toString(text)).entries; - }).then(function (entries) { - return Promise.all(entries.map(downloadEntry)); - }).then(function () { - return routes; - }); - }; - }; - }; - - return search(hash)("")({}); - }; - }; // String -> String -> Promise (Map String String) - // Same as `downloadEntries`, but returns only hashes (no types). - - - var downloadRoutes = function downloadRoutes(swarmUrl) { - return function (hash) { - return downloadEntries(swarmUrl)(hash).then(function (entries) { - return toMap(Object.keys(entries))(Object.keys(entries).map(function (route) { - return entries[route].hash; - })); - }); - }; - }; // String -> String -> Promise (Map String File) - // Gets the entire directory tree in a Swarm address. - // Returns a promise mapping paths to file contents. - - - var downloadDirectory = function downloadDirectory(swarmUrl) { - return function (hash) { - return downloadEntries(swarmUrl)(hash).then(function (entries) { - var paths = Object.keys(entries); - var hashs = paths.map(function (path) { - return entries[path].hash; - }); - var types = paths.map(function (path) { - return entries[path].type; - }); - var datas = hashs.map(downloadData(swarmUrl)); - - var files = function files(datas) { - return datas.map(function (data, i) { - return { - type: types[i], - data: data - }; - }); - }; - - return Promise.all(datas).then(function (datas) { - return toMap(paths)(files(datas)); - }); - }); - }; - }; // String -> String -> String -> Promise String - // Gets the raw contents of a Swarm hash address. - // Returns a promise with the downloaded file path. - - - var downloadDataToDisk = function downloadDataToDisk(swarmUrl) { - return function (hash) { - return function (filePath) { - return files.download(rawUrl(swarmUrl)(hash))(filePath); - }; - }; - }; // String -> String -> String -> Promise (Map String String) - // Gets the entire directory tree in a Swarm address. - // Returns a promise mapping paths to file contents. - - - var downloadDirectoryToDisk = function downloadDirectoryToDisk(swarmUrl) { - return function (hash) { - return function (dirPath) { - return downloadRoutes(swarmUrl)(hash).then(function (routingTable) { - var downloads = []; - - for (var route in routingTable) { - if (route.length > 0) { - var filePath = path.join(dirPath, route); - downloads.push(downloadDataToDisk(swarmUrl)(routingTable[route])(filePath)); - } - - ; - } - - ; - return Promise.all(downloads).then(function () { - return dirPath; - }); - }); - }; - }; - }; // String -> Uint8Array -> Promise String - // Uploads raw data to Swarm. - // Returns a promise with the uploaded hash. - - - var uploadData = function uploadData(swarmUrl) { - return function (data) { - return request("".concat(swarmUrl, "/bzzr:/"), { - body: typeof data === "string" ? fromString(data) : data, - method: "POST" - }); - }; - }; // String -> String -> String -> File -> Promise String - // Uploads a file to the Swarm manifest at a given hash, under a specific - // route. Returns a promise containing the uploaded hash. - // FIXME: for some reasons Swarm-Gateways is sometimes returning - // error 404 (bad request), so we retry up to 3 times. Why? - - - var uploadToManifest = function uploadToManifest(swarmUrl) { - return function (hash) { - return function (route) { - return function (file) { - var attempt = function attempt(n) { - var slashRoute = route[0] === "/" ? route : "/" + route; - var url = "".concat(swarmUrl, "/bzz:/").concat(hash).concat(slashRoute); - var opt = { - method: "PUT", - headers: { - "Content-Type": file.type - }, - body: file.data - }; - return request(url, opt).then(function (response) { - if (response.indexOf("error") !== -1) { - throw response; - } - - return response; - }).catch(function (e) { - return n > 0 && attempt(n - 1); - }); - }; - - return attempt(3); - }; - }; - }; - }; // String -> {type: String, data: Uint8Array} -> Promise String - - - var uploadFile = function uploadFile(swarmUrl) { - return function (file) { - return uploadDirectory(swarmUrl)({ - "": file - }); - }; - }; // String -> String -> Promise String - - - var uploadFileFromDisk = function uploadFileFromDisk(swarmUrl) { - return function (filePath) { - return fs.readFile(filePath).then(function (data) { - return uploadFile(swarmUrl)({ - type: mimetype.lookup(filePath), - data: data - }); - }); - }; - }; // String -> Map String File -> Promise String - // Uploads a directory to Swarm. The directory is - // represented as a map of routes and files. - // A default path is encoded by having a "" route. - - - var uploadDirectory = function uploadDirectory(swarmUrl) { - return function (directory) { - return uploadData(swarmUrl)("{}").then(function (hash) { - var uploadRoute = function uploadRoute(route) { - return function (hash) { - return uploadToManifest(swarmUrl)(hash)(route)(directory[route]); - }; - }; - - var uploadToHash = function uploadToHash(hash, route) { - return hash.then(uploadRoute(route)); - }; - - return Object.keys(directory).reduce(uploadToHash, Promise.resolve(hash)); - }); - }; - }; // String -> Promise String - - - var uploadDataFromDisk = function uploadDataFromDisk(swarmUrl) { - return function (filePath) { - return fs.readFile(filePath).then(uploadData(swarmUrl)); - }; - }; // String -> Nullable String -> String -> Promise String - - - var uploadDirectoryFromDisk = function uploadDirectoryFromDisk(swarmUrl) { - return function (defaultPath) { - return function (dirPath) { - return files.directoryTree(dirPath).then(function (fullPaths) { - return Promise.all(fullPaths.map(function (path) { - return fs.readFile(path); - })).then(function (datas) { - var paths = fullPaths.map(function (path) { - return path.slice(dirPath.length); - }); - var types = fullPaths.map(function (path) { - return mimetype.lookup(path) || "text/plain"; - }); - return toMap(paths)(datas.map(function (data, i) { - return { - type: types[i], - data: data - }; - })); - }); - }).then(function (directory) { - return merge(defaultPath ? { - "": directory[defaultPath] - } : {})(directory); - }).then(uploadDirectory(swarmUrl)); - }; - }; - }; // String -> UploadInfo -> Promise String - // Simplified multi-type upload which calls the correct - // one based on the type of the argument given. - - - var _upload = function upload(swarmUrl) { - return function (arg) { - // Upload raw data from browser - if (arg.pick === "data") { - return pick.data().then(uploadData(swarmUrl)); // Upload a file from browser - } else if (arg.pick === "file") { - return pick.file().then(uploadFile(swarmUrl)); // Upload a directory from browser - } else if (arg.pick === "directory") { - return pick.directory().then(uploadDirectory(swarmUrl)); // Upload directory/file from disk - } else if (arg.path) { - switch (arg.kind) { - case "data": - return uploadDataFromDisk(swarmUrl)(arg.path); - - case "file": - return uploadFileFromDisk(swarmUrl)(arg.path); - - case "directory": - return uploadDirectoryFromDisk(swarmUrl)(arg.defaultFile)(arg.path); - } - - ; // Upload UTF-8 string or raw data (buffer) - } else if (arg.length || typeof arg === "string") { - return uploadData(swarmUrl)(arg); // Upload directory with JSON - } else if (arg instanceof Object) { - return uploadDirectory(swarmUrl)(arg); - } - - return Promise.reject(new Error("Bad arguments")); - }; - }; // String -> String -> Nullable String -> Promise (String | Uint8Array | Map String Uint8Array) - // Simplified multi-type download which calls the correct function based on - // the type of the argument given, and on whether the Swwarm address has a - // directory or a file. - - - var _download = function download(swarmUrl) { - return function (hash) { - return function (path) { - return isDirectory(swarmUrl)(hash).then(function (isDir) { - if (isDir) { - return path ? downloadDirectoryToDisk(swarmUrl)(hash)(path) : downloadDirectory(swarmUrl)(hash); - } else { - return path ? downloadDataToDisk(swarmUrl)(hash)(path) : downloadData(swarmUrl)(hash); - } - }); - }; - }; - }; // String -> Promise String - // Downloads the Swarm binaries into a path. Returns a promise that only - // resolves when the exact Swarm file is there, and verified to be correct. - // If it was already there to begin with, skips the download. - - - var downloadBinary = function downloadBinary(path, archives) { - var system = os.platform().replace("win32", "windows") + "-" + (os.arch() === "x64" ? "amd64" : "386"); - var archive = (archives || defaultArchives)[system]; - var archiveUrl = downloadUrl + archive.archive + ".tar.gz"; - var archiveMD5 = archive.archiveMD5; - var binaryMD5 = archive.binaryMD5; - return files.safeDownloadArchived(archiveUrl)(archiveMD5)(binaryMD5)(path); - }; // type SwarmSetup = { - // account : String, - // password : String, - // dataDir : String, - // binPath : String, - // ensApi : String, - // onDownloadProgress : Number ~> (), - // archives : [{ - // archive: String, - // binaryMD5: String, - // archiveMD5: String - // }] - // } - // SwarmSetup ~> Promise Process - // Starts the Swarm process. - - - var startProcess = function startProcess(swarmSetup) { - return new Promise(function (resolve, reject) { - var spawn = child_process.spawn; - - var hasString = function hasString(str) { - return function (buffer) { - return ('' + buffer).indexOf(str) !== -1; - }; - }; - - var account = swarmSetup.account, - password = swarmSetup.password, - dataDir = swarmSetup.dataDir, - ensApi = swarmSetup.ensApi, - privateKey = swarmSetup.privateKey; - var STARTUP_TIMEOUT_SECS = 3; - var WAITING_PASSWORD = 0; - var STARTING = 1; - var LISTENING = 2; - var PASSWORD_PROMPT_HOOK = "Passphrase"; - var LISTENING_HOOK = "Swarm http proxy started"; - var state = WAITING_PASSWORD; - var swarmProcess = spawn(swarmSetup.binPath, ['--bzzaccount', account || privateKey, '--datadir', dataDir, '--ens-api', ensApi]); - - var handleProcessOutput = function handleProcessOutput(data) { - if (state === WAITING_PASSWORD && hasString(PASSWORD_PROMPT_HOOK)(data)) { - setTimeout(function () { - state = STARTING; - swarmProcess.stdin.write(password + '\n'); - }, 500); - } else if (hasString(LISTENING_HOOK)(data)) { - state = LISTENING; - clearTimeout(timeout); - resolve(swarmProcess); - } - }; - - swarmProcess.stdout.on('data', handleProcessOutput); - swarmProcess.stderr.on('data', handleProcessOutput); //swarmProcess.on('close', () => setTimeout(restart, 2000)); - - var restart = function restart() { - return startProcess(swarmSetup).then(resolve).catch(reject); - }; - - var error = function error() { - return reject(new Error("Couldn't start swarm process.")); - }; - - var timeout = setTimeout(error, 20000); - }); - }; // Process ~> Promise () - // Stops the Swarm process. - - - var stopProcess = function stopProcess(process) { - return new Promise(function (resolve, reject) { - process.stderr.removeAllListeners('data'); - process.stdout.removeAllListeners('data'); - process.stdin.removeAllListeners('error'); - process.removeAllListeners('error'); - process.removeAllListeners('exit'); - process.kill('SIGINT'); - var killTimeout = setTimeout(function () { - return process.kill('SIGKILL'); - }, 8000); - process.once('close', function () { - clearTimeout(killTimeout); - resolve(); - }); - }); - }; // SwarmSetup -> (SwarmAPI -> Promise ()) -> Promise () - // Receives a Swarm configuration object and a callback function. It then - // checks if a local Swarm node is running. If no local Swarm is found, it - // downloads the Swarm binaries to the dataDir (if not there), checksums, - // starts the Swarm process and calls the callback function with an API - // object using the local node. That callback must return a promise which - // will resolve when it is done using the API, so that this function can - // close the Swarm process properly. Returns a promise that resolves when the - // user is done with the API and the Swarm process is closed. - // TODO: check if Swarm process is already running (improve `isAvailable`) - - - var local = function local(swarmSetup) { - return function (useAPI) { - return _isAvailable("http://localhost:8500").then(function (isAvailable) { - return isAvailable ? useAPI(at("http://localhost:8500")).then(function () {}) : downloadBinary(swarmSetup.binPath, swarmSetup.archives).onData(function (data) { - return (swarmSetup.onProgress || function () {})(data.length); - }).then(function () { - return startProcess(swarmSetup); - }).then(function (process) { - return useAPI(at("http://localhost:8500")).then(function () { - return process; - }); - }).then(stopProcess); - }); - }; - }; // String ~> Promise Bool - // Returns true if Swarm is available on `url`. - // Perfoms a test upload to determine that. - // TODO: improve this? - - - var _isAvailable = function isAvailable(swarmUrl) { - var testFile = "test"; - var testHash = "c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"; - return uploadData(swarmUrl)(testFile).then(function (hash) { - return hash === testHash; - }).catch(function () { - return false; - }); - }; // String -> String ~> Promise Bool - // Returns a Promise which is true if that Swarm address is a directory. - // Determines that by checking that it (i) is a JSON, (ii) has a .entries. - // TODO: improve this? - - - var isDirectory = function isDirectory(swarmUrl) { - return function (hash) { - return downloadData(swarmUrl)(hash).then(function (data) { - try { - return !!JSON.parse(toString(data)).entries; - } catch (e) { - return false; - } - }); - }; - }; // Uncurries a function; used to allow the f(x,y,z) style on exports. - - - var uncurry = function uncurry(f) { - return function (a, b, c, d, e) { - var p; // Hardcoded because efficiency (`arguments` is very slow). - - if (typeof a !== "undefined") p = f(a); - if (typeof b !== "undefined") p = f(b); - if (typeof c !== "undefined") p = f(c); - if (typeof d !== "undefined") p = f(d); - if (typeof e !== "undefined") p = f(e); - return p; - }; - }; // () -> Promise Bool - // Not sure how to mock Swarm to test it properly. Ideas? - - - var test = function test() { - return Promise.resolve(true); - }; // Uint8Array -> String - - - var toString = function toString(uint8Array) { - return bytes.toString(bytes.fromUint8Array(uint8Array)); - }; // String -> Uint8Array - - - var fromString = function fromString(string) { - return bytes.toUint8Array(bytes.fromString(string)); - }; // String -> SwarmAPI - // Fixes the `swarmUrl`, returning an API where you don't have to pass it. - - - var at = function at(swarmUrl) { - return { - download: function download(hash, path) { - return _download(swarmUrl)(hash)(path); - }, - downloadData: uncurry(downloadData(swarmUrl)), - downloadDataToDisk: uncurry(downloadDataToDisk(swarmUrl)), - downloadDirectory: uncurry(downloadDirectory(swarmUrl)), - downloadDirectoryToDisk: uncurry(downloadDirectoryToDisk(swarmUrl)), - downloadEntries: uncurry(downloadEntries(swarmUrl)), - downloadRoutes: uncurry(downloadRoutes(swarmUrl)), - isAvailable: function isAvailable() { - return _isAvailable(swarmUrl); - }, - upload: function upload(arg) { - return _upload(swarmUrl)(arg); - }, - uploadData: uncurry(uploadData(swarmUrl)), - uploadFile: uncurry(uploadFile(swarmUrl)), - uploadFileFromDisk: uncurry(uploadFile(swarmUrl)), - uploadDataFromDisk: uncurry(uploadDataFromDisk(swarmUrl)), - uploadDirectory: uncurry(uploadDirectory(swarmUrl)), - uploadDirectoryFromDisk: uncurry(uploadDirectoryFromDisk(swarmUrl)), - uploadToManifest: uncurry(uploadToManifest(swarmUrl)), - pick: pick, - hash: hash, - fromString: fromString, - toString: toString - }; - }; - - return { - at: at, - local: local, - download: _download, - downloadBinary: downloadBinary, - downloadData: downloadData, - downloadDataToDisk: downloadDataToDisk, - downloadDirectory: downloadDirectory, - downloadDirectoryToDisk: downloadDirectoryToDisk, - downloadEntries: downloadEntries, - downloadRoutes: downloadRoutes, - isAvailable: _isAvailable, - startProcess: startProcess, - stopProcess: stopProcess, - upload: _upload, - uploadData: uploadData, - uploadDataFromDisk: uploadDataFromDisk, - uploadFile: uploadFile, - uploadFileFromDisk: uploadFileFromDisk, - uploadDirectory: uploadDirectory, - uploadDirectoryFromDisk: uploadDirectoryFromDisk, - uploadToManifest: uploadToManifest, - pick: pick, - hash: hash, - fromString: fromString, - toString: toString - }; -}; -},{}],1748:[function(require,module,exports){ +},{"_process":1258}],1499:[function(require,module,exports){ 'use strict' const throttle = require('lodash.throttle') @@ -228861,7 +163736,7 @@ function getTimeElapsed (prevTime) { return Math.floor(a / 1000) } -},{"lodash.throttle":1215}],1749:[function(require,module,exports){ +},{"lodash.throttle":1044}],1500:[function(require,module,exports){ (function (setImmediate,clearImmediate){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; @@ -228940,7 +163815,7 @@ exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : delete immediateIds[id]; }; }).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":1438,"timers":1749}],1750:[function(require,module,exports){ +},{"process/browser.js":1258,"timers":1500}],1501:[function(require,module,exports){ /** * Timestamp for 64-bit time_t, nanosecond precision and strftime * @@ -229348,7 +164223,7 @@ var Timestamp = (function() { } })(); -},{}],1751:[function(require,module,exports){ +},{}],1502:[function(require,module,exports){ module.exports = toArray function toArray(list, index) { @@ -229363,1999 +164238,14 @@ function toArray(list, index) { return array } -},{}],1752:[function(require,module,exports){ -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * 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. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. - */ -'use strict'; -var net = require('net'); -var urlParse = require('url').parse; -var util = require('util'); -var pubsuffix = require('./pubsuffix-psl'); -var Store = require('./store').Store; -var MemoryCookieStore = require('./memstore').MemoryCookieStore; -var pathMatch = require('./pathMatch').pathMatch; -var VERSION = require('../package.json').version; - -var punycode; -try { - punycode = require('punycode'); -} catch(e) { - console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); -} - -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -var CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -var TERMINATORS = ['\n', '\r', '\0']; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -var MONTH_TO_NUM = { - jan:0, feb:1, mar:2, apr:3, may:4, jun:5, - jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 -}; -var NUM_TO_MONTH = [ - 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' -]; -var NUM_TO_DAY = [ - 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' -]; - -var MAX_TIME = 2147483647000; // 31-bit max -var MIN_TIME = 0; // 31-bit min - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - var count = 0; - while (count < token.length) { - var c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2F || c >= 0x3A) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0,count), 10); -} - -function parseTime(token) { - var parts = token.split(':'); - var result = [0,0,0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (var i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - var trailingOK = (i == 2); - var num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token).substr(0,3).toLowerCase(); - var num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - var tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - var hour = null; - var minute = null; - var second = null; - var dayOfMonth = null; - var month = null; - var year = null; - - for (var i=0; i= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || month === null || year === null || second === null || - dayOfMonth < 1 || dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; - var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; - var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; - var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; - return NUM_TO_DAY[date.getUTCDay()] + ', ' + - d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ - h+':'+m+':'+s+' GMT'; -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * "The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ - - /* "* The string is a host name (i.e., not an IP address)." */ - if (net.isIP(str)) { - return false; - } - - /* "* The domain string is a suffix of the string" */ - var idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // e.g "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { // it's not a suffix - return false; - } - - /* "* The last character of the string that is not included in the domain - * string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; - } - - return true; -} - - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0,1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - var rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (var t = 0; t < TERMINATORS.length; t++) { - var terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0,terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - var firstEq = cookiePair.indexOf('='); - if (looseMode) { - if (firstEq === 0) { // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf('='); // might still need to split on '=' - } - } else { // non-loose mode - if (firstEq <= 0) { // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - var cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq+1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - var c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== 'object') { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - var firstSemi = str.indexOf(';'); // S5.2 step 1 - var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); - var c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - var unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - var cookie_avs = unparsed.split(';'); - while (cookie_avs.length) { - var av = cookie_avs.shift().trim(); - if (av.length === 0) { // happens if ";;" appears - continue; - } - var av_sep = av.indexOf('='); - var av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; - } else { - av_key = av.substr(0,av_sep); - av_value = av.substr(av_sep+1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch(av_key) { - case 'expires': // S5.2.1 - if (av_value) { - var exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case 'max-age': // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - var delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case 'domain': // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - var domain = av_value.trim().replace(/^\./, ''); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case 'path': // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case 'secure': // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case 'httponly': // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - var obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - var obj; - if (typeof str === 'string') { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; - } - } else { - // assume it's an Object - obj = str; - } - - var c = new Cookie(); - for (var i=0; i 1) { - var lindex = path.lastIndexOf('/'); - if (lindex === 0) { - break; - } - path = path.substr(0,lindex); - permutations.push(path); - } - permutations.push('/'); - return permutations; -} - -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } - catch(err) { - // Silently swallow error - } - - return urlParse(url); -} - -function Cookie(options) { - options = options || {}; - - Object.keys(options).forEach(function(prop) { - if (Cookie.prototype.hasOwnProperty(prop) && - Cookie.prototype[prop] !== options[prop] && - prop.substr(0,1) !== '_') - { - this[prop] = options[prop]; - } - }, this); - - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, 'creationIndex', { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); -} - -Cookie.cookiesCreated = 0; // incremented each time a cookie is created - -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; - -Cookie.prototype.key = ""; -Cookie.prototype.value = ""; - -// the order in which the RFC has them: -Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity -Cookie.prototype.maxAge = null; // takes precedence over expires for TTL -Cookie.prototype.domain = null; -Cookie.prototype.path = null; -Cookie.prototype.secure = false; -Cookie.prototype.httpOnly = false; -Cookie.prototype.extensions = null; - -// set by the CookieJar: -Cookie.prototype.hostOnly = null; // boolean when set -Cookie.prototype.pathIsDefault = null; // boolean when set -Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse -Cookie.prototype.lastAccessed = null; // Date when set -Object.defineProperty(Cookie.prototype, 'creationIndex', { - configurable: true, - enumerable: false, - writable: true, - value: 0 -}); - -Cookie.serializableProperties = Object.keys(Cookie.prototype) - .filter(function(prop) { - return !( - Cookie.prototype[prop] instanceof Function || - prop === 'creationIndex' || - prop.substr(0,1) === '_' - ); - }); - -Cookie.prototype.inspect = function inspect() { - var now = Date.now(); - return 'Cookie="'+this.toString() + - '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + - '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + - '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + - '"'; -}; - -// Use the new custom inspection symbol to add the custom inspect function if -// available. -if (util.inspect.custom) { - Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; -} - -Cookie.prototype.toJSON = function() { - var obj = {}; - - var props = Cookie.serializableProperties; - for (var i=0; i=2.4.3 <2.5.0", - "_hasShrinkwrap": false, - "_id": "tough-cookie@2.4.3", - "_inCache": true, - "_installable": true, - "_location": "/tough-cookie", - "_nodeVersion": "10.5.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/tough-cookie_2.4.3_1529960207843_0.4882910670728131" - }, - "_npmUser": { - "email": "jstash@gmail.com", - "name": "jstash" - }, - "_npmVersion": "6.1.0", - "_phantomChildren": {}, - "_requested": { - "name": "tough-cookie", - "raw": "tough-cookie@~2.4.3", - "rawSpec": "~2.4.3", - "scope": null, - "spec": ">=2.4.3 <2.5.0", - "type": "range" - }, - "_requiredBy": [ - "/request" - ], - "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", - "_shasum": "53f36da3f47783b0925afa06ff9f3b165280f781", - "_shrinkwrap": null, - "_spec": "tough-cookie@~2.4.3", - "_where": "/var/www/html/ethoFSV2/node_modules/request", - "author": { - "email": "jstash@gmail.com", - "name": "Jeremy Stashewsky" - }, - "bugs": { - "url": "https://github.com/salesforce/tough-cookie/issues" - }, - "contributors": [ - { - "name": "Alexander Savin" - }, - { - "name": "Ian Livingstone" - }, - { - "name": "Ivan Nikulin" - }, - { - "name": "Lalit Kapoor" - }, - { - "name": "Sam Thompson" - }, - { - "name": "Sebastian Mayr" - } - ], - "dependencies": { - "psl": "^1.1.24", - "punycode": "^1.4.1" - }, - "description": "RFC6265 Cookies and Cookie Jar for node.js", - "devDependencies": { - "async": "^1.4.2", - "nyc": "^11.6.0", - "string.prototype.repeat": "^0.2.0", - "vows": "^0.8.1" - }, - "directories": {}, - "dist": { - "fileCount": 9, - "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbMVcQCRA9TVsSAnZWagAAzX0P/2COkbzb3dOX/FTOYIVL\n7oHge7BvGODNkEHTjBtNsR0jO/AA/gVcUOq6CSmFH+UC14LrmCyNDemQvD15\njnYuJXUIiZsSZO7BGGbOFYrQF+DKLiwgf0LokrIM8KasZ5nxc5xS1jYHG5o+\nwCqutfhlRTqlPbZsexB+eRlIuYNvpsbRAdSDYXrhLJNMZgx49g/SZ7IwunGN\nJ/5Fe041MZqqdi7MAavM3T7vX9IvVRJJ3f4xAEVxY1vh4s0dN+h4fG2eMQzL\nOiaulRUIahs4xmJUYHZgZESc9eTIrI8K+YT7i3r35TGc0Du7ueB2KYxBqy7q\n6AUFbdX9Ep308kTVsTf/h4wE0RvdxKLfZ0ww7T1ivADX9xMi2oIvVtyhCQHo\nSIpyBhaav/fTufF0/Fu4Lcr7PMJxyvF0UcNRqrPmEQTw4UZkFKfT8HN2P5cH\nBvJsFwpeEjt84tt5pJ/bmD0j0EUCLUXLGH6fbA84fHpZGifO239zSf262Qdv\nSXeygU7YxnK8wOCnvlauZx/gp+/WTMfMdODxiX0QnqwS5BctiPCgGG1cKJcC\nqvTECaAEmxMVf/gEW73oxVXJgUO7f6jJaWoawV7ka+wR91W9Bp0pKGOOAxAG\nU72rmnwQKid9U7ly5833sb3D+lbzKJXGNIqohegP4daKZfNNTaLWZXmKE+Iy\n7Vml\r\n=8KpS\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "53f36da3f47783b0925afa06ff9f3b165280f781", - "tarball": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", - "unpackedSize": 83959 - }, - "engines": { - "node": ">=0.8" - }, - "files": [ - "lib" - ], - "gitHead": "671ad413b38d7464352886772f57a7ec417d4760", - "homepage": "https://github.com/salesforce/tough-cookie", - "keywords": [ - "HTTP", - "RFC2965", - "RFC6265", - "cookie", - "cookiejar", - "cookies", - "jar", - "set-cookie" - ], - "license": "BSD-3-Clause", - "main": "./lib/cookie", - "maintainers": [ - { - "name": "awaterma", - "email": "awaterma@awaterma.net" - }, - { - "name": "jstash", - "email": "jstash@gmail.com" - }, - { - "name": "maratto", - "email": "marat+npm@salesforce.com" - }, - { - "name": "ruoho", - "email": "clint@ruoho.org" - } - ], - "name": "tough-cookie", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git://github.com/salesforce/tough-cookie.git" - }, - "scripts": { - "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js", - "test": "vows test/*_test.js" - }, - "version": "2.4.3" -} - -},{}],1759:[function(require,module,exports){ +},{}],1503:[function(require,module,exports){ 'use strict'; var truncate = require("./lib/truncate"); var getLength = require("utf8-byte-length/browser"); module.exports = truncate.bind(null, getLength); -},{"./lib/truncate":1760,"utf8-byte-length/browser":1771}],1760:[function(require,module,exports){ +},{"./lib/truncate":1504,"utf8-byte-length/browser":1509}],1504:[function(require,module,exports){ 'use strict'; function isHighSurrogate(codePoint) { @@ -231400,2674 +164290,7 @@ module.exports = function truncate(getLength, string, byteLength) { }; -},{}],1761:[function(require,module,exports){ -(function (process){ -'use strict' - -var net = require('net') - , tls = require('tls') - , http = require('http') - , https = require('https') - , events = require('events') - , assert = require('assert') - , util = require('util') - , Buffer = require('safe-buffer').Buffer - ; - -exports.httpOverHttp = httpOverHttp -exports.httpsOverHttp = httpsOverHttp -exports.httpOverHttps = httpOverHttps -exports.httpsOverHttps = httpsOverHttps - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options) - agent.request = http.request - return agent -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options) - agent.request = http.request - agent.createSocket = createSecureSocket - agent.defaultPort = 443 - return agent -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options) - agent.request = https.request - return agent -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options) - agent.request = https.request - agent.createSocket = createSecureSocket - agent.defaultPort = 443 - return agent -} - - -function TunnelingAgent(options) { - var self = this - self.options = options || {} - self.proxyOptions = self.options.proxy || {} - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets - self.requests = [] - self.sockets = [] - - self.on('free', function onFree(socket, host, port) { - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i] - if (pending.host === host && pending.port === port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1) - pending.request.onSocket(socket) - return - } - } - socket.destroy() - self.removeSocket(socket) - }) -} -util.inherits(TunnelingAgent, events.EventEmitter) - -TunnelingAgent.prototype.addRequest = function addRequest(req, options) { - var self = this - - // Legacy API: addRequest(req, host, port, path) - if (typeof options === 'string') { - options = { - host: options, - port: arguments[2], - path: arguments[3] - }; - } - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push({host: options.host, port: options.port, request: req}) - return - } - - // If we are under maxSockets create a new one. - self.createConnection({host: options.host, port: options.port, request: req}) -} - -TunnelingAgent.prototype.createConnection = function createConnection(pending) { - var self = this - - self.createSocket(pending, function(socket) { - socket.on('free', onFree) - socket.on('close', onCloseOrRemove) - socket.on('agentRemove', onCloseOrRemove) - pending.request.onSocket(socket) - - function onFree() { - self.emit('free', socket, pending.host, pending.port) - } - - function onCloseOrRemove(err) { - self.removeSocket(socket) - socket.removeListener('free', onFree) - socket.removeListener('close', onCloseOrRemove) - socket.removeListener('agentRemove', onCloseOrRemove) - } - }) -} - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this - var placeholder = {} - self.sockets.push(placeholder) - - var connectOptions = mergeOptions({}, self.proxyOptions, - { method: 'CONNECT' - , path: options.host + ':' + options.port - , agent: false - } - ) - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {} - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - Buffer.from(connectOptions.proxyAuth).toString('base64') - } - - debug('making CONNECT request') - var connectReq = self.request(connectOptions) - connectReq.useChunkedEncodingByDefault = false // for v0.6 - connectReq.once('response', onResponse) // for v0.6 - connectReq.once('upgrade', onUpgrade) // for v0.6 - connectReq.once('connect', onConnect) // for v0.7 or later - connectReq.once('error', onError) - connectReq.end() - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head) - }) - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners() - socket.removeAllListeners() - - if (res.statusCode === 200) { - assert.equal(head.length, 0) - debug('tunneling connection has established') - self.sockets[self.sockets.indexOf(placeholder)] = socket - cb(socket) - } else { - debug('tunneling socket could not be established, statusCode=%d', res.statusCode) - var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) - error.code = 'ECONNRESET' - options.request.emit('error', error) - self.removeSocket(placeholder) - } - } - - function onError(cause) { - connectReq.removeAllListeners() - - debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack) - var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message) - error.code = 'ECONNRESET' - options.request.emit('error', error) - self.removeSocket(placeholder) - } -} - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) return - - this.sockets.splice(pos, 1) - - var pending = this.requests.shift() - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createConnection(pending) - } -} - -function createSecureSocket(options, cb) { - var self = this - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, mergeOptions({}, self.options, - { servername: options.host - , socket: socket - } - )) - self.sockets[self.sockets.indexOf(socket)] = secureSocket - cb(secureSocket) - }) -} - - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i] - if (typeof overrides === 'object') { - var keys = Object.keys(overrides) - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j] - if (overrides[k] !== undefined) { - target[k] = overrides[k] - } - } - } - } - return target -} - - -var debug -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments) - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0] - } else { - args.unshift('TUNNEL:') - } - console.error.apply(console, args) - } -} else { - debug = function() {} -} -exports.debug = debug // for test - -}).call(this,require('_process')) -},{"_process":1438,"assert":78,"events":370,"http":1716,"https":446,"net":212,"safe-buffer":1593,"tls":212,"util":1776}],1762:[function(require,module,exports){ -(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/ - -var gf = function(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. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; - -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; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; -} - -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; - } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; -} - -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); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); -} - -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); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - 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 -*/ - -var poly1305 = function(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; -}; - -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; -}; - -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; - - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } - - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; - } - 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; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; - } - g[9] -= (1 << 13); - - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - - 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; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; - } - - 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; -}; - -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; - - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } - - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } - - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } -}; - -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; -} - -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); -} - -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); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; -} - -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); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; -} - -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} - -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c-1 + 37 * (c-1); -} - -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } -} - -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; - } -} - -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); -} - -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; -} - -function unpack25519(o, n) { - var i; - 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 - 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; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} - -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(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - 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); - } - 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]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} - -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]); - - return 0; -} - -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; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} - -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; -} - -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - 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); - } -} - -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); -} - -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); - - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} - -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]); - -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - 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; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} - -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} - -// Note: difference from C - smlen returned, not passed as argument. -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; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); - - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } - - modL(sm.subarray(32), x); - return smlen; -} - -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; -} - -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; - - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); - - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } - - 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 */ - -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'); -} - -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'); -} - -function checkArrayTypes() { - var t, i; - 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'); - } -} - -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'); - }; -} - -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]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; - -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); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - 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); -}; - -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - -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; -}; - -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; -}; - -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); -}; - -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; -}; - -nacl.box.after = nacl.secretbox; - -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; - -nacl.box.open.after = nacl.secretbox.open; - -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}; -}; - -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)}; -}; - -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; -}; - -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); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; -}; - -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; -}; - -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; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - 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 {publicKey: pk, secretKey: sk}; -}; - -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); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; -}; - -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); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; -}; - -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; - -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; - -nacl.hash.hashLength = crypto_hash_BYTES; - -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - 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; -}; - -nacl.setPRNG = function(fn) { - randombytes = fn; -}; - -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (typeof require !== 'undefined') { - // Node.js. - crypto = require('crypto'); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); - -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); - -},{"crypto":182}],1763:[function(require,module,exports){ -(function (Buffer){ -/** - * Convert a typed array to a Buffer without a copy - * - * Author: Feross Aboukhadijeh - * License: MIT - * - * `npm install typedarray-to-buffer` - */ - -var isTypedArray = require('is-typedarray').strict - -module.exports = function typedarrayToBuffer (arr) { - if (isTypedArray(arr)) { - // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer - var buf = Buffer.from(arr.buffer) - if (arr.byteLength !== arr.buffer.byteLength) { - // Respect the "view", i.e. byteOffset and byteLength, without doing a copy - buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength) - } - return buf - } else { - // Pass through all other types to `Buffer.from` - return Buffer.from(arr) - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":217,"is-typedarray":779}],1764:[function(require,module,exports){ +},{}],1505:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : @@ -234326,1703 +164549,7 @@ module.exports = function typedarrayToBuffer (arr) { })); -},{}],1765:[function(require,module,exports){ -(function (global){ -// Underscore.js 1.9.1 -// http://underscorejs.org -// (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors -// Underscore may be freely distributed under the MIT license. - -(function() { - - // Baseline setup - // -------------- - - // Establish the root object, `window` (`self`) in the browser, `global` - // on the server, or `this` in some virtual machines. We use `self` - // instead of `window` for `WebWorker` support. - var root = typeof self == 'object' && self.self === self && self || - typeof global == 'object' && global.global === global && global || - this || - {}; - - // Save the previous value of the `_` variable. - var previousUnderscore = root._; - - // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype; - var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; - - // Create quick reference variables for speed access to core prototypes. - var push = ArrayProto.push, - slice = ArrayProto.slice, - toString = ObjProto.toString, - hasOwnProperty = ObjProto.hasOwnProperty; - - // All **ECMAScript 5** native function implementations that we hope to use - // are declared here. - var nativeIsArray = Array.isArray, - nativeKeys = Object.keys, - nativeCreate = Object.create; - - // Naked function reference for surrogate-prototype-swapping. - var Ctor = function(){}; - - // Create a safe reference to the Underscore object for use below. - var _ = function(obj) { - if (obj instanceof _) return obj; - if (!(this instanceof _)) return new _(obj); - this._wrapped = obj; - }; - - // Export the Underscore object for **Node.js**, with - // backwards-compatibility for their old module API. If we're in - // the browser, add `_` as a global object. - // (`nodeType` is checked to ensure that `module` - // and `exports` are not HTML elements.) - if (typeof exports != 'undefined' && !exports.nodeType) { - if (typeof module != 'undefined' && !module.nodeType && module.exports) { - exports = module.exports = _; - } - exports._ = _; - } else { - root._ = _; - } - - // Current version. - _.VERSION = '1.9.1'; - - // Internal function that returns an efficient (for current engines) version - // of the passed-in callback, to be repeatedly applied in other Underscore - // functions. - var optimizeCb = function(func, context, argCount) { - if (context === void 0) return func; - switch (argCount == null ? 3 : argCount) { - case 1: return function(value) { - return func.call(context, value); - }; - // The 2-argument case is omitted because we’re not using it. - case 3: return function(value, index, collection) { - return func.call(context, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(context, accumulator, value, index, collection); - }; - } - return function() { - return func.apply(context, arguments); - }; - }; - - var builtinIteratee; - - // An internal function to generate callbacks that can be applied to each - // element in a collection, returning the desired result — either `identity`, - // an arbitrary callback, a property matcher, or a property accessor. - var cb = function(value, context, argCount) { - if (_.iteratee !== builtinIteratee) return _.iteratee(value, context); - if (value == null) return _.identity; - if (_.isFunction(value)) return optimizeCb(value, context, argCount); - if (_.isObject(value) && !_.isArray(value)) return _.matcher(value); - return _.property(value); - }; - - // External wrapper for our callback generator. Users may customize - // `_.iteratee` if they want additional predicate/iteratee shorthand styles. - // This abstraction hides the internal-only argCount argument. - _.iteratee = builtinIteratee = function(value, context) { - return cb(value, context, Infinity); - }; - - // Some functions take a variable number of arguments, or a few expected - // arguments at the beginning and then a variable number of values to operate - // on. This helper accumulates all remaining arguments past the function’s - // argument length (or an explicit `startIndex`), into an array that becomes - // the last argument. Similar to ES6’s "rest parameter". - var restArguments = function(func, startIndex) { - startIndex = startIndex == null ? func.length - 1 : +startIndex; - return function() { - var length = Math.max(arguments.length - startIndex, 0), - rest = Array(length), - index = 0; - for (; index < length; index++) { - rest[index] = arguments[index + startIndex]; - } - switch (startIndex) { - case 0: return func.call(this, rest); - case 1: return func.call(this, arguments[0], rest); - case 2: return func.call(this, arguments[0], arguments[1], rest); - } - var args = Array(startIndex + 1); - for (index = 0; index < startIndex; index++) { - args[index] = arguments[index]; - } - args[startIndex] = rest; - return func.apply(this, args); - }; - }; - - // An internal function for creating a new object that inherits from another. - var baseCreate = function(prototype) { - if (!_.isObject(prototype)) return {}; - if (nativeCreate) return nativeCreate(prototype); - Ctor.prototype = prototype; - var result = new Ctor; - Ctor.prototype = null; - return result; - }; - - var shallowProperty = function(key) { - return function(obj) { - return obj == null ? void 0 : obj[key]; - }; - }; - - var has = function(obj, path) { - return obj != null && hasOwnProperty.call(obj, path); - } - - var deepGet = function(obj, path) { - var length = path.length; - for (var i = 0; i < length; i++) { - if (obj == null) return void 0; - obj = obj[path[i]]; - } - return length ? obj : void 0; - }; - - // Helper for collection methods to determine whether a collection - // should be iterated as an array or as an object. - // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength - // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 - var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; - var getLength = shallowProperty('length'); - var isArrayLike = function(collection) { - var length = getLength(collection); - return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; - }; - - // Collection Functions - // -------------------- - - // The cornerstone, an `each` implementation, aka `forEach`. - // Handles raw objects in addition to array-likes. Treats all - // sparse array-likes as if they were dense. - _.each = _.forEach = function(obj, iteratee, context) { - iteratee = optimizeCb(iteratee, context); - var i, length; - if (isArrayLike(obj)) { - for (i = 0, length = obj.length; i < length; i++) { - iteratee(obj[i], i, obj); - } - } else { - var keys = _.keys(obj); - for (i = 0, length = keys.length; i < length; i++) { - iteratee(obj[keys[i]], keys[i], obj); - } - } - return obj; - }; - - // Return the results of applying the iteratee to each element. - _.map = _.collect = function(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length, - results = Array(length); - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - results[index] = iteratee(obj[currentKey], currentKey, obj); - } - return results; - }; - - // Create a reducing function iterating left or right. - var createReduce = function(dir) { - // Wrap code that reassigns argument variables in a separate function than - // the one that accesses `arguments.length` to avoid a perf hit. (#1991) - var reducer = function(obj, iteratee, memo, initial) { - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length, - index = dir > 0 ? 0 : length - 1; - if (!initial) { - memo = obj[keys ? keys[index] : index]; - index += dir; - } - for (; index >= 0 && index < length; index += dir) { - var currentKey = keys ? keys[index] : index; - memo = iteratee(memo, obj[currentKey], currentKey, obj); - } - return memo; - }; - - return function(obj, iteratee, memo, context) { - var initial = arguments.length >= 3; - return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); - }; - }; - - // **Reduce** builds up a single result from a list of values, aka `inject`, - // or `foldl`. - _.reduce = _.foldl = _.inject = createReduce(1); - - // The right-associative version of reduce, also known as `foldr`. - _.reduceRight = _.foldr = createReduce(-1); - - // Return the first value which passes a truth test. Aliased as `detect`. - _.find = _.detect = function(obj, predicate, context) { - var keyFinder = isArrayLike(obj) ? _.findIndex : _.findKey; - var key = keyFinder(obj, predicate, context); - if (key !== void 0 && key !== -1) return obj[key]; - }; - - // Return all the elements that pass a truth test. - // Aliased as `select`. - _.filter = _.select = function(obj, predicate, context) { - var results = []; - predicate = cb(predicate, context); - _.each(obj, function(value, index, list) { - if (predicate(value, index, list)) results.push(value); - }); - return results; - }; - - // Return all the elements for which a truth test fails. - _.reject = function(obj, predicate, context) { - return _.filter(obj, _.negate(cb(predicate)), context); - }; - - // Determine whether all of the elements match a truth test. - // Aliased as `all`. - _.every = _.all = function(obj, predicate, context) { - predicate = cb(predicate, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - if (!predicate(obj[currentKey], currentKey, obj)) return false; - } - return true; - }; - - // Determine if at least one element in the object matches a truth test. - // Aliased as `any`. - _.some = _.any = function(obj, predicate, context) { - predicate = cb(predicate, context); - var keys = !isArrayLike(obj) && _.keys(obj), - length = (keys || obj).length; - for (var index = 0; index < length; index++) { - var currentKey = keys ? keys[index] : index; - if (predicate(obj[currentKey], currentKey, obj)) return true; - } - return false; - }; - - // Determine if the array or object contains a given item (using `===`). - // Aliased as `includes` and `include`. - _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { - if (!isArrayLike(obj)) obj = _.values(obj); - if (typeof fromIndex != 'number' || guard) fromIndex = 0; - return _.indexOf(obj, item, fromIndex) >= 0; - }; - - // Invoke a method (with arguments) on every item in a collection. - _.invoke = restArguments(function(obj, path, args) { - var contextPath, func; - if (_.isFunction(path)) { - func = path; - } else if (_.isArray(path)) { - contextPath = path.slice(0, -1); - path = path[path.length - 1]; - } - return _.map(obj, function(context) { - var method = func; - if (!method) { - if (contextPath && contextPath.length) { - context = deepGet(context, contextPath); - } - if (context == null) return void 0; - method = context[path]; - } - return method == null ? method : method.apply(context, args); - }); - }); - - // Convenience version of a common use case of `map`: fetching a property. - _.pluck = function(obj, key) { - return _.map(obj, _.property(key)); - }; - - // Convenience version of a common use case of `filter`: selecting only objects - // containing specific `key:value` pairs. - _.where = function(obj, attrs) { - return _.filter(obj, _.matcher(attrs)); - }; - - // Convenience version of a common use case of `find`: getting the first object - // containing specific `key:value` pairs. - _.findWhere = function(obj, attrs) { - return _.find(obj, _.matcher(attrs)); - }; - - // Return the maximum element (or element-based computation). - _.max = function(obj, iteratee, context) { - var result = -Infinity, lastComputed = -Infinity, - value, computed; - if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { - obj = isArrayLike(obj) ? obj : _.values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value > result) { - result = value; - } - } - } else { - iteratee = cb(iteratee, context); - _.each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed > lastComputed || computed === -Infinity && result === -Infinity) { - result = v; - lastComputed = computed; - } - }); - } - return result; - }; - - // Return the minimum element (or element-based computation). - _.min = function(obj, iteratee, context) { - var result = Infinity, lastComputed = Infinity, - value, computed; - if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) { - obj = isArrayLike(obj) ? obj : _.values(obj); - for (var i = 0, length = obj.length; i < length; i++) { - value = obj[i]; - if (value != null && value < result) { - result = value; - } - } - } else { - iteratee = cb(iteratee, context); - _.each(obj, function(v, index, list) { - computed = iteratee(v, index, list); - if (computed < lastComputed || computed === Infinity && result === Infinity) { - result = v; - lastComputed = computed; - } - }); - } - return result; - }; - - // Shuffle a collection. - _.shuffle = function(obj) { - return _.sample(obj, Infinity); - }; - - // Sample **n** random values from a collection using the modern version of the - // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). - // If **n** is not specified, returns a single random element. - // The internal `guard` argument allows it to work with `map`. - _.sample = function(obj, n, guard) { - if (n == null || guard) { - if (!isArrayLike(obj)) obj = _.values(obj); - return obj[_.random(obj.length - 1)]; - } - var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); - var length = getLength(sample); - n = Math.max(Math.min(n, length), 0); - var last = length - 1; - for (var index = 0; index < n; index++) { - var rand = _.random(index, last); - var temp = sample[index]; - sample[index] = sample[rand]; - sample[rand] = temp; - } - return sample.slice(0, n); - }; - - // Sort the object's values by a criterion produced by an iteratee. - _.sortBy = function(obj, iteratee, context) { - var index = 0; - iteratee = cb(iteratee, context); - return _.pluck(_.map(obj, function(value, key, list) { - return { - value: value, - index: index++, - criteria: iteratee(value, key, list) - }; - }).sort(function(left, right) { - var a = left.criteria; - var b = right.criteria; - if (a !== b) { - if (a > b || a === void 0) return 1; - if (a < b || b === void 0) return -1; - } - return left.index - right.index; - }), 'value'); - }; - - // An internal function used for aggregate "group by" operations. - var group = function(behavior, partition) { - return function(obj, iteratee, context) { - var result = partition ? [[], []] : {}; - iteratee = cb(iteratee, context); - _.each(obj, function(value, index) { - var key = iteratee(value, index, obj); - behavior(result, value, key); - }); - return result; - }; - }; - - // Groups the object's values by a criterion. Pass either a string attribute - // to group by, or a function that returns the criterion. - _.groupBy = group(function(result, value, key) { - if (has(result, key)) result[key].push(value); else result[key] = [value]; - }); - - // Indexes the object's values by a criterion, similar to `groupBy`, but for - // when you know that your index values will be unique. - _.indexBy = group(function(result, value, key) { - result[key] = value; - }); - - // Counts instances of an object that group by a certain criterion. Pass - // either a string attribute to count by, or a function that returns the - // criterion. - _.countBy = group(function(result, value, key) { - if (has(result, key)) result[key]++; else result[key] = 1; - }); - - var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; - // Safely create a real, live array from anything iterable. - _.toArray = function(obj) { - if (!obj) return []; - if (_.isArray(obj)) return slice.call(obj); - if (_.isString(obj)) { - // Keep surrogate pair characters together - return obj.match(reStrSymbol); - } - if (isArrayLike(obj)) return _.map(obj, _.identity); - return _.values(obj); - }; - - // Return the number of elements in an object. - _.size = function(obj) { - if (obj == null) return 0; - return isArrayLike(obj) ? obj.length : _.keys(obj).length; - }; - - // Split a collection into two arrays: one whose elements all satisfy the given - // predicate, and one whose elements all do not satisfy the predicate. - _.partition = group(function(result, value, pass) { - result[pass ? 0 : 1].push(value); - }, true); - - // Array Functions - // --------------- - - // Get the first element of an array. Passing **n** will return the first N - // values in the array. Aliased as `head` and `take`. The **guard** check - // allows it to work with `_.map`. - _.first = _.head = _.take = function(array, n, guard) { - if (array == null || array.length < 1) return n == null ? void 0 : []; - if (n == null || guard) return array[0]; - return _.initial(array, array.length - n); - }; - - // Returns everything but the last entry of the array. Especially useful on - // the arguments object. Passing **n** will return all the values in - // the array, excluding the last N. - _.initial = function(array, n, guard) { - return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); - }; - - // Get the last element of an array. Passing **n** will return the last N - // values in the array. - _.last = function(array, n, guard) { - if (array == null || array.length < 1) return n == null ? void 0 : []; - if (n == null || guard) return array[array.length - 1]; - return _.rest(array, Math.max(0, array.length - n)); - }; - - // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. - // Especially useful on the arguments object. Passing an **n** will return - // the rest N values in the array. - _.rest = _.tail = _.drop = function(array, n, guard) { - return slice.call(array, n == null || guard ? 1 : n); - }; - - // Trim out all falsy values from an array. - _.compact = function(array) { - return _.filter(array, Boolean); - }; - - // Internal implementation of a recursive `flatten` function. - var flatten = function(input, shallow, strict, output) { - output = output || []; - var idx = output.length; - for (var i = 0, length = getLength(input); i < length; i++) { - var value = input[i]; - if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { - // Flatten current level of array or arguments object. - if (shallow) { - var j = 0, len = value.length; - while (j < len) output[idx++] = value[j++]; - } else { - flatten(value, shallow, strict, output); - idx = output.length; - } - } else if (!strict) { - output[idx++] = value; - } - } - return output; - }; - - // Flatten out an array, either recursively (by default), or just one level. - _.flatten = function(array, shallow) { - return flatten(array, shallow, false); - }; - - // Return a version of the array that does not contain the specified value(s). - _.without = restArguments(function(array, otherArrays) { - return _.difference(array, otherArrays); - }); - - // Produce a duplicate-free version of the array. If the array has already - // been sorted, you have the option of using a faster algorithm. - // The faster algorithm will not work with an iteratee if the iteratee - // is not a one-to-one function, so providing an iteratee will disable - // the faster algorithm. - // Aliased as `unique`. - _.uniq = _.unique = function(array, isSorted, iteratee, context) { - if (!_.isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; - } - if (iteratee != null) iteratee = cb(iteratee, context); - var result = []; - var seen = []; - for (var i = 0, length = getLength(array); i < length; i++) { - var value = array[i], - computed = iteratee ? iteratee(value, i, array) : value; - if (isSorted && !iteratee) { - if (!i || seen !== computed) result.push(value); - seen = computed; - } else if (iteratee) { - if (!_.contains(seen, computed)) { - seen.push(computed); - result.push(value); - } - } else if (!_.contains(result, value)) { - result.push(value); - } - } - return result; - }; - - // Produce an array that contains the union: each distinct element from all of - // the passed-in arrays. - _.union = restArguments(function(arrays) { - return _.uniq(flatten(arrays, true, true)); - }); - - // Produce an array that contains every item shared between all the - // passed-in arrays. - _.intersection = function(array) { - var result = []; - var argsLength = arguments.length; - for (var i = 0, length = getLength(array); i < length; i++) { - var item = array[i]; - if (_.contains(result, item)) continue; - var j; - for (j = 1; j < argsLength; j++) { - if (!_.contains(arguments[j], item)) break; - } - if (j === argsLength) result.push(item); - } - return result; - }; - - // Take the difference between one array and a number of other arrays. - // Only the elements present in just the first array will remain. - _.difference = restArguments(function(array, rest) { - rest = flatten(rest, true, true); - return _.filter(array, function(value){ - return !_.contains(rest, value); - }); - }); - - // Complement of _.zip. Unzip accepts an array of arrays and groups - // each array's elements on shared indices. - _.unzip = function(array) { - var length = array && _.max(array, getLength).length || 0; - var result = Array(length); - - for (var index = 0; index < length; index++) { - result[index] = _.pluck(array, index); - } - return result; - }; - - // Zip together multiple lists into a single array -- elements that share - // an index go together. - _.zip = restArguments(_.unzip); - - // Converts lists into objects. Pass either a single array of `[key, value]` - // pairs, or two parallel arrays of the same length -- one of keys, and one of - // the corresponding values. Passing by pairs is the reverse of _.pairs. - _.object = function(list, values) { - var result = {}; - for (var i = 0, length = getLength(list); i < length; i++) { - if (values) { - result[list[i]] = values[i]; - } else { - result[list[i][0]] = list[i][1]; - } - } - return result; - }; - - // Generator function to create the findIndex and findLastIndex functions. - var createPredicateIndexFinder = function(dir) { - return function(array, predicate, context) { - predicate = cb(predicate, context); - var length = getLength(array); - var index = dir > 0 ? 0 : length - 1; - for (; index >= 0 && index < length; index += dir) { - if (predicate(array[index], index, array)) return index; - } - return -1; - }; - }; - - // Returns the first index on an array-like that passes a predicate test. - _.findIndex = createPredicateIndexFinder(1); - _.findLastIndex = createPredicateIndexFinder(-1); - - // Use a comparator function to figure out the smallest index at which - // an object should be inserted so as to maintain order. Uses binary search. - _.sortedIndex = function(array, obj, iteratee, context) { - iteratee = cb(iteratee, context, 1); - var value = iteratee(obj); - var low = 0, high = getLength(array); - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; - } - return low; - }; - - // Generator function to create the indexOf and lastIndexOf functions. - var createIndexFinder = function(dir, predicateFind, sortedIndex) { - return function(array, item, idx) { - var i = 0, length = getLength(array); - if (typeof idx == 'number') { - if (dir > 0) { - i = idx >= 0 ? idx : Math.max(idx + length, i); - } else { - length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; - } - } else if (sortedIndex && idx && length) { - idx = sortedIndex(array, item); - return array[idx] === item ? idx : -1; - } - if (item !== item) { - idx = predicateFind(slice.call(array, i, length), _.isNaN); - return idx >= 0 ? idx + i : -1; - } - for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { - if (array[idx] === item) return idx; - } - return -1; - }; - }; - - // Return the position of the first occurrence of an item in an array, - // or -1 if the item is not included in the array. - // If the array is large and already in sort order, pass `true` - // for **isSorted** to use binary search. - _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); - _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); - - // Generate an integer Array containing an arithmetic progression. A port of - // the native Python `range()` function. See - // [the Python documentation](http://docs.python.org/library/functions.html#range). - _.range = function(start, stop, step) { - if (stop == null) { - stop = start || 0; - start = 0; - } - if (!step) { - step = stop < start ? -1 : 1; - } - - var length = Math.max(Math.ceil((stop - start) / step), 0); - var range = Array(length); - - for (var idx = 0; idx < length; idx++, start += step) { - range[idx] = start; - } - - return range; - }; - - // Chunk a single array into multiple arrays, each containing `count` or fewer - // items. - _.chunk = function(array, count) { - if (count == null || count < 1) return []; - var result = []; - var i = 0, length = array.length; - while (i < length) { - result.push(slice.call(array, i, i += count)); - } - return result; - }; - - // Function (ahem) Functions - // ------------------ - - // Determines whether to execute a function as a constructor - // or a normal function with the provided arguments. - var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { - if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); - var self = baseCreate(sourceFunc.prototype); - var result = sourceFunc.apply(self, args); - if (_.isObject(result)) return result; - return self; - }; - - // Create a function bound to a given object (assigning `this`, and arguments, - // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if - // available. - _.bind = restArguments(function(func, context, args) { - if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); - var bound = restArguments(function(callArgs) { - return executeBound(func, bound, context, this, args.concat(callArgs)); - }); - return bound; - }); - - // Partially apply a function by creating a version that has had some of its - // arguments pre-filled, without changing its dynamic `this` context. _ acts - // as a placeholder by default, allowing any combination of arguments to be - // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. - _.partial = restArguments(function(func, boundArgs) { - var placeholder = _.partial.placeholder; - var bound = function() { - var position = 0, length = boundArgs.length; - var args = Array(length); - for (var i = 0; i < length; i++) { - args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; - } - while (position < arguments.length) args.push(arguments[position++]); - return executeBound(func, bound, this, this, args); - }; - return bound; - }); - - _.partial.placeholder = _; - - // Bind a number of an object's methods to that object. Remaining arguments - // are the method names to be bound. Useful for ensuring that all callbacks - // defined on an object belong to it. - _.bindAll = restArguments(function(obj, keys) { - keys = flatten(keys, false, false); - var index = keys.length; - if (index < 1) throw new Error('bindAll must be passed function names'); - while (index--) { - var key = keys[index]; - obj[key] = _.bind(obj[key], obj); - } - }); - - // Memoize an expensive function by storing its results. - _.memoize = function(func, hasher) { - var memoize = function(key) { - var cache = memoize.cache; - var address = '' + (hasher ? hasher.apply(this, arguments) : key); - if (!has(cache, address)) cache[address] = func.apply(this, arguments); - return cache[address]; - }; - memoize.cache = {}; - return memoize; - }; - - // Delays a function for the given number of milliseconds, and then calls - // it with the arguments supplied. - _.delay = restArguments(function(func, wait, args) { - return setTimeout(function() { - return func.apply(null, args); - }, wait); - }); - - // Defers a function, scheduling it to run after the current call stack has - // cleared. - _.defer = _.partial(_.delay, _, 1); - - // Returns a function, that, when invoked, will only be triggered at most once - // during a given window of time. Normally, the throttled function will run - // as much as it can, without ever going more than once per `wait` duration; - // but if you'd like to disable the execution on the leading edge, pass - // `{leading: false}`. To disable execution on the trailing edge, ditto. - _.throttle = function(func, wait, options) { - var timeout, context, args, result; - var previous = 0; - if (!options) options = {}; - - var later = function() { - previous = options.leading === false ? 0 : _.now(); - timeout = null; - result = func.apply(context, args); - if (!timeout) context = args = null; - }; - - var throttled = function() { - var now = _.now(); - if (!previous && options.leading === false) previous = now; - var remaining = wait - (now - previous); - context = this; - args = arguments; - if (remaining <= 0 || remaining > wait) { - if (timeout) { - clearTimeout(timeout); - timeout = null; - } - previous = now; - result = func.apply(context, args); - if (!timeout) context = args = null; - } else if (!timeout && options.trailing !== false) { - timeout = setTimeout(later, remaining); - } - return result; - }; - - throttled.cancel = function() { - clearTimeout(timeout); - previous = 0; - timeout = context = args = null; - }; - - return throttled; - }; - - // Returns a function, that, as long as it continues to be invoked, will not - // be triggered. The function will be called after it stops being called for - // N milliseconds. If `immediate` is passed, trigger the function on the - // leading edge, instead of the trailing. - _.debounce = function(func, wait, immediate) { - var timeout, result; - - var later = function(context, args) { - timeout = null; - if (args) result = func.apply(context, args); - }; - - var debounced = restArguments(function(args) { - if (timeout) clearTimeout(timeout); - if (immediate) { - var callNow = !timeout; - timeout = setTimeout(later, wait); - if (callNow) result = func.apply(this, args); - } else { - timeout = _.delay(later, wait, this, args); - } - - return result; - }); - - debounced.cancel = function() { - clearTimeout(timeout); - timeout = null; - }; - - return debounced; - }; - - // Returns the first function passed as an argument to the second, - // allowing you to adjust arguments, run code before and after, and - // conditionally execute the original function. - _.wrap = function(func, wrapper) { - return _.partial(wrapper, func); - }; - - // Returns a negated version of the passed-in predicate. - _.negate = function(predicate) { - return function() { - return !predicate.apply(this, arguments); - }; - }; - - // Returns a function that is the composition of a list of functions, each - // consuming the return value of the function that follows. - _.compose = function() { - var args = arguments; - var start = args.length - 1; - return function() { - var i = start; - var result = args[start].apply(this, arguments); - while (i--) result = args[i].call(this, result); - return result; - }; - }; - - // Returns a function that will only be executed on and after the Nth call. - _.after = function(times, func) { - return function() { - if (--times < 1) { - return func.apply(this, arguments); - } - }; - }; - - // Returns a function that will only be executed up to (but not including) the Nth call. - _.before = function(times, func) { - var memo; - return function() { - if (--times > 0) { - memo = func.apply(this, arguments); - } - if (times <= 1) func = null; - return memo; - }; - }; - - // Returns a function that will be executed at most one time, no matter how - // often you call it. Useful for lazy initialization. - _.once = _.partial(_.before, 2); - - _.restArguments = restArguments; - - // Object Functions - // ---------------- - - // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. - var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); - var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', - 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; - - var collectNonEnumProps = function(obj, keys) { - var nonEnumIdx = nonEnumerableProps.length; - var constructor = obj.constructor; - var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; - - // Constructor is a special case. - var prop = 'constructor'; - if (has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); - - while (nonEnumIdx--) { - prop = nonEnumerableProps[nonEnumIdx]; - if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { - keys.push(prop); - } - } - }; - - // Retrieve the names of an object's own properties. - // Delegates to **ECMAScript 5**'s native `Object.keys`. - _.keys = function(obj) { - if (!_.isObject(obj)) return []; - if (nativeKeys) return nativeKeys(obj); - var keys = []; - for (var key in obj) if (has(obj, key)) keys.push(key); - // Ahem, IE < 9. - if (hasEnumBug) collectNonEnumProps(obj, keys); - return keys; - }; - - // Retrieve all the property names of an object. - _.allKeys = function(obj) { - if (!_.isObject(obj)) return []; - var keys = []; - for (var key in obj) keys.push(key); - // Ahem, IE < 9. - if (hasEnumBug) collectNonEnumProps(obj, keys); - return keys; - }; - - // Retrieve the values of an object's properties. - _.values = function(obj) { - var keys = _.keys(obj); - var length = keys.length; - var values = Array(length); - for (var i = 0; i < length; i++) { - values[i] = obj[keys[i]]; - } - return values; - }; - - // Returns the results of applying the iteratee to each element of the object. - // In contrast to _.map it returns an object. - _.mapObject = function(obj, iteratee, context) { - iteratee = cb(iteratee, context); - var keys = _.keys(obj), - length = keys.length, - results = {}; - for (var index = 0; index < length; index++) { - var currentKey = keys[index]; - results[currentKey] = iteratee(obj[currentKey], currentKey, obj); - } - return results; - }; - - // Convert an object into a list of `[key, value]` pairs. - // The opposite of _.object. - _.pairs = function(obj) { - var keys = _.keys(obj); - var length = keys.length; - var pairs = Array(length); - for (var i = 0; i < length; i++) { - pairs[i] = [keys[i], obj[keys[i]]]; - } - return pairs; - }; - - // Invert the keys and values of an object. The values must be serializable. - _.invert = function(obj) { - var result = {}; - var keys = _.keys(obj); - for (var i = 0, length = keys.length; i < length; i++) { - result[obj[keys[i]]] = keys[i]; - } - return result; - }; - - // Return a sorted list of the function names available on the object. - // Aliased as `methods`. - _.functions = _.methods = function(obj) { - var names = []; - for (var key in obj) { - if (_.isFunction(obj[key])) names.push(key); - } - return names.sort(); - }; - - // An internal function for creating assigner functions. - var createAssigner = function(keysFunc, defaults) { - return function(obj) { - var length = arguments.length; - if (defaults) obj = Object(obj); - if (length < 2 || obj == null) return obj; - for (var index = 1; index < length; index++) { - var source = arguments[index], - keys = keysFunc(source), - l = keys.length; - for (var i = 0; i < l; i++) { - var key = keys[i]; - if (!defaults || obj[key] === void 0) obj[key] = source[key]; - } - } - return obj; - }; - }; - - // Extend a given object with all the properties in passed-in object(s). - _.extend = createAssigner(_.allKeys); - - // Assigns a given object with all the own properties in the passed-in object(s). - // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) - _.extendOwn = _.assign = createAssigner(_.keys); - - // Returns the first key on an object that passes a predicate test. - _.findKey = function(obj, predicate, context) { - predicate = cb(predicate, context); - var keys = _.keys(obj), key; - for (var i = 0, length = keys.length; i < length; i++) { - key = keys[i]; - if (predicate(obj[key], key, obj)) return key; - } - }; - - // Internal pick helper function to determine if `obj` has key `key`. - var keyInObj = function(value, key, obj) { - return key in obj; - }; - - // Return a copy of the object only containing the whitelisted properties. - _.pick = restArguments(function(obj, keys) { - var result = {}, iteratee = keys[0]; - if (obj == null) return result; - if (_.isFunction(iteratee)) { - if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); - keys = _.allKeys(obj); - } else { - iteratee = keyInObj; - keys = flatten(keys, false, false); - obj = Object(obj); - } - for (var i = 0, length = keys.length; i < length; i++) { - var key = keys[i]; - var value = obj[key]; - if (iteratee(value, key, obj)) result[key] = value; - } - return result; - }); - - // Return a copy of the object without the blacklisted properties. - _.omit = restArguments(function(obj, keys) { - var iteratee = keys[0], context; - if (_.isFunction(iteratee)) { - iteratee = _.negate(iteratee); - if (keys.length > 1) context = keys[1]; - } else { - keys = _.map(flatten(keys, false, false), String); - iteratee = function(value, key) { - return !_.contains(keys, key); - }; - } - return _.pick(obj, iteratee, context); - }); - - // Fill in a given object with default properties. - _.defaults = createAssigner(_.allKeys, true); - - // Creates an object that inherits from the given prototype object. - // If additional properties are provided then they will be added to the - // created object. - _.create = function(prototype, props) { - var result = baseCreate(prototype); - if (props) _.extendOwn(result, props); - return result; - }; - - // Create a (shallow-cloned) duplicate of an object. - _.clone = function(obj) { - if (!_.isObject(obj)) return obj; - return _.isArray(obj) ? obj.slice() : _.extend({}, obj); - }; - - // Invokes interceptor with the obj, and then returns obj. - // The primary purpose of this method is to "tap into" a method chain, in - // order to perform operations on intermediate results within the chain. - _.tap = function(obj, interceptor) { - interceptor(obj); - return obj; - }; - - // Returns whether an object has a given set of `key:value` pairs. - _.isMatch = function(object, attrs) { - var keys = _.keys(attrs), length = keys.length; - if (object == null) return !length; - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = keys[i]; - if (attrs[key] !== obj[key] || !(key in obj)) return false; - } - return true; - }; - - - // Internal recursive comparison function for `isEqual`. - var eq, deepEq; - eq = function(a, b, aStack, bStack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b; - // `null` or `undefined` only equal to itself (strict comparison). - if (a == null || b == null) return false; - // `NaN`s are equivalent, but non-reflexive. - if (a !== a) return b !== b; - // Exhaust primitive checks - var type = typeof a; - if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; - return deepEq(a, b, aStack, bStack); - }; - - // Internal recursive comparison function for `isEqual`. - deepEq = function(a, b, aStack, bStack) { - // Unwrap any wrapped objects. - if (a instanceof _) a = a._wrapped; - if (b instanceof _) b = b._wrapped; - // Compare `[[Class]]` names. - var className = toString.call(a); - if (className !== toString.call(b)) return false; - switch (className) { - // Strings, numbers, regular expressions, dates, and booleans are compared by value. - case '[object RegExp]': - // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return '' + a === '' + b; - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. - // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b; - // An `egal` comparison is performed for other numeric values. - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a === +b; - case '[object Symbol]': - return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b); - } - - var areArrays = className === '[object Array]'; - if (!areArrays) { - if (typeof a != 'object' || typeof b != 'object') return false; - - // Objects with different constructors are not equivalent, but `Object`s or `Array`s - // from different frames are. - var aCtor = a.constructor, bCtor = b.constructor; - if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && - _.isFunction(bCtor) && bCtor instanceof bCtor) - && ('constructor' in a && 'constructor' in b)) { - return false; - } - } - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - - // Initializing stack of traversed objects. - // It's done here since we only need them for objects and arrays comparison. - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] === a) return bStack[length] === b; - } - - // Add the first object to the stack of traversed objects. - aStack.push(a); - bStack.push(b); - - // Recursively compare objects and arrays. - if (areArrays) { - // Compare array lengths to determine if a deep comparison is necessary. - length = a.length; - if (length !== b.length) return false; - // Deep compare the contents, ignoring non-numeric properties. - while (length--) { - if (!eq(a[length], b[length], aStack, bStack)) return false; - } - } else { - // Deep compare objects. - var keys = _.keys(a), key; - length = keys.length; - // Ensure that both objects contain the same number of properties before comparing deep equality. - if (_.keys(b).length !== length) return false; - while (length--) { - // Deep compare each member - key = keys[length]; - if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; - } - } - // Remove the first object from the stack of traversed objects. - aStack.pop(); - bStack.pop(); - return true; - }; - - // Perform a deep comparison to check if two objects are equal. - _.isEqual = function(a, b) { - return eq(a, b); - }; - - // Is a given array, string, or object empty? - // An "empty" object has no enumerable own-properties. - _.isEmpty = function(obj) { - if (obj == null) return true; - if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; - return _.keys(obj).length === 0; - }; - - // Is a given value a DOM element? - _.isElement = function(obj) { - return !!(obj && obj.nodeType === 1); - }; - - // Is a given value an array? - // Delegates to ECMA5's native Array.isArray - _.isArray = nativeIsArray || function(obj) { - return toString.call(obj) === '[object Array]'; - }; - - // Is a given variable an object? - _.isObject = function(obj) { - var type = typeof obj; - return type === 'function' || type === 'object' && !!obj; - }; - - // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError, isMap, isWeakMap, isSet, isWeakSet. - _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol', 'Map', 'WeakMap', 'Set', 'WeakSet'], function(name) { - _['is' + name] = function(obj) { - return toString.call(obj) === '[object ' + name + ']'; - }; - }); - - // Define a fallback version of the method in browsers (ahem, IE < 9), where - // there isn't any inspectable "Arguments" type. - if (!_.isArguments(arguments)) { - _.isArguments = function(obj) { - return has(obj, 'callee'); - }; - } - - // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, - // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). - var nodelist = root.document && root.document.childNodes; - if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { - _.isFunction = function(obj) { - return typeof obj == 'function' || false; - }; - } - - // Is a given object a finite number? - _.isFinite = function(obj) { - return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj)); - }; - - // Is the given value `NaN`? - _.isNaN = function(obj) { - return _.isNumber(obj) && isNaN(obj); - }; - - // Is a given value a boolean? - _.isBoolean = function(obj) { - return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; - }; - - // Is a given value equal to null? - _.isNull = function(obj) { - return obj === null; - }; - - // Is a given variable undefined? - _.isUndefined = function(obj) { - return obj === void 0; - }; - - // Shortcut function for checking if an object has a given property directly - // on itself (in other words, not on a prototype). - _.has = function(obj, path) { - if (!_.isArray(path)) { - return has(obj, path); - } - var length = path.length; - for (var i = 0; i < length; i++) { - var key = path[i]; - if (obj == null || !hasOwnProperty.call(obj, key)) { - return false; - } - obj = obj[key]; - } - return !!length; - }; - - // Utility Functions - // ----------------- - - // Run Underscore.js in *noConflict* mode, returning the `_` variable to its - // previous owner. Returns a reference to the Underscore object. - _.noConflict = function() { - root._ = previousUnderscore; - return this; - }; - - // Keep the identity function around for default iteratees. - _.identity = function(value) { - return value; - }; - - // Predicate-generating functions. Often useful outside of Underscore. - _.constant = function(value) { - return function() { - return value; - }; - }; - - _.noop = function(){}; - - // Creates a function that, when passed an object, will traverse that object’s - // properties down the given `path`, specified as an array of keys or indexes. - _.property = function(path) { - if (!_.isArray(path)) { - return shallowProperty(path); - } - return function(obj) { - return deepGet(obj, path); - }; - }; - - // Generates a function for a given object that returns a given property. - _.propertyOf = function(obj) { - if (obj == null) { - return function(){}; - } - return function(path) { - return !_.isArray(path) ? obj[path] : deepGet(obj, path); - }; - }; - - // Returns a predicate for checking whether an object has a given set of - // `key:value` pairs. - _.matcher = _.matches = function(attrs) { - attrs = _.extendOwn({}, attrs); - return function(obj) { - return _.isMatch(obj, attrs); - }; - }; - - // Run a function **n** times. - _.times = function(n, iteratee, context) { - var accum = Array(Math.max(0, n)); - iteratee = optimizeCb(iteratee, context, 1); - for (var i = 0; i < n; i++) accum[i] = iteratee(i); - return accum; - }; - - // Return a random integer between min and max (inclusive). - _.random = function(min, max) { - if (max == null) { - max = min; - min = 0; - } - return min + Math.floor(Math.random() * (max - min + 1)); - }; - - // A (possibly faster) way to get the current timestamp as an integer. - _.now = Date.now || function() { - return new Date().getTime(); - }; - - // List of HTML entities for escaping. - var escapeMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '`': '`' - }; - var unescapeMap = _.invert(escapeMap); - - // Functions for escaping and unescaping strings to/from HTML interpolation. - var createEscaper = function(map) { - var escaper = function(match) { - return map[match]; - }; - // Regexes for identifying a key that needs to be escaped. - var source = '(?:' + _.keys(map).join('|') + ')'; - var testRegexp = RegExp(source); - var replaceRegexp = RegExp(source, 'g'); - return function(string) { - string = string == null ? '' : '' + string; - return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; - }; - }; - _.escape = createEscaper(escapeMap); - _.unescape = createEscaper(unescapeMap); - - // Traverses the children of `obj` along `path`. If a child is a function, it - // is invoked with its parent as context. Returns the value of the final - // child, or `fallback` if any child is undefined. - _.result = function(obj, path, fallback) { - if (!_.isArray(path)) path = [path]; - var length = path.length; - if (!length) { - return _.isFunction(fallback) ? fallback.call(obj) : fallback; - } - for (var i = 0; i < length; i++) { - var prop = obj == null ? void 0 : obj[path[i]]; - if (prop === void 0) { - prop = fallback; - i = length; // Ensure we don't continue iterating. - } - obj = _.isFunction(prop) ? prop.call(obj) : prop; - } - return obj; - }; - - // Generate a unique integer id (unique within the entire client session). - // Useful for temporary DOM ids. - var idCounter = 0; - _.uniqueId = function(prefix) { - var id = ++idCounter + ''; - return prefix ? prefix + id : id; - }; - - // By default, Underscore uses ERB-style template delimiters, change the - // following template settings to use alternative delimiters. - _.templateSettings = { - evaluate: /<%([\s\S]+?)%>/g, - interpolate: /<%=([\s\S]+?)%>/g, - escape: /<%-([\s\S]+?)%>/g - }; - - // When customizing `templateSettings`, if you don't want to define an - // interpolation, evaluation or escaping regex, we need one that is - // guaranteed not to match. - var noMatch = /(.)^/; - - // Certain characters need to be escaped so that they can be put into a - // string literal. - var escapes = { - "'": "'", - '\\': '\\', - '\r': 'r', - '\n': 'n', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; - - var escapeChar = function(match) { - return '\\' + escapes[match]; - }; - - // JavaScript micro-templating, similar to John Resig's implementation. - // Underscore templating handles arbitrary delimiters, preserves whitespace, - // and correctly escapes quotes within interpolated code. - // NB: `oldSettings` only exists for backwards compatibility. - _.template = function(text, settings, oldSettings) { - if (!settings && oldSettings) settings = oldSettings; - settings = _.defaults({}, settings, _.templateSettings); - - // Combine delimiters into one regular expression via alternation. - var matcher = RegExp([ - (settings.escape || noMatch).source, - (settings.interpolate || noMatch).source, - (settings.evaluate || noMatch).source - ].join('|') + '|$', 'g'); - - // Compile the template source, escaping string literals appropriately. - var index = 0; - var source = "__p+='"; - text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { - source += text.slice(index, offset).replace(escapeRegExp, escapeChar); - index = offset + match.length; - - if (escape) { - source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; - } else if (interpolate) { - source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; - } else if (evaluate) { - source += "';\n" + evaluate + "\n__p+='"; - } - - // Adobe VMs need the match returned to produce the correct offset. - return match; - }); - source += "';\n"; - - // If a variable is not specified, place data values in local scope. - if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; - - source = "var __t,__p='',__j=Array.prototype.join," + - "print=function(){__p+=__j.call(arguments,'');};\n" + - source + 'return __p;\n'; - - var render; - try { - render = new Function(settings.variable || 'obj', '_', source); - } catch (e) { - e.source = source; - throw e; - } - - var template = function(data) { - return render.call(this, data, _); - }; - - // Provide the compiled source as a convenience for precompilation. - var argument = settings.variable || 'obj'; - template.source = 'function(' + argument + '){\n' + source + '}'; - - return template; - }; - - // Add a "chain" function. Start chaining a wrapped Underscore object. - _.chain = function(obj) { - var instance = _(obj); - instance._chain = true; - return instance; - }; - - // OOP - // --------------- - // If Underscore is called as a function, it returns a wrapped object that - // can be used OO-style. This wrapper holds altered versions of all the - // underscore functions. Wrapped objects may be chained. - - // Helper function to continue chaining intermediate results. - var chainResult = function(instance, obj) { - return instance._chain ? _(obj).chain() : obj; - }; - - // Add your own custom functions to the Underscore object. - _.mixin = function(obj) { - _.each(_.functions(obj), function(name) { - var func = _[name] = obj[name]; - _.prototype[name] = function() { - var args = [this._wrapped]; - push.apply(args, arguments); - return chainResult(this, func.apply(_, args)); - }; - }); - return _; - }; - - // Add all of the Underscore functions to the wrapper object. - _.mixin(_); - - // Add all mutator Array functions to the wrapper. - _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { - var method = ArrayProto[name]; - _.prototype[name] = function() { - var obj = this._wrapped; - method.apply(obj, arguments); - if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; - return chainResult(this, obj); - }; - }); - - // Add all accessor Array functions to the wrapper. - _.each(['concat', 'join', 'slice'], function(name) { - var method = ArrayProto[name]; - _.prototype[name] = function() { - return chainResult(this, method.apply(this._wrapped, arguments)); - }; - }); - - // Extracts the result from a wrapped and chained object. - _.prototype.value = function() { - return this._wrapped; - }; - - // Provide unwrapping proxy for some methods used in engine operations - // such as arithmetic and JSON stringification. - _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; - - _.prototype.toString = function() { - return String(this._wrapped); - }; - - // AMD registration happens at the end for compatibility with AMD loaders - // that may not enforce next-turn semantics on modules. Even though general - // practice for AMD registration is to be anonymous, underscore registers - // as a named module because, like jQuery, it is a base library that is - // popular enough to be bundled in a third party lib, but not be part of - // an AMD load request. Those cases could generate an error when an - // anonymous define() is called outside of a loader request. - if (typeof define == 'function' && define.amd) { - define('underscore', [], function() { - return _; - }); - } -}()); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1766:[function(require,module,exports){ +},{}],1506:[function(require,module,exports){ 'use strict'; module.exports = uniqueBy; @@ -236049,1423 +164576,7 @@ function uniqueBy(arr, getValue) { return unique; } -},{}],1767:[function(require,module,exports){ -/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.URI = global.URI || {}))); -}(this, (function (exports) { 'use strict'; - -function merge() { - for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { - sets[_key] = arguments[_key]; - } - - if (sets.length > 1) { - sets[0] = sets[0].slice(0, -1); - var xl = sets.length - 1; - for (var x = 1; x < xl; ++x) { - sets[x] = sets[x].slice(1, -1); - } - sets[xl] = sets[xl].slice(1); - return sets.join(''); - } else { - return sets[0]; - } -} -function subexp(str) { - return "(?:" + str + ")"; -} -function typeOf(o) { - return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); -} -function toUpperCase(str) { - return str.toUpperCase(); -} -function toArray(obj) { - return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; -} -function assign(target, source) { - var obj = target; - if (source) { - for (var key in source) { - obj[key] = source[key]; - } - } - return obj; -} - -function buildExps(isIRI) { - var ALPHA$$ = "[A-Za-z]", - CR$ = "[\\x0D]", - DIGIT$$ = "[0-9]", - DQUOTE$$ = "[\\x22]", - HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), - //case-insensitive - LF$$ = "[\\x0A]", - SP$$ = "[\\x20]", - PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), - //expanded - GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", - SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", - RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), - UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", - //subset, excludes bidi control characters - IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", - //subset - UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), - SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), - USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), - DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), - DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), - //relaxed parsing rules - IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), - H16$ = subexp(HEXDIG$$ + "{1,4}"), - LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), - IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), - // 6( h16 ":" ) ls32 - IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), - // "::" 5( h16 ":" ) ls32 - IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), - //[ h16 ] "::" 4( h16 ":" ) ls32 - IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), - //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), - //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), - //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), - //[ *4( h16 ":" ) h16 ] "::" ls32 - IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), - //[ *5( h16 ":" ) h16 ] "::" h16 - IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), - //[ *6( h16 ":" ) h16 ] "::" - IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), - ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), - //RFC 6874 - IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), - //RFC 6874 - IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), - //RFC 6874, with relaxed parsing rules - IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), - IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), - //RFC 6874 - REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), - HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), - PORT$ = subexp(DIGIT$$ + "*"), - AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), - PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), - SEGMENT$ = subexp(PCHAR$ + "*"), - SEGMENT_NZ$ = subexp(PCHAR$ + "+"), - SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), - PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), - PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), - //simplified - PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), - //simplified - PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), - //simplified - PATH_EMPTY$ = "(?!" + PCHAR$ + ")", - PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), - FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), - HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), - RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), - ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), - GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", - SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; - return { - NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), - NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), - NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), - ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), - UNRESERVED: new RegExp(UNRESERVED$$, "g"), - OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), - PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), - IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), - IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules - }; -} -var URI_PROTOCOL = buildExps(false); - -var IRI_PROTOCOL = buildExps(true); - -var slicedToArray = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - - - - - - - - - - - - - -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - - return arr2; - } else { - return Array.from(arr); - } -}; - -/** Highest positive signed 32-bit float value */ - -var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - -/** Bootstring parameters */ -var base = 36; -var tMin = 1; -var tMax = 26; -var skew = 38; -var damp = 700; -var initialBias = 72; -var initialN = 128; // 0x80 -var delimiter = '-'; // '\x2D' - -/** Regular expressions */ -var regexPunycode = /^xn--/; -var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars -var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - -/** Error messages */ -var errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}; - -/** Convenience shortcuts */ -var baseMinusTMin = base - tMin; -var floor = Math.floor; -var stringFromCharCode = String.fromCharCode; - -/*--------------------------------------------------------------------------*/ - -/** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ -function error$1(type) { - throw new RangeError(errors[type]); -} - -/** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ -function map(array, fn) { - var result = []; - var length = array.length; - while (length--) { - result[length] = fn(array[length]); - } - return result; -} - -/** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ -function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; -} - -/** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ -function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - while (counter < length) { - var value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // It's an unmatched surrogate; only append this code unit, in case the - // next code unit is the high surrogate of a surrogate pair. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} - -/** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ -var ucs2encode = function ucs2encode(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); -}; - -/** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ -var basicToDigit = function basicToDigit(codePoint) { - if (codePoint - 0x30 < 0x0A) { - return codePoint - 0x16; - } - if (codePoint - 0x41 < 0x1A) { - return codePoint - 0x41; - } - if (codePoint - 0x61 < 0x1A) { - return codePoint - 0x61; - } - return base; -}; - -/** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ -var digitToBasic = function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); -}; - -/** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ -var adapt = function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); -}; - -/** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ -var decode = function decode(input) { - // Don't use UCS-2. - var output = []; - var inputLength = input.length; - var i = 0; - var n = initialN; - var bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - var basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (var j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error$1('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - var oldi = i; - for (var w = 1, k = base;; /* no condition */k += base) { - - if (index >= inputLength) { - error$1('invalid-input'); - } - - var digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1('overflow'); - } - - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - - if (digit < t) { - break; - } - - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1('overflow'); - } - - w *= baseMinusT; - } - - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error$1('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } - - return String.fromCodePoint.apply(String, output); -}; - -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -var encode = function encode(input) { - var output = []; - - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); - - // Cache the length. - var inputLength = input.length; - - // Initialize the state. - var n = initialN; - var delta = 0; - var bias = initialBias; - - // Handle the basic code points. - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _currentValue2 = _step.value; - - if (_currentValue2 < 0x80) { - output.push(stringFromCharCode(_currentValue2)); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var basicLength = output.length; - var handledCPCount = basicLength; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - var m = maxInt; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; - - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - var handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error$1('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _currentValue = _step3.value; - - if (_currentValue < n && ++delta > maxInt) { - error$1('overflow'); - } - if (_currentValue == n) { - // Represent delta as a generalized variable-length integer. - var q = delta; - for (var k = base;; /* no condition */k += base) { - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - var qMinusT = q - t; - var baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - ++delta; - ++n; - } - return output.join(''); -}; - -/** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ -var toUnicode = function toUnicode(input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); -}; - -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -var toASCII = function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; - -/*--------------------------------------------------------------------------*/ - -/** Define the public API */ -var punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.1.0', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode -}; - -/** - * URI.js - * - * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. - * @author Gary Court - * @see http://github.com/garycourt/uri-js - */ -/** - * Copyright 2011 Gary Court. All rights reserved. - * - * 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. - * - * THIS SOFTWARE IS PROVIDED BY GARY COURT ``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 GARY COURT OR - * CONTRIBUTORS 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of Gary Court. - */ -var SCHEMES = {}; -function pctEncChar(chr) { - var c = chr.charCodeAt(0); - var e = void 0; - if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - return e; -} -function pctDecChars(str) { - var newStr = ""; - var i = 0; - var il = str.length; - while (i < il) { - var c = parseInt(str.substr(i + 1, 2), 16); - if (c < 128) { - newStr += String.fromCharCode(c); - i += 3; - } else if (c >= 194 && c < 224) { - if (il - i >= 6) { - var c2 = parseInt(str.substr(i + 4, 2), 16); - newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); - } else { - newStr += str.substr(i, 6); - } - i += 6; - } else if (c >= 224) { - if (il - i >= 9) { - var _c = parseInt(str.substr(i + 4, 2), 16); - var c3 = parseInt(str.substr(i + 7, 2), 16); - newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); - } else { - newStr += str.substr(i, 9); - } - i += 9; - } else { - newStr += str.substr(i, 3); - i += 3; - } - } - return newStr; -} -function _normalizeComponentEncoding(components, protocol) { - function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(protocol.UNRESERVED) ? str : decStr; - } - if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); - if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - return components; -} - -function _stripLeadingZeros(str) { - return str.replace(/^0*(.*)/, "$1") || "0"; -} -function _normalizeIPv4(host, protocol) { - var matches = host.match(protocol.IPV4ADDRESS) || []; - - var _matches = slicedToArray(matches, 2), - address = _matches[1]; - - if (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } -} -function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; - - var _matches2 = slicedToArray(matches, 3), - address = _matches2[1], - zone = _matches2[2]; - - if (address) { - var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), - _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), - last = _address$toLowerCase$2[0], - first = _address$toLowerCase$2[1]; - - var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; - var lastFields = last.split(":").map(_stripLeadingZeros); - var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); - var fieldCount = isLastFieldIPv4Address ? 7 : 8; - var lastFieldsStart = lastFields.length - fieldCount; - var fields = Array(fieldCount); - for (var x = 0; x < fieldCount; ++x) { - fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; - } - if (isLastFieldIPv4Address) { - fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); - } - var allZeroFields = fields.reduce(function (acc, field, index) { - if (!field || field === "0") { - var lastLongest = acc[acc.length - 1]; - if (lastLongest && lastLongest.index + lastLongest.length === index) { - lastLongest.length++; - } else { - acc.push({ index: index, length: 1 }); - } - } - return acc; - }, []); - var longestZeroFields = allZeroFields.sort(function (a, b) { - return b.length - a.length; - })[0]; - var newHost = void 0; - if (longestZeroFields && longestZeroFields.length > 1) { - var newFirst = fields.slice(0, longestZeroFields.index); - var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); - newHost = newFirst.join(":") + "::" + newLast.join(":"); - } else { - newHost = fields.join(":"); - } - if (zone) { - newHost += "%" + zone; - } - return newHost; - } else { - return host; - } -} -var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; -var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; -function parse(uriString) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var components = {}; - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; - var matches = uriString.match(URI_PARSE); - if (matches) { - if (NO_MATCH_IS_UNDEFINED) { - //store each component - components.scheme = matches[1]; - components.userinfo = matches[3]; - components.host = matches[4]; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = matches[7]; - components.fragment = matches[8]; - //fix port number - if (isNaN(components.port)) { - components.port = matches[5]; - } - } else { - //IE FIX for improper RegExp matching - //store each component - components.scheme = matches[1] || undefined; - components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; - components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; - components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; - //fix port number - if (isNaN(components.port)) { - components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; - } - } - if (components.host) { - //normalize IP hosts - components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); - } - //determine reference type - if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { - components.reference = "same-document"; - } else if (components.scheme === undefined) { - components.reference = "relative"; - } else if (components.fragment === undefined) { - components.reference = "absolute"; - } else { - components.reference = "uri"; - } - //check for reference errors - if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { - components.error = components.error || "URI is not a " + options.reference + " reference."; - } - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //check if scheme can't handle IRIs - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - //if host component is a domain name - if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { - //convert Unicode IDN -> ASCII IDN - try { - components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; - } - } - //convert IRI -> URI - _normalizeComponentEncoding(components, URI_PROTOCOL); - } else { - //normalize encodings - _normalizeComponentEncoding(components, protocol); - } - //perform scheme specific parsing - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(components, options); - } - } else { - components.error = components.error || "URI can not be parsed."; - } - return components; -} - -function _recomposeAuthority(components, options) { - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - if (components.userinfo !== undefined) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== undefined) { - //normalize IP hosts, add brackets and escape zone separator for IPv6 - uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { - return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; - })); - } - if (typeof components.port === "number") { - uriTokens.push(":"); - uriTokens.push(components.port.toString(10)); - } - return uriTokens.length ? uriTokens.join("") : undefined; -} - -var RDS1 = /^\.\.?\//; -var RDS2 = /^\/\.(\/|$)/; -var RDS3 = /^\/\.\.(\/|$)/; -var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; -function removeDotSegments(input) { - var output = []; - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, ""); - } else if (input.match(RDS2)) { - input = input.replace(RDS2, "/"); - } else if (input.match(RDS3)) { - input = input.replace(RDS3, "/"); - output.pop(); - } else if (input === "." || input === "..") { - input = ""; - } else { - var im = input.match(RDS5); - if (im) { - var s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); -} - -function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //perform scheme specific serialization - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); - if (components.host) { - //if host component is an IPv6 address - if (protocol.IPV6ADDRESS.test(components.host)) {} - //TODO: normalize IPv6 address as per RFC 5952 - - //if host component is a domain name - else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { - //convert IDN via punycode - try { - components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - } - } - //normalize encoding - _normalizeComponentEncoding(components, protocol); - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme); - uriTokens.push(":"); - } - var authority = _recomposeAuthority(components, options); - if (authority !== undefined) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (components.path && components.path.charAt(0) !== "/") { - uriTokens.push("/"); - } - } - if (components.path !== undefined) { - var s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === undefined) { - s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" - } - uriTokens.push(s); - } - if (components.query !== undefined) { - uriTokens.push("?"); - uriTokens.push(components.query); - } - if (components.fragment !== undefined) { - uriTokens.push("#"); - uriTokens.push(components.fragment); - } - return uriTokens.join(""); //merge tokens into a string -} - -function resolveComponents(base, relative) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var skipNormalization = arguments[3]; - - var target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); //normalize base components - relative = parse(serialize(relative, options), options); //normalize relative components - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== undefined) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path.charAt(0) === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = "/" + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - //target.authority = base.authority; - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; -} - -function resolve(baseURI, relativeURI, options) { - var schemelessOptions = assign({ scheme: 'null' }, options); - return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); -} - -function normalize(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse(uri, options), options); - } else if (typeOf(uri) === "object") { - uri = parse(serialize(uri, options), options); - } - return uri; -} - -function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = serialize(parse(uriA, options), options); - } else if (typeOf(uriA) === "object") { - uriA = serialize(uriA, options); - } - if (typeof uriB === "string") { - uriB = serialize(parse(uriB, options), options); - } else if (typeOf(uriB) === "object") { - uriB = serialize(uriB, options); - } - return uriA === uriB; -} - -function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); -} - -function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); -} - -var handler = { - scheme: "http", - domainHost: true, - parse: function parse(components, options) { - //report missing host - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - }, - serialize: function serialize(components, options) { - //normalize the default port - if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") { - components.port = undefined; - } - //normalize the empty path - if (!components.path) { - components.path = "/"; - } - //NOTE: We do not parse query strings for HTTP URIs - //as WWW Form Url Encoded query strings are part of the HTML4+ spec, - //and not the HTTP spec. - return components; - } -}; - -var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize -}; - -var O = {}; -var isIRI = true; -//RFC 3986 -var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; -var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive -var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded -//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = -//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) -//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext -//const VCHAR$$ = "[\\x21-\\x7E]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext -//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); -//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); -//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); -var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; -var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; -var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); -var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; -var UNRESERVED = new RegExp(UNRESERVED$$, "g"); -var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); -var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); -var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); -var NOT_HFVALUE = NOT_HFNAME; -function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(UNRESERVED) ? str : decStr; -} -var handler$2 = { - scheme: "mailto", - parse: function parse$$1(components, options) { - var mailtoComponents = components; - var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; - mailtoComponents.path = undefined; - if (mailtoComponents.query) { - var unknownHeaders = false; - var headers = {}; - var hfields = mailtoComponents.query.split("&"); - for (var x = 0, xl = hfields.length; x < xl; ++x) { - var hfield = hfields[x].split("="); - switch (hfield[0]) { - case "to": - var toAddrs = hfield[1].split(","); - for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { - to.push(toAddrs[_x]); - } - break; - case "subject": - mailtoComponents.subject = unescapeComponent(hfield[1], options); - break; - case "body": - mailtoComponents.body = unescapeComponent(hfield[1], options); - break; - default: - unknownHeaders = true; - headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); - break; - } - } - if (unknownHeaders) mailtoComponents.headers = headers; - } - mailtoComponents.query = undefined; - for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { - var addr = to[_x2].split("@"); - addr[0] = unescapeComponent(addr[0]); - if (!options.unicodeSupport) { - //convert Unicode IDN -> ASCII IDN - try { - addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); - } catch (e) { - mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; - } - } else { - addr[1] = unescapeComponent(addr[1], options).toLowerCase(); - } - to[_x2] = addr.join("@"); - } - return mailtoComponents; - }, - serialize: function serialize$$1(mailtoComponents, options) { - var components = mailtoComponents; - var to = toArray(mailtoComponents.to); - if (to) { - for (var x = 0, xl = to.length; x < xl; ++x) { - var toAddr = String(to[x]); - var atIdx = toAddr.lastIndexOf("@"); - var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); - var domain = toAddr.slice(atIdx + 1); - //convert IDN via punycode - try { - domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); - } catch (e) { - components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - to[x] = localPart + "@" + domain; - } - components.path = to.join(","); - } - var headers = mailtoComponents.headers = mailtoComponents.headers || {}; - if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; - if (mailtoComponents.body) headers["body"] = mailtoComponents.body; - var fields = []; - for (var name in headers) { - if (headers[name] !== O[name]) { - fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); - } - } - if (fields.length) { - components.query = fields.join("&"); - } - return components; - } -}; - -var URN_PARSE = /^([^\:]+)\:(.*)/; -//RFC 2141 -var handler$3 = { - scheme: "urn", - parse: function parse$$1(components, options) { - var matches = components.path && components.path.match(URN_PARSE); - var urnComponents = components; - if (matches) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = matches[1].toLowerCase(); - var nss = matches[2]; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - urnComponents.nid = nid; - urnComponents.nss = nss; - urnComponents.path = undefined; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - }, - serialize: function serialize$$1(urnComponents, options) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = urnComponents.nid; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - var uriComponents = urnComponents; - var nss = urnComponents.nss; - uriComponents.path = (nid || options.nid) + ":" + nss; - return uriComponents; - } -}; - -var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; -//RFC 4122 -var handler$4 = { - scheme: "urn:uuid", - parse: function parse(urnComponents, options) { - var uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = undefined; - if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - }, - serialize: function serialize(uuidComponents, options) { - var urnComponents = uuidComponents; - //normalize UUID - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } -}; - -SCHEMES[handler.scheme] = handler; -SCHEMES[handler$1.scheme] = handler$1; -SCHEMES[handler$2.scheme] = handler$2; -SCHEMES[handler$3.scheme] = handler$3; -SCHEMES[handler$4.scheme] = handler$4; - -exports.SCHEMES = SCHEMES; -exports.pctEncChar = pctEncChar; -exports.pctDecChars = pctDecChars; -exports.parse = parse; -exports.removeDotSegments = removeDotSegments; -exports.serialize = serialize; -exports.resolveComponents = resolveComponents; -exports.resolve = resolve; -exports.normalize = normalize; -exports.equal = equal; -exports.escapeComponent = escapeComponent; -exports.unescapeComponent = unescapeComponent; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); - - -},{}],1768:[function(require,module,exports){ -module.exports = urlSetQuery -function urlSetQuery (url, query) { - if (query) { - // remove optional leading symbols - query = query.trim().replace(/^(\?|#|&)/, '') - - // don't append empty query - query = query ? ('?' + query) : query - - var parts = url.split(/[\?\#]/) - var start = parts[0] - if (query && /\:\/\/[^\/]*$/.test(start)) { - // e.g. http://foo.com -> http://foo.com/ - start = start + '/' - } - var match = url.match(/(\#.*)$/) - url = start + query - if (match) { // add hash back in - url = url + match[0] - } - } - return url -} - -},{}],1769:[function(require,module,exports){ +},{}],1507:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -238199,7 +165310,7 @@ Url.prototype.parseHost = function() { if (host) this.hostname = host; }; -},{"./util":1770,"punycode":1538,"querystring":1547}],1770:[function(require,module,exports){ +},{"./util":1508,"punycode":174,"querystring":1361}],1508:[function(require,module,exports){ 'use strict'; module.exports = { @@ -238217,7 +165328,7 @@ module.exports = { } }; -},{}],1771:[function(require,module,exports){ +},{}],1509:[function(require,module,exports){ 'use strict'; function isHighSurrogate(codePoint) { @@ -238266,211 +165377,7 @@ module.exports = function getByteLength(string) { return byteLength; }; -},{}],1772:[function(require,module,exports){ -/*! https://mths.be/utf8js v3.0.0 by @mathias */ -;(function(root) { - - var stringFromCharCode = String.fromCharCode; - - // Taken from https://mths.be/punycode - function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - var value; - var extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - // Taken from https://mths.be/punycode - function ucs2encode(array) { - var length = array.length; - var index = -1; - var value; - var output = ''; - while (++index < length) { - value = array[index]; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - } - return output; - } - - function checkScalarValue(codePoint) { - if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { - throw Error( - 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + - ' is not a scalar value' - ); - } - } - /*--------------------------------------------------------------------------*/ - - function createByte(codePoint, shift) { - return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); - } - - function encodeCodePoint(codePoint) { - if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence - return stringFromCharCode(codePoint); - } - var symbol = ''; - if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence - symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); - } - else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence - checkScalarValue(codePoint); - symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); - symbol += createByte(codePoint, 6); - } - else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence - symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); - symbol += createByte(codePoint, 12); - symbol += createByte(codePoint, 6); - } - symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); - return symbol; - } - - function utf8encode(string) { - var codePoints = ucs2decode(string); - var length = codePoints.length; - var index = -1; - var codePoint; - var byteString = ''; - while (++index < length) { - codePoint = codePoints[index]; - byteString += encodeCodePoint(codePoint); - } - return byteString; - } - - /*--------------------------------------------------------------------------*/ - - function readContinuationByte() { - if (byteIndex >= byteCount) { - throw Error('Invalid byte index'); - } - - var continuationByte = byteArray[byteIndex] & 0xFF; - byteIndex++; - - if ((continuationByte & 0xC0) == 0x80) { - return continuationByte & 0x3F; - } - - // If we end up here, it’s not a continuation byte - throw Error('Invalid continuation byte'); - } - - function decodeSymbol() { - var byte1; - var byte2; - var byte3; - var byte4; - var codePoint; - - if (byteIndex > byteCount) { - throw Error('Invalid byte index'); - } - - if (byteIndex == byteCount) { - return false; - } - - // Read first byte - byte1 = byteArray[byteIndex] & 0xFF; - byteIndex++; - - // 1-byte sequence (no continuation bytes) - if ((byte1 & 0x80) == 0) { - return byte1; - } - - // 2-byte sequence - if ((byte1 & 0xE0) == 0xC0) { - byte2 = readContinuationByte(); - codePoint = ((byte1 & 0x1F) << 6) | byte2; - if (codePoint >= 0x80) { - return codePoint; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 3-byte sequence (may include unpaired surrogates) - if ((byte1 & 0xF0) == 0xE0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; - if (codePoint >= 0x0800) { - checkScalarValue(codePoint); - return codePoint; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 4-byte sequence - if ((byte1 & 0xF8) == 0xF0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - byte4 = readContinuationByte(); - codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | - (byte3 << 0x06) | byte4; - if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { - return codePoint; - } - } - - throw Error('Invalid UTF-8 detected'); - } - - var byteArray; - var byteCount; - var byteIndex; - function utf8decode(byteString) { - byteArray = ucs2decode(byteString); - byteCount = byteArray.length; - byteIndex = 0; - var codePoints = []; - var tmp; - while ((tmp = decodeSymbol()) !== false) { - codePoints.push(tmp); - } - return ucs2encode(codePoints); - } - - /*--------------------------------------------------------------------------*/ - - root.version = '3.0.0'; - root.encode = utf8encode; - root.decode = utf8decode; - -}(typeof exports === 'undefined' ? this.utf8 = {} : exports)); - -},{}],1773:[function(require,module,exports){ +},{}],1510:[function(require,module,exports){ (function (global){ /** @@ -238541,13 +165448,11 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1774:[function(require,module,exports){ -arguments[4][79][0].apply(exports,arguments) -},{"dup":79}],1775:[function(require,module,exports){ -arguments[4][80][0].apply(exports,arguments) -},{"dup":80}],1776:[function(require,module,exports){ -arguments[4][81][0].apply(exports,arguments) -},{"./support/isBuffer":1775,"_process":1438,"dup":81,"inherits":1774}],1777:[function(require,module,exports){ +},{}],1511:[function(require,module,exports){ +arguments[4][28][0].apply(exports,arguments) +},{"dup":28}],1512:[function(require,module,exports){ +arguments[4][29][0].apply(exports,arguments) +},{"./support/isBuffer":1511,"_process":1258,"dup":29,"inherits":317}],1513:[function(require,module,exports){ var v1 = require('./v1'); var v4 = require('./v4'); @@ -238557,7 +165462,7 @@ uuid.v4 = v4; module.exports = uuid; -},{"./v1":1780,"./v4":1781}],1778:[function(require,module,exports){ +},{"./v1":1516,"./v4":1517}],1514:[function(require,module,exports){ /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX @@ -238571,7 +165476,7 @@ function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([bth[buf[i++]], bth[buf[i++]], + return ([bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', @@ -238583,7 +165488,7 @@ function bytesToUuid(buf, offset) { module.exports = bytesToUuid; -},{}],1779:[function(require,module,exports){ +},{}],1515:[function(require,module,exports){ // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via @@ -238619,7 +165524,7 @@ if (getRandomValues) { }; } -},{}],1780:[function(require,module,exports){ +},{}],1516:[function(require,module,exports){ var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); @@ -238730,7 +165635,7 @@ function v1(options, buf, offset) { module.exports = v1; -},{"./lib/bytesToUuid":1778,"./lib/rng":1779}],1781:[function(require,module,exports){ +},{"./lib/bytesToUuid":1514,"./lib/rng":1515}],1517:[function(require,module,exports){ var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); @@ -238761,7 +165666,7 @@ function v4(options, buf, offset) { module.exports = v4; -},{"./lib/bytesToUuid":1778,"./lib/rng":1779}],1782:[function(require,module,exports){ +},{"./lib/bytesToUuid":1514,"./lib/rng":1515}],1518:[function(require,module,exports){ (function (Buffer){ 'use strict' @@ -238784,7 +165689,7 @@ module.exports = (buf) => { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":766,"varint":1785}],1783:[function(require,module,exports){ +},{"../../is-buffer/index.js":608,"varint":1521}],1519:[function(require,module,exports){ module.exports = read var MSB = 0x80 @@ -238815,7 +165720,7 @@ function read(buf, offset) { return res } -},{}],1784:[function(require,module,exports){ +},{}],1520:[function(require,module,exports){ module.exports = encode var MSB = 0x80 @@ -238837,20 +165742,20 @@ function encode(num, out, offset) { num >>>= 7 } out[offset] = num | 0 - + encode.bytes = offset - oldOffset + 1 - + return out } -},{}],1785:[function(require,module,exports){ +},{}],1521:[function(require,module,exports){ module.exports = { encode: require('./encode.js') , decode: require('./decode.js') , encodingLength: require('./length.js') } -},{"./decode.js":1783,"./encode.js":1784,"./length.js":1786}],1786:[function(require,module,exports){ +},{"./decode.js":1519,"./encode.js":1520,"./length.js":1522}],1522:[function(require,module,exports){ var N1 = Math.pow(2, 7) var N2 = Math.pow(2, 14) @@ -238877,460 +165782,7 @@ module.exports = function (value) { ) } -},{}],1787:[function(require,module,exports){ -/* - * verror.js: richer JavaScript errors - */ - -var mod_assertplus = require('assert-plus'); -var mod_util = require('util'); - -var mod_extsprintf = require('extsprintf'); -var mod_isError = require('core-util-is').isError; -var sprintf = mod_extsprintf.sprintf; - -/* - * Public interface - */ - -/* So you can 'var VError = require('verror')' */ -module.exports = VError; -/* For compatibility */ -VError.VError = VError; -/* Other exported classes */ -VError.SError = SError; -VError.WError = WError; -VError.MultiError = MultiError; - -/* - * Common function used to parse constructor arguments for VError, WError, and - * SError. Named arguments to this function: - * - * strict force strict interpretation of sprintf arguments, even - * if the options in "argv" don't say so - * - * argv error's constructor arguments, which are to be - * interpreted as described in README.md. For quick - * reference, "argv" has one of the following forms: - * - * [ sprintf_args... ] (argv[0] is a string) - * [ cause, sprintf_args... ] (argv[0] is an Error) - * [ options, sprintf_args... ] (argv[0] is an object) - * - * This function normalizes these forms, producing an object with the following - * properties: - * - * options equivalent to "options" in third form. This will never - * be a direct reference to what the caller passed in - * (i.e., it may be a shallow copy), so it can be freely - * modified. - * - * shortmessage result of sprintf(sprintf_args), taking options.strict - * into account as described in README.md. - */ -function parseConstructorArguments(args) -{ - var argv, options, sprintf_args, shortmessage, k; - - mod_assertplus.object(args, 'args'); - mod_assertplus.bool(args.strict, 'args.strict'); - mod_assertplus.array(args.argv, 'args.argv'); - argv = args.argv; - - /* - * First, figure out which form of invocation we've been given. - */ - if (argv.length === 0) { - options = {}; - sprintf_args = []; - } else if (mod_isError(argv[0])) { - options = { 'cause': argv[0] }; - sprintf_args = argv.slice(1); - } else if (typeof (argv[0]) === 'object') { - options = {}; - for (k in argv[0]) { - options[k] = argv[0][k]; - } - sprintf_args = argv.slice(1); - } else { - mod_assertplus.string(argv[0], - 'first argument to VError, SError, or WError ' + - 'constructor must be a string, object, or Error'); - options = {}; - sprintf_args = argv; - } - - /* - * Now construct the error's message. - * - * extsprintf (which we invoke here with our caller's arguments in order - * to construct this Error's message) is strict in its interpretation of - * values to be processed by the "%s" specifier. The value passed to - * extsprintf must actually be a string or something convertible to a - * String using .toString(). Passing other values (notably "null" and - * "undefined") is considered a programmer error. The assumption is - * that if you actually want to print the string "null" or "undefined", - * then that's easy to do that when you're calling extsprintf; on the - * other hand, if you did NOT want that (i.e., there's actually a bug - * where the program assumes some variable is non-null and tries to - * print it, which might happen when constructing a packet or file in - * some specific format), then it's better to stop immediately than - * produce bogus output. - * - * However, sometimes the bug is only in the code calling VError, and a - * programmer might prefer to have the error message contain "null" or - * "undefined" rather than have the bug in the error path crash the - * program (making the first bug harder to identify). For that reason, - * by default VError converts "null" or "undefined" arguments to their - * string representations and passes those to extsprintf. Programmers - * desiring the strict behavior can use the SError class or pass the - * "strict" option to the VError constructor. - */ - mod_assertplus.object(options); - if (!options.strict && !args.strict) { - sprintf_args = sprintf_args.map(function (a) { - return (a === null ? 'null' : - a === undefined ? 'undefined' : a); - }); - } - - if (sprintf_args.length === 0) { - shortmessage = ''; - } else { - shortmessage = sprintf.apply(null, sprintf_args); - } - - return ({ - 'options': options, - 'shortmessage': shortmessage - }); -} - -/* - * See README.md for reference documentation. - */ -function VError() -{ - var args, obj, parsed, cause, ctor, message, k; - - args = Array.prototype.slice.call(arguments, 0); - - /* - * This is a regrettable pattern, but JavaScript's built-in Error class - * is defined to work this way, so we allow the constructor to be called - * without "new". - */ - if (!(this instanceof VError)) { - obj = Object.create(VError.prototype); - VError.apply(obj, arguments); - return (obj); - } - - /* - * For convenience and backwards compatibility, we support several - * different calling forms. Normalize them here. - */ - parsed = parseConstructorArguments({ - 'argv': args, - 'strict': false - }); - - /* - * If we've been given a name, apply it now. - */ - if (parsed.options.name) { - mod_assertplus.string(parsed.options.name, - 'error\'s "name" must be a string'); - this.name = parsed.options.name; - } - - /* - * For debugging, we keep track of the original short message (attached - * this Error particularly) separately from the complete message (which - * includes the messages of our cause chain). - */ - this.jse_shortmsg = parsed.shortmessage; - message = parsed.shortmessage; - - /* - * If we've been given a cause, record a reference to it and update our - * message appropriately. - */ - cause = parsed.options.cause; - if (cause) { - mod_assertplus.ok(mod_isError(cause), 'cause is not an Error'); - this.jse_cause = cause; - - if (!parsed.options.skipCauseMessage) { - message += ': ' + cause.message; - } - } - - /* - * If we've been given an object with properties, shallow-copy that - * here. We don't want to use a deep copy in case there are non-plain - * objects here, but we don't want to use the original object in case - * the caller modifies it later. - */ - this.jse_info = {}; - if (parsed.options.info) { - for (k in parsed.options.info) { - this.jse_info[k] = parsed.options.info[k]; - } - } - - this.message = message; - Error.call(this, message); - - if (Error.captureStackTrace) { - ctor = parsed.options.constructorOpt || this.constructor; - Error.captureStackTrace(this, ctor); - } - - return (this); -} - -mod_util.inherits(VError, Error); -VError.prototype.name = 'VError'; - -VError.prototype.toString = function ve_toString() -{ - var str = (this.hasOwnProperty('name') && this.name || - this.constructor.name || this.constructor.prototype.name); - if (this.message) - str += ': ' + this.message; - - return (str); -}; - -/* - * This method is provided for compatibility. New callers should use - * VError.cause() instead. That method also uses the saner `null` return value - * when there is no cause. - */ -VError.prototype.cause = function ve_cause() -{ - var cause = VError.cause(this); - return (cause === null ? undefined : cause); -}; - -/* - * Static methods - * - * These class-level methods are provided so that callers can use them on - * instances of Errors that are not VErrors. New interfaces should be provided - * only using static methods to eliminate the class of programming mistake where - * people fail to check whether the Error object has the corresponding methods. - */ - -VError.cause = function (err) -{ - mod_assertplus.ok(mod_isError(err), 'err must be an Error'); - return (mod_isError(err.jse_cause) ? err.jse_cause : null); -}; - -VError.info = function (err) -{ - var rv, cause, k; - - mod_assertplus.ok(mod_isError(err), 'err must be an Error'); - cause = VError.cause(err); - if (cause !== null) { - rv = VError.info(cause); - } else { - rv = {}; - } - - if (typeof (err.jse_info) == 'object' && err.jse_info !== null) { - for (k in err.jse_info) { - rv[k] = err.jse_info[k]; - } - } - - return (rv); -}; - -VError.findCauseByName = function (err, name) -{ - var cause; - - mod_assertplus.ok(mod_isError(err), 'err must be an Error'); - mod_assertplus.string(name, 'name'); - mod_assertplus.ok(name.length > 0, 'name cannot be empty'); - - for (cause = err; cause !== null; cause = VError.cause(cause)) { - mod_assertplus.ok(mod_isError(cause)); - if (cause.name == name) { - return (cause); - } - } - - return (null); -}; - -VError.hasCauseWithName = function (err, name) -{ - return (VError.findCauseByName(err, name) !== null); -}; - -VError.fullStack = function (err) -{ - mod_assertplus.ok(mod_isError(err), 'err must be an Error'); - - var cause = VError.cause(err); - - if (cause) { - return (err.stack + '\ncaused by: ' + VError.fullStack(cause)); - } - - return (err.stack); -}; - -VError.errorFromList = function (errors) -{ - mod_assertplus.arrayOfObject(errors, 'errors'); - - if (errors.length === 0) { - return (null); - } - - errors.forEach(function (e) { - mod_assertplus.ok(mod_isError(e)); - }); - - if (errors.length == 1) { - return (errors[0]); - } - - return (new MultiError(errors)); -}; - -VError.errorForEach = function (err, func) -{ - mod_assertplus.ok(mod_isError(err), 'err must be an Error'); - mod_assertplus.func(func, 'func'); - - if (err instanceof MultiError) { - err.errors().forEach(function iterError(e) { func(e); }); - } else { - func(err); - } -}; - - -/* - * SError is like VError, but stricter about types. You cannot pass "null" or - * "undefined" as string arguments to the formatter. - */ -function SError() -{ - var args, obj, parsed, options; - - args = Array.prototype.slice.call(arguments, 0); - if (!(this instanceof SError)) { - obj = Object.create(SError.prototype); - SError.apply(obj, arguments); - return (obj); - } - - parsed = parseConstructorArguments({ - 'argv': args, - 'strict': true - }); - - options = parsed.options; - VError.call(this, options, '%s', parsed.shortmessage); - - return (this); -} - -/* - * We don't bother setting SError.prototype.name because once constructed, - * SErrors are just like VErrors. - */ -mod_util.inherits(SError, VError); - - -/* - * Represents a collection of errors for the purpose of consumers that generally - * only deal with one error. Callers can extract the individual errors - * contained in this object, but may also just treat it as a normal single - * error, in which case a summary message will be printed. - */ -function MultiError(errors) -{ - mod_assertplus.array(errors, 'list of errors'); - mod_assertplus.ok(errors.length > 0, 'must be at least one error'); - this.ase_errors = errors; - - VError.call(this, { - 'cause': errors[0] - }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's'); -} - -mod_util.inherits(MultiError, VError); -MultiError.prototype.name = 'MultiError'; - -MultiError.prototype.errors = function me_errors() -{ - return (this.ase_errors.slice(0)); -}; - - -/* - * See README.md for reference details. - */ -function WError() -{ - var args, obj, parsed, options; - - args = Array.prototype.slice.call(arguments, 0); - if (!(this instanceof WError)) { - obj = Object.create(WError.prototype); - WError.apply(obj, args); - return (obj); - } - - parsed = parseConstructorArguments({ - 'argv': args, - 'strict': false - }); - - options = parsed.options; - options['skipCauseMessage'] = true; - VError.call(this, options, '%s', parsed.shortmessage); - - return (this); -} - -mod_util.inherits(WError, VError); -WError.prototype.name = 'WError'; - -WError.prototype.toString = function we_toString() -{ - var str = (this.hasOwnProperty('name') && this.name || - this.constructor.name || this.constructor.prototype.name); - if (this.message) - str += ': ' + this.message; - if (this.jse_cause && this.jse_cause.message) - str += '; caused by ' + this.jse_cause.toString(); - - return (str); -}; - -/* - * For purely historical reasons, WError's cause() function allows you to set - * the cause. - */ -WError.prototype.cause = function we_cause(c) -{ - if (mod_isError(c)) - this.jse_cause = c; - - return (this.jse_cause); -}; - -},{"assert-plus":77,"core-util-is":230,"extsprintf":374,"util":1776}],1788:[function(require,module,exports){ +},{}],1523:[function(require,module,exports){ var indexOf = function (xs, item) { if (xs.indexOf) return xs.indexOf(item); else for (var i = 0; i < xs.length; i++) { @@ -239390,13 +165842,13 @@ Script.prototype.runInContext = function (context) { if (!(context instanceof Context)) { throw new TypeError("needs a 'context' argument."); } - + var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; - + document.body.appendChild(iframe); - + var win = iframe.contentWindow; var wEval = win.eval, wExecScript = win.execScript; @@ -239405,7 +165857,7 @@ Script.prototype.runInContext = function (context) { wExecScript.call(win, 'null'); wEval = win.eval; } - + forEach(Object_keys(context), function (key) { win[key] = context[key]; }); @@ -239414,11 +165866,11 @@ Script.prototype.runInContext = function (context) { win[key] = context[key]; } }); - + var winKeys = Object_keys(win); var res = wEval.call(win, this.code); - + forEach(Object_keys(win), function (key) { // Avoid copying circular objects like `top` and `window` by only // updating existing context properties or new properties in the `win` @@ -239433,9 +165885,9 @@ Script.prototype.runInContext = function (context) { defineProp(context, key, win[key]); } }); - + document.body.removeChild(iframe); - + return res; }; @@ -239481,8896 +165933,7 @@ exports.createContext = Script.createContext = function (context) { return copy; }; -},{}],1789:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var swarm = require("swarm-js"); - - -var Bzz = function Bzz(provider) { - - this.givenProvider = Bzz.givenProvider; - - if (provider && provider._requestManager) { - provider = provider.currentProvider; - } - - // only allow file picker when in browser - if(typeof document !== 'undefined') { - this.pick = swarm.pick; - } - - this.setProvider(provider); -}; - -// set default ethereum provider -/* jshint ignore:start */ -Bzz.givenProvider = null; -if(typeof ethereumProvider !== 'undefined' && ethereumProvider.bzz) { - Bzz.givenProvider = ethereumProvider.bzz; -} -/* jshint ignore:end */ - -Bzz.prototype.setProvider = function(provider) { - // is ethereum provider - if(_.isObject(provider) && _.isString(provider.bzz)) { - provider = provider.bzz; - // is no string, set default - } - // else if(!_.isString(provider)) { - // provider = 'http://swarm-gateways.net'; // default to gateway - // } - - - if(_.isString(provider)) { - this.currentProvider = provider; - } else { - this.currentProvider = null; - - var noProviderError = new Error('No provider set, please set one using bzz.setProvider().'); - - this.download = this.upload = this.isAvailable = function(){ - throw noProviderError; - }; - - return false; - } - - // add functions - this.download = swarm.at(provider).download; - this.upload = swarm.at(provider).upload; - this.isAvailable = swarm.at(provider).isAvailable; - - return true; -}; - - -module.exports = Bzz; - - -},{"swarm-js":1744,"underscore":1765}],1790:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file errors.js - * @author Fabian Vogelsteller - * @author Marek Kotewicz - * @date 2017 - */ - -"use strict"; - -module.exports = { - ErrorResponse: function (result) { - var message = !!result && !!result.error && !!result.error.message ? result.error.message : JSON.stringify(result); - return new Error('Returned error: ' + message); - }, - InvalidNumberOfParams: function (got, expected, method) { - return new Error('Invalid number of parameters for "'+ method +'". Got '+ got +' expected '+ expected +'!'); - }, - InvalidConnection: function (host){ - return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); - }, - InvalidProvider: function () { - return new Error('Provider not set or invalid'); - }, - InvalidResponse: function (result){ - var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); - return new Error(message); - }, - ConnectionTimeout: function (ms){ - return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); - } -}; - -},{}],1791:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file formatters.js - * @author Fabian Vogelsteller - * @author Marek Kotewicz - * @date 2017 - */ - -"use strict"; - - -var _ = require('underscore'); -var utils = require('web3-utils'); -var Iban = require('web3-eth-iban'); - -/** - * Should the format output to a big number - * - * @method outputBigNumberFormatter - * @param {String|Number|BigNumber} number - * @returns {BigNumber} object - */ -var outputBigNumberFormatter = function (number) { - return utils.toBN(number).toString(10); -}; - -var isPredefinedBlockNumber = function (blockNumber) { - return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; -}; - -var inputDefaultBlockNumberFormatter = function (blockNumber) { - if (this && (blockNumber === undefined || blockNumber === null)) { - return this.defaultBlock; - } - if (blockNumber === 'genesis' || blockNumber === 'earliest') { - return '0x0'; - } - return inputBlockNumberFormatter(blockNumber); -}; - -var inputBlockNumberFormatter = function (blockNumber) { - if (blockNumber === undefined) { - return undefined; - } else if (isPredefinedBlockNumber(blockNumber)) { - return blockNumber; - } - return (utils.isHexStrict(blockNumber)) ? ((_.isString(blockNumber)) ? blockNumber.toLowerCase() : blockNumber) : utils.numberToHex(blockNumber); -}; - -/** - * Formats the input of a transaction and converts all values to HEX - * - * @method _txInputFormatter - * @param {Object} transaction options - * @returns object - */ -var _txInputFormatter = function (options){ - - if (options.to) { // it might be contract creation - options.to = inputAddressFormatter(options.to); - } - - if (options.data && options.input) { - throw new Error('You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); - } - - if (!options.data && options.input) { - options.data = options.input; - delete options.input; - } - - if(options.data && !utils.isHex(options.data)) { - throw new Error('The data field must be HEX encoded data.'); - } - - // allow both - if (options.gas || options.gasLimit) { - options.gas = options.gas || options.gasLimit; - } - - ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { - return options[key] !== undefined; - }).forEach(function(key){ - options[key] = utils.numberToHex(options[key]); - }); - - return options; -}; - -/** - * Formats the input of a transaction and converts all values to HEX - * - * @method inputCallFormatter - * @param {Object} transaction options - * @returns object -*/ -var inputCallFormatter = function (options){ - - options = _txInputFormatter(options); - - var from = options.from || (this ? this.defaultAccount : null); - - if (from) { - options.from = inputAddressFormatter(from); - } - - - return options; -}; - -/** - * Formats the input of a transaction and converts all values to HEX - * - * @method inputTransactionFormatter - * @param {Object} options - * @returns object -*/ -var inputTransactionFormatter = function (options) { - - options = _txInputFormatter(options); - - // check from, only if not number, or object - if (!_.isNumber(options.from) && !_.isObject(options.from)) { - options.from = options.from || (this ? this.defaultAccount : null); - - if (!options.from && !_.isNumber(options.from)) { - throw new Error('The send transactions "from" field must be defined!'); - } - - options.from = inputAddressFormatter(options.from); - } - - return options; -}; - -/** - * Hex encodes the data passed to eth_sign and personal_sign - * - * @method inputSignFormatter - * @param {String} data - * @returns {String} - */ -var inputSignFormatter = function (data) { - return (utils.isHexStrict(data)) ? data : utils.utf8ToHex(data); -}; - -/** - * Formats the output of a transaction to its proper values - * - * @method outputTransactionFormatter - * @param {Object} tx - * @returns {Object} -*/ -var outputTransactionFormatter = function (tx){ - if(tx.blockNumber !== null) - tx.blockNumber = utils.hexToNumber(tx.blockNumber); - if(tx.transactionIndex !== null) - tx.transactionIndex = utils.hexToNumber(tx.transactionIndex); - tx.nonce = utils.hexToNumber(tx.nonce); - tx.gas = utils.hexToNumber(tx.gas); - tx.gasPrice = outputBigNumberFormatter(tx.gasPrice); - tx.value = outputBigNumberFormatter(tx.value); - - if(tx.to && utils.isAddress(tx.to)) { // tx.to could be `0x0` or `null` while contract creation - tx.to = utils.toChecksumAddress(tx.to); - } else { - tx.to = null; // set to `null` if invalid address - } - - if(tx.from) { - tx.from = utils.toChecksumAddress(tx.from); - } - - return tx; -}; - -/** - * Formats the output of a transaction receipt to its proper values - * - * @method outputTransactionReceiptFormatter - * @param {Object} receipt - * @returns {Object} -*/ -var outputTransactionReceiptFormatter = function (receipt){ - if(typeof receipt !== 'object') { - throw new Error('Received receipt is invalid: '+ receipt); - } - - if(receipt.blockNumber !== null) - receipt.blockNumber = utils.hexToNumber(receipt.blockNumber); - if(receipt.transactionIndex !== null) - receipt.transactionIndex = utils.hexToNumber(receipt.transactionIndex); - receipt.cumulativeGasUsed = utils.hexToNumber(receipt.cumulativeGasUsed); - receipt.gasUsed = utils.hexToNumber(receipt.gasUsed); - - if(_.isArray(receipt.logs)) { - receipt.logs = receipt.logs.map(outputLogFormatter); - } - - if(receipt.contractAddress) { - receipt.contractAddress = utils.toChecksumAddress(receipt.contractAddress); - } - - if(typeof receipt.status !== 'undefined') { - receipt.status = Boolean(parseInt(receipt.status)); - } - - return receipt; -}; - -/** - * Formats the output of a block to its proper values - * - * @method outputBlockFormatter - * @param {Object} block - * @returns {Object} -*/ -var outputBlockFormatter = function(block) { - - // transform to number - block.gasLimit = utils.hexToNumber(block.gasLimit); - block.gasUsed = utils.hexToNumber(block.gasUsed); - block.size = utils.hexToNumber(block.size); - block.timestamp = utils.hexToNumber(block.timestamp); - if (block.number !== null) - block.number = utils.hexToNumber(block.number); - - if(block.difficulty) - block.difficulty = outputBigNumberFormatter(block.difficulty); - if(block.totalDifficulty) - block.totalDifficulty = outputBigNumberFormatter(block.totalDifficulty); - - if (_.isArray(block.transactions)) { - block.transactions.forEach(function(item){ - if(!_.isString(item)) - return outputTransactionFormatter(item); - }); - } - - if (block.miner) - block.miner = utils.toChecksumAddress(block.miner); - - return block; -}; - -/** - * Formats the input of a log - * - * @method inputLogFormatter - * @param {Object} log object - * @returns {Object} log -*/ -var inputLogFormatter = function(options) { - var toTopic = function(value){ - - if(value === null || typeof value === 'undefined') - return null; - - value = String(value); - - if(value.indexOf('0x') === 0) - return value; - else - return utils.fromUtf8(value); - }; - - if (options.fromBlock) - options.fromBlock = inputBlockNumberFormatter(options.fromBlock); - - if (options.toBlock) - options.toBlock = inputBlockNumberFormatter(options.toBlock); - - - // make sure topics, get converted to hex - options.topics = options.topics || []; - options.topics = options.topics.map(function(topic){ - return (_.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); - }); - - toTopic = null; - - if (options.address) { - options.address = (_.isArray(options.address)) ? options.address.map(function (addr) { - return inputAddressFormatter(addr); - }) : inputAddressFormatter(options.address); - } - - return options; -}; - -/** - * Formats the output of a log - * - * @method outputLogFormatter - * @param {Object} log object - * @returns {Object} log -*/ -var outputLogFormatter = function(log) { - - // generate a custom log id - if(typeof log.blockHash === 'string' && - typeof log.transactionHash === 'string' && - typeof log.logIndex === 'string') { - var shaId = utils.sha3(log.blockHash.replace('0x','') + log.transactionHash.replace('0x','') + log.logIndex.replace('0x','')); - log.id = 'log_'+ shaId.replace('0x','').substr(0,8); - } else if(!log.id) { - log.id = null; - } - - if (log.blockNumber !== null) - log.blockNumber = utils.hexToNumber(log.blockNumber); - if (log.transactionIndex !== null) - log.transactionIndex = utils.hexToNumber(log.transactionIndex); - if (log.logIndex !== null) - log.logIndex = utils.hexToNumber(log.logIndex); - - if (log.address) { - log.address = utils.toChecksumAddress(log.address); - } - - return log; -}; - -/** - * Formats the input of a whisper post and converts all values to HEX - * - * @method inputPostFormatter - * @param {Object} transaction object - * @returns {Object} -*/ -var inputPostFormatter = function(post) { - - // post.payload = utils.toHex(post.payload); - - if (post.ttl) - post.ttl = utils.numberToHex(post.ttl); - if (post.workToProve) - post.workToProve = utils.numberToHex(post.workToProve); - if (post.priority) - post.priority = utils.numberToHex(post.priority); - - // fallback - if (!_.isArray(post.topics)) { - post.topics = post.topics ? [post.topics] : []; - } - - // format the following options - post.topics = post.topics.map(function(topic){ - // convert only if not hex - return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); - }); - - return post; -}; - -/** - * Formats the output of a received post message - * - * @method outputPostFormatter - * @param {Object} - * @returns {Object} - */ -var outputPostFormatter = function(post){ - - post.expiry = utils.hexToNumber(post.expiry); - post.sent = utils.hexToNumber(post.sent); - post.ttl = utils.hexToNumber(post.ttl); - post.workProved = utils.hexToNumber(post.workProved); - // post.payloadRaw = post.payload; - // post.payload = utils.hexToAscii(post.payload); - - // if (utils.isJson(post.payload)) { - // post.payload = JSON.parse(post.payload); - // } - - // format the following options - if (!post.topics) { - post.topics = []; - } - post.topics = post.topics.map(function(topic){ - return utils.toUtf8(topic); - }); - - return post; -}; - -var inputAddressFormatter = function (address) { - var iban = new Iban(address); - if (iban.isValid() && iban.isDirect()) { - return iban.toAddress().toLowerCase(); - } else if (utils.isAddress(address)) { - return '0x' + address.toLowerCase().replace('0x',''); - } - throw new Error('Provided address "'+ address +'" is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can\'t be converted.'); -}; - - -var outputSyncingFormatter = function(result) { - - result.startingBlock = utils.hexToNumber(result.startingBlock); - result.currentBlock = utils.hexToNumber(result.currentBlock); - result.highestBlock = utils.hexToNumber(result.highestBlock); - if (result.knownStates) { - result.knownStates = utils.hexToNumber(result.knownStates); - result.pulledStates = utils.hexToNumber(result.pulledStates); - } - - return result; -}; - -module.exports = { - inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, - inputBlockNumberFormatter: inputBlockNumberFormatter, - inputCallFormatter: inputCallFormatter, - inputTransactionFormatter: inputTransactionFormatter, - inputAddressFormatter: inputAddressFormatter, - inputPostFormatter: inputPostFormatter, - inputLogFormatter: inputLogFormatter, - inputSignFormatter: inputSignFormatter, - outputBigNumberFormatter: outputBigNumberFormatter, - outputTransactionFormatter: outputTransactionFormatter, - outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, - outputBlockFormatter: outputBlockFormatter, - outputLogFormatter: outputLogFormatter, - outputPostFormatter: outputPostFormatter, - outputSyncingFormatter: outputSyncingFormatter -}; - - -},{"underscore":1765,"web3-eth-iban":1825,"web3-utils":1835}],1792:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var errors = require('./errors'); -var formatters = require('./formatters'); - -module.exports = { - errors: errors, - formatters: formatters -}; - - -},{"./errors":1790,"./formatters":1791}],1793:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @author Marek Kotewicz - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var errors = require('web3-core-helpers').errors; -var formatters = require('web3-core-helpers').formatters; -var utils = require('web3-utils'); -var promiEvent = require('web3-core-promievent'); -var Subscriptions = require('web3-core-subscriptions').subscriptions; - -var TIMEOUTBLOCK = 50; -var POLLINGTIMEOUT = 15 * TIMEOUTBLOCK; // ~average block time (seconds) * TIMEOUTBLOCK -var CONFIRMATIONBLOCKS = 24; - -var Method = function Method(options) { - - if(!options.call || !options.name) { - throw new Error('When creating a method you need to provide at least the "name" and "call" property.'); - } - - this.name = options.name; - this.call = options.call; - this.params = options.params || 0; - this.inputFormatter = options.inputFormatter; - this.outputFormatter = options.outputFormatter; - this.transformPayload = options.transformPayload; - this.extraFormatters = options.extraFormatters; - - this.requestManager = options.requestManager; - - // reference to eth.accounts - this.accounts = options.accounts; - - this.defaultBlock = options.defaultBlock || 'latest'; - this.defaultAccount = options.defaultAccount || null; -}; - -Method.prototype.setRequestManager = function (requestManager, accounts) { - this.requestManager = requestManager; - - // reference to eth.accounts - if (accounts) { - this.accounts = accounts; - } - -}; - -Method.prototype.createFunction = function (requestManager, accounts) { - var func = this.buildCall(); - func.call = this.call; - - this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts); - - return func; -}; - -Method.prototype.attachToObject = function (obj) { - var func = this.buildCall(); - func.call = this.call; - var name = this.name.split('.'); - if (name.length > 1) { - obj[name[0]] = obj[name[0]] || {}; - obj[name[0]][name[1]] = func; - } else { - obj[name[0]] = func; - } -}; - -/** - * Should be used to determine name of the jsonrpc method based on arguments - * - * @method getCall - * @param {Array} arguments - * @return {String} name of jsonrpc method - */ -Method.prototype.getCall = function (args) { - return _.isFunction(this.call) ? this.call(args) : this.call; -}; - -/** - * Should be used to extract callback from array of arguments. Modifies input param - * - * @method extractCallback - * @param {Array} arguments - * @return {Function|Null} callback, if exists - */ -Method.prototype.extractCallback = function (args) { - if (_.isFunction(args[args.length - 1])) { - return args.pop(); // modify the args array! - } -}; - -/** - * Should be called to check if the number of arguments is correct - * - * @method validateArgs - * @param {Array} arguments - * @throws {Error} if it is not - */ -Method.prototype.validateArgs = function (args) { - if (args.length !== this.params) { - throw errors.InvalidNumberOfParams(args.length, this.params, this.name); - } -}; - -/** - * Should be called to format input args of method - * - * @method formatInput - * @param {Array} - * @return {Array} - */ -Method.prototype.formatInput = function (args) { - var _this = this; - - if (!this.inputFormatter) { - return args; - } - - return this.inputFormatter.map(function (formatter, index) { - // bind this for defaultBlock, and defaultAccount - return formatter ? formatter.call(_this, args[index]) : args[index]; - }); -}; - -/** - * Should be called to format output(result) of method - * - * @method formatOutput - * @param {Object} - * @return {Object} - */ -Method.prototype.formatOutput = function (result) { - var _this = this; - - if(_.isArray(result)) { - return result.map(function(res){ - return _this.outputFormatter && res ? _this.outputFormatter(res) : res; - }); - } else { - return this.outputFormatter && result ? this.outputFormatter(result) : result; - } -}; - -/** - * Should create payload from given input args - * - * @method toPayload - * @param {Array} args - * @return {Object} - */ -Method.prototype.toPayload = function (args) { - var call = this.getCall(args); - var callback = this.extractCallback(args); - var params = this.formatInput(args); - this.validateArgs(params); - - var payload = { - method: call, - params: params, - callback: callback - }; - - if (this.transformPayload) { - payload = this.transformPayload(payload); - } - - return payload; -}; - - -Method.prototype._confirmTransaction = function (defer, result, payload) { - var method = this, - promiseResolved = false, - canUnsubscribe = true, - timeoutCount = 0, - confirmationCount = 0, - intervalId = null, - receiptJSON = '', - gasProvided = (_.isObject(payload.params[0]) && payload.params[0].gas) ? payload.params[0].gas : null, - isContractDeployment = _.isObject(payload.params[0]) && - payload.params[0].data && - payload.params[0].from && - !payload.params[0].to; - - // add custom send Methods - var _ethereumCalls = [ - new Method({ - name: 'getTransactionReceipt', - call: 'eth_getTransactionReceipt', - params: 1, - inputFormatter: [null], - outputFormatter: formatters.outputTransactionReceiptFormatter - }), - new Method({ - name: 'getCode', - call: 'eth_getCode', - params: 2, - inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] - }), - new Subscriptions({ - name: 'subscribe', - type: 'eth', - subscriptions: { - 'newBlockHeaders': { - subscriptionName: 'newHeads', // replace subscription with this name - params: 0, - outputFormatter: formatters.outputBlockFormatter - } - } - }) - ]; - // attach methods to this._ethereumCall - var _ethereumCall = {}; - _.each(_ethereumCalls, function (mthd) { - mthd.attachToObject(_ethereumCall); - mthd.requestManager = method.requestManager; // assign rather than call setRequestManager() - }); - - - // fire "receipt" and confirmation events and resolve after - var checkConfirmation = function (existingReceipt, isPolling, err, blockHeader, sub) { - if (!err) { - // create fake unsubscribe - if (!sub) { - sub = { - unsubscribe: function () { - clearInterval(intervalId); - } - }; - } - // if we have a valid receipt we don't need to send a request - return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result)) - // catch error from requesting receipt - .catch(function (err) { - sub.unsubscribe(); - promiseResolved = true; - utils._fireError({message: 'Failed to check for transaction receipt:', data: err}, defer.eventEmitter, defer.reject); - }) - // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false - .then(function(receipt) { - if (!receipt || !receipt.blockHash) { - throw new Error('Receipt missing or blockHash null'); - } - - // apply extra formatters - if (method.extraFormatters && method.extraFormatters.receiptFormatter) { - receipt = method.extraFormatters.receiptFormatter(receipt); - } - - // check if confirmation listener exists - if (defer.eventEmitter.listeners('confirmation').length > 0) { - - // If there was an immediately retrieved receipt, it's already - // been confirmed by the direct call to checkConfirmation needed - // for parity instant-seal - if (existingReceipt === undefined || confirmationCount !== 0){ - defer.eventEmitter.emit('confirmation', confirmationCount, receipt); - } - - canUnsubscribe = false; - confirmationCount++; - - if (confirmationCount === CONFIRMATIONBLOCKS + 1) { // add 1 so we account for conf 0 - sub.unsubscribe(); - defer.eventEmitter.removeAllListeners(); - } - } - - return receipt; - }) - // CHECK for CONTRACT DEPLOYMENT - .then(function(receipt) { - - if (isContractDeployment && !promiseResolved) { - - if (!receipt.contractAddress) { - - if (canUnsubscribe) { - sub.unsubscribe(); - promiseResolved = true; - } - - utils._fireError(new Error('The transaction receipt didn\'t contain a contract address.'), defer.eventEmitter, defer.reject); - return; - } - - _ethereumCall.getCode(receipt.contractAddress, function (e, code) { - - if (!code) { - return; - } - - - if (code.length > 2) { - defer.eventEmitter.emit('receipt', receipt); - - // if contract, return instance instead of receipt - if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) { - defer.resolve(method.extraFormatters.contractDeployFormatter(receipt)); - } else { - defer.resolve(receipt); - } - - // need to remove listeners, as they aren't removed automatically when succesfull - if (canUnsubscribe) { - defer.eventEmitter.removeAllListeners(); - } - - } else { - utils._fireError(new Error('The contract code couldn\'t be stored, please check your gas limit.'), defer.eventEmitter, defer.reject); - } - - if (canUnsubscribe) { - sub.unsubscribe(); - } - promiseResolved = true; - }); - } - - return receipt; - }) - // CHECK for normal tx check for receipt only - .then(function(receipt) { - - if (!isContractDeployment && !promiseResolved) { - - if(!receipt.outOfGas && - (!gasProvided || gasProvided !== receipt.gasUsed) && - (receipt.status === true || receipt.status === '0x1' || typeof receipt.status === 'undefined')) { - defer.eventEmitter.emit('receipt', receipt); - defer.resolve(receipt); - - // need to remove listeners, as they aren't removed automatically when succesfull - if (canUnsubscribe) { - defer.eventEmitter.removeAllListeners(); - } - - } else { - receiptJSON = JSON.stringify(receipt, null, 2); - if (receipt.status === false || receipt.status === '0x0') { - utils._fireError(new Error("Transaction has been reverted by the EVM:\n" + receiptJSON), - defer.eventEmitter, defer.reject); - } else { - utils._fireError( - new Error("Transaction ran out of gas. Please provide more gas:\n" + receiptJSON), - defer.eventEmitter, defer.reject); - } - } - - if (canUnsubscribe) { - sub.unsubscribe(); - } - promiseResolved = true; - } - - }) - // time out the transaction if not mined after 50 blocks - .catch(function () { - timeoutCount++; - - // check to see if we are http polling - if(!!isPolling) { - // polling timeout is different than TIMEOUTBLOCK blocks since we are triggering every second - if (timeoutCount - 1 >= POLLINGTIMEOUT) { - sub.unsubscribe(); - promiseResolved = true; - utils._fireError(new Error('Transaction was not mined within' + POLLINGTIMEOUT + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); - } - } else { - if (timeoutCount - 1 >= TIMEOUTBLOCK) { - sub.unsubscribe(); - promiseResolved = true; - utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); - } - } - }); - - - } else { - sub.unsubscribe(); - promiseResolved = true; - utils._fireError({message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.', data: err}, defer.eventEmitter, defer.reject); - } - }; - - // start watching for confirmation depending on the support features of the provider - var startWatching = function(existingReceipt) { - // if provider allows PUB/SUB - if (_.isFunction(this.requestManager.provider.on)) { - _ethereumCall.subscribe('newBlockHeaders', checkConfirmation.bind(null, existingReceipt, false)); - } else { - intervalId = setInterval(checkConfirmation.bind(null, existingReceipt, true), 1000); - } - }.bind(this); - - - // first check if we already have a confirmed transaction - _ethereumCall.getTransactionReceipt(result) - .then(function(receipt) { - if (receipt && receipt.blockHash) { - if (defer.eventEmitter.listeners('confirmation').length > 0) { - // We must keep on watching for new Blocks, if a confirmation listener is present - startWatching(receipt); - } - checkConfirmation(receipt, false); - - } else if (!promiseResolved) { - startWatching(); - } - }) - .catch(function(){ - if (!promiseResolved) startWatching(); - }); - -}; - - -var getWallet = function(from, accounts) { - var wallet = null; - - // is index given - if (_.isNumber(from)) { - wallet = accounts.wallet[from]; - - // is account given - } else if (_.isObject(from) && from.address && from.privateKey) { - wallet = from; - - // search in wallet for address - } else { - wallet = accounts.wallet[from.toLowerCase()]; - } - - return wallet; -}; - -Method.prototype.buildCall = function() { - var method = this, - isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'); // || method.call === 'personal_sendTransaction' - - // actual send function - var send = function () { - var defer = promiEvent(!isSendTx), - payload = method.toPayload(Array.prototype.slice.call(arguments)); - - - // CALLBACK function - var sendTxCallback = function (err, result) { - try { - result = method.formatOutput(result); - } catch(e) { - err = e; - } - - if (result instanceof Error) { - err = result; - } - - if (!err) { - if (payload.callback) { - payload.callback(null, result); - } - } else { - if(err.error) { - err = err.error; - } - - return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback); - } - - // return PROMISE - if (!isSendTx) { - - if (!err) { - defer.resolve(result); - - } - - // return PROMIEVENT - } else { - defer.eventEmitter.emit('transactionHash', result); - - method._confirmTransaction(defer, result, payload); - } - - }; - - // SENDS the SIGNED SIGNATURE - var sendSignedTx = function(sign){ - - var signedPayload = _.extend({}, payload, { - method: 'eth_sendRawTransaction', - params: [sign.rawTransaction] - }); - - method.requestManager.send(signedPayload, sendTxCallback); - }; - - - var sendRequest = function(payload, method) { - - if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) { - var wallet; - - // ETH_SENDTRANSACTION - if (payload.method === 'eth_sendTransaction') { - var tx = payload.params[0]; - wallet = getWallet((_.isObject(tx)) ? tx.from : null, method.accounts); - - - // If wallet was found, sign tx, and send using sendRawTransaction - if (wallet && wallet.privateKey) { - return method.accounts.signTransaction(_.omit(tx, 'from'), wallet.privateKey).then(sendSignedTx); - } - - // ETH_SIGN - } else if (payload.method === 'eth_sign') { - var data = payload.params[1]; - wallet = getWallet(payload.params[0], method.accounts); - - // If wallet was found, sign tx, and send using sendRawTransaction - if (wallet && wallet.privateKey) { - var sign = method.accounts.sign(data, wallet.privateKey); - - if (payload.callback) { - payload.callback(null, sign.signature); - } - - defer.resolve(sign.signature); - return; - } - - - } - } - - return method.requestManager.send(payload, sendTxCallback); - }; - - // Send the actual transaction - if(isSendTx && _.isObject(payload.params[0]) && typeof payload.params[0].gasPrice === 'undefined') { - - var getGasPrice = (new Method({ - name: 'getGasPrice', - call: 'eth_gasPrice', - params: 0 - })).createFunction(method.requestManager); - - getGasPrice(function (err, gasPrice) { - - if (gasPrice) { - payload.params[0].gasPrice = gasPrice; - } - sendRequest(payload, method); - }); - - } else { - sendRequest(payload, method); - } - - - return defer.eventEmitter; - }; - - // necessary to attach things to the method - send.method = method; - // necessary for batch requests - send.request = this.request.bind(this); - return send; -}; - -/** - * Should be called to create the pure JSONRPC request which can be used in a batch request - * - * @method request - * @return {Object} jsonrpc request - */ -Method.prototype.request = function () { - var payload = this.toPayload(Array.prototype.slice.call(arguments)); - payload.format = this.formatOutput.bind(this); - return payload; -}; - -module.exports = Method; - -},{"underscore":1765,"web3-core-helpers":1792,"web3-core-promievent":1794,"web3-core-subscriptions":1799,"web3-utils":1835}],1794:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2016 - */ - -"use strict"; - -var EventEmitter = require('eventemitter3'); -var Promise = require("any-promise"); - -/** - * This function generates a defer promise and adds eventEmitter functionality to it - * - * @method eventifiedPromise - */ -var PromiEvent = function PromiEvent(justPromise) { - var resolve, reject, - eventEmitter = new Promise(function() { - resolve = arguments[0]; - reject = arguments[1]; - }); - - if(justPromise) { - return { - resolve: resolve, - reject: reject, - eventEmitter: eventEmitter - }; - } - - // get eventEmitter - var emitter = new EventEmitter(); - - // add eventEmitter to the promise - eventEmitter._events = emitter._events; - eventEmitter.emit = emitter.emit; - eventEmitter.on = emitter.on; - eventEmitter.once = emitter.once; - eventEmitter.off = emitter.off; - eventEmitter.listeners = emitter.listeners; - eventEmitter.addListener = emitter.addListener; - eventEmitter.removeListener = emitter.removeListener; - eventEmitter.removeAllListeners = emitter.removeAllListeners; - - return { - resolve: resolve, - reject: reject, - eventEmitter: eventEmitter - }; -}; - -PromiEvent.resolve = function(value) { - var promise = PromiEvent(true); - promise.resolve(value); - return promise.eventEmitter; -}; - -module.exports = PromiEvent; - -},{"any-promise":51,"eventemitter3":369}],1795:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file batch.js - * @author Marek Kotewicz - * @date 2015 - */ - -"use strict"; - -var Jsonrpc = require('./jsonrpc'); -var errors = require('web3-core-helpers').errors; - -var Batch = function (requestManager) { - this.requestManager = requestManager; - this.requests = []; -}; - -/** - * Should be called to add create new request to batch request - * - * @method add - * @param {Object} jsonrpc requet object - */ -Batch.prototype.add = function (request) { - this.requests.push(request); -}; - -/** - * Should be called to execute batch request - * - * @method execute - */ -Batch.prototype.execute = function () { - var requests = this.requests; - this.requestManager.sendBatch(requests, function (err, results) { - results = results || []; - requests.map(function (request, index) { - return results[index] || {}; - }).forEach(function (result, index) { - if (requests[index].callback) { - if (result && result.error) { - return requests[index].callback(errors.ErrorResponse(result)); - } - - if (!Jsonrpc.isValidResponse(result)) { - return requests[index].callback(errors.InvalidResponse(result)); - } - - try { - requests[index].callback(null, requests[index].format ? requests[index].format(result.result) : result.result); - } catch (err) { - requests[index].callback(err); - } - } - }); - }); -}; - -module.exports = Batch; - - -},{"./jsonrpc":1798,"web3-core-helpers":1792}],1796:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file givenProvider.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var givenProvider = null; - -// ADD GIVEN PROVIDER -/* jshint ignore:start */ -var global; -try { - global = Function('return this')(); -} catch (e) { - global = window; -} - -// EthereumProvider -if(typeof global.ethereumProvider !== 'undefined') { - givenProvider = global.ethereumProvider; - -// Legacy web3.currentProvider -} else if(typeof global.web3 !== 'undefined' && global.web3.currentProvider) { - - if(global.web3.currentProvider.sendAsync) { - global.web3.currentProvider.send = global.web3.currentProvider.sendAsync; - delete global.web3.currentProvider.sendAsync; - } - - // if connection is 'ipcProviderWrapper', add subscription support - if(!global.web3.currentProvider.on && - global.web3.currentProvider.connection && - global.web3.currentProvider.connection.constructor.name === 'ipcProviderWrapper') { - - global.web3.currentProvider.on = function (type, callback) { - - if(typeof callback !== 'function') - throw new Error('The second parameter callback must be a function.'); - - switch(type){ - case 'data': - this.connection.on('data', function(data) { - var result = ''; - - data = data.toString(); - - try { - result = JSON.parse(data); - } catch(e) { - return callback(new Error('Couldn\'t parse response data'+ data)); - } - - // notification - if(!result.id && result.method.indexOf('_subscription') !== -1) { - callback(null, result); - } - - }); - break; - - default: - this.connection.on(type, callback); - break; - } - }; - } - - givenProvider = global.web3.currentProvider; -} -/* jshint ignore:end */ - - -module.exports = givenProvider; - -},{}],1797:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - - -var _ = require('underscore'); -var errors = require('web3-core-helpers').errors; -var Jsonrpc = require('./jsonrpc.js'); -var BatchManager = require('./batch.js'); -var givenProvider = require('./givenProvider.js'); - - - - /** - * It's responsible for passing messages to providers - * It's also responsible for polling the ethereum node for incoming messages - * Default poll timeout is 1 second - * Singleton - */ -var RequestManager = function RequestManager(provider) { - this.provider = null; - this.providers = RequestManager.providers; - - this.setProvider(provider); - this.subscriptions = {}; -}; - - - -RequestManager.givenProvider = givenProvider; - -RequestManager.providers = { - WebsocketProvider: require('web3-providers-ws'), - HttpProvider: require('web3-providers-http'), - IpcProvider: require('web3-providers-ipc') -}; - - - -/** - * Should be used to set provider of request manager - * - * @method setProvider - * @param {Object} p - */ -RequestManager.prototype.setProvider = function (p, net) { - var _this = this; - - // autodetect provider - if(p && typeof p === 'string' && this.providers) { - - // HTTP - if(/^http(s)?:\/\//i.test(p)) { - p = new this.providers.HttpProvider(p); - - // WS - } else if(/^ws(s)?:\/\//i.test(p)) { - p = new this.providers.WebsocketProvider(p); - - // IPC - } else if(p && typeof net === 'object' && typeof net.connect === 'function') { - p = new this.providers.IpcProvider(p, net); - - } else if(p) { - throw new Error('Can\'t autodetect provider for "'+ p +'"'); - } - } - - // reset the old one before changing, if still connected - if(this.provider && this.provider.connected) - this.clearSubscriptions(); - - - this.provider = p || null; - - // listen to incoming notifications - if(this.provider && this.provider.on) { - this.provider.on('data', function requestManagerNotification(result, deprecatedResult){ - result = result || deprecatedResult; // this is for possible old providers, which may had the error first handler - - // check for result.method, to prevent old providers errors to pass as result - if(result.method && _this.subscriptions[result.params.subscription] && _this.subscriptions[result.params.subscription].callback) { - _this.subscriptions[result.params.subscription].callback(null, result.params.result); - } - }); - // TODO add error, end, timeout, connect?? - // this.provider.on('error', function requestManagerNotification(result){ - // Object.keys(_this.subscriptions).forEach(function(id){ - // if(_this.subscriptions[id].callback) - // _this.subscriptions[id].callback(err); - // }); - // } - } -}; - - -/** - * Should be used to asynchronously send request - * - * @method sendAsync - * @param {Object} data - * @param {Function} callback - */ -RequestManager.prototype.send = function (data, callback) { - callback = callback || function(){}; - - if (!this.provider) { - return callback(errors.InvalidProvider()); - } - - var payload = Jsonrpc.toPayload(data.method, data.params); - this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, result) { - if(result && result.id && payload.id !== result.id) return callback(new Error('Wrong response id "'+ result.id +'" (expected: "'+ payload.id +'") in '+ JSON.stringify(payload))); - - if (err) { - return callback(err); - } - - if (result && result.error) { - return callback(errors.ErrorResponse(result)); - } - - if (!Jsonrpc.isValidResponse(result)) { - return callback(errors.InvalidResponse(result)); - } - - callback(null, result.result); - }); -}; - -/** - * Should be called to asynchronously send batch request - * - * @method sendBatch - * @param {Array} batch data - * @param {Function} callback - */ -RequestManager.prototype.sendBatch = function (data, callback) { - if (!this.provider) { - return callback(errors.InvalidProvider()); - } - - var payload = Jsonrpc.toBatchPayload(data); - this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, results) { - if (err) { - return callback(err); - } - - if (!_.isArray(results)) { - return callback(errors.InvalidResponse(results)); - } - - callback(null, results); - }); -}; - - -/** - * Waits for notifications - * - * @method addSubscription - * @param {String} id the subscription id - * @param {String} name the subscription name - * @param {String} type the subscription namespace (eth, personal, etc) - * @param {Function} callback the callback to call for incoming notifications - */ -RequestManager.prototype.addSubscription = function (id, name, type, callback) { - if(this.provider.on) { - this.subscriptions[id] = { - callback: callback, - type: type, - name: name - }; - - } else { - throw new Error('The provider doesn\'t support subscriptions: '+ this.provider.constructor.name); - } -}; - -/** - * Waits for notifications - * - * @method removeSubscription - * @param {String} id the subscription id - * @param {Function} callback fired once the subscription is removed - */ -RequestManager.prototype.removeSubscription = function (id, callback) { - var _this = this; - - if(this.subscriptions[id]) { - - this.send({ - method: this.subscriptions[id].type + '_unsubscribe', - params: [id] - }, callback); - - // remove subscription - delete _this.subscriptions[id]; - } -}; - -/** - * Should be called to reset the subscriptions - * - * @method reset - */ -RequestManager.prototype.clearSubscriptions = function (keepIsSyncing) { - var _this = this; - - - // uninstall all subscriptions - Object.keys(this.subscriptions).forEach(function(id){ - if(!keepIsSyncing || _this.subscriptions[id].name !== 'syncing') - _this.removeSubscription(id); - }); - - - // reset notification callbacks etc. - if(this.provider.reset) - this.provider.reset(); -}; - -module.exports = { - Manager: RequestManager, - BatchManager: BatchManager -}; - -},{"./batch.js":1795,"./givenProvider.js":1796,"./jsonrpc.js":1798,"underscore":1765,"web3-core-helpers":1792,"web3-providers-http":1830,"web3-providers-ipc":1831,"web3-providers-ws":1832}],1798:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** @file jsonrpc.js - * @authors: - * Fabian Vogelsteller - * Marek Kotewicz - * Aaron Kumavis - * @date 2015 - */ - -"use strict"; - -// Initialize Jsonrpc as a simple object with utility functions. -var Jsonrpc = { - messageId: 0 -}; - -/** - * Should be called to valid json create payload object - * - * @method toPayload - * @param {Function} method of jsonrpc call, required - * @param {Array} params, an array of method params, optional - * @returns {Object} valid jsonrpc payload object - */ -Jsonrpc.toPayload = function (method, params) { - if (!method) { - throw new Error('JSONRPC method should be specified for params: "'+ JSON.stringify(params) +'"!'); - } - - // advance message ID - Jsonrpc.messageId++; - - return { - jsonrpc: '2.0', - id: Jsonrpc.messageId, - method: method, - params: params || [] - }; -}; - -/** - * Should be called to check if jsonrpc response is valid - * - * @method isValidResponse - * @param {Object} - * @returns {Boolean} true if response is valid, otherwise false - */ -Jsonrpc.isValidResponse = function (response) { - return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); - - function validateSingleMessage(message){ - return !!message && - !message.error && - message.jsonrpc === '2.0' && - (typeof message.id === 'number' || typeof message.id === 'string') && - message.result !== undefined; // only undefined is not valid json object - } -}; - -/** - * Should be called to create batch payload object - * - * @method toBatchPayload - * @param {Array} messages, an array of objects with method (required) and params (optional) fields - * @returns {Array} batch payload - */ -Jsonrpc.toBatchPayload = function (messages) { - return messages.map(function (message) { - return Jsonrpc.toPayload(message.method, message.params); - }); -}; - -module.exports = Jsonrpc; - - -},{}],1799:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var Subscription = require('./subscription.js'); - - -var Subscriptions = function Subscriptions(options) { - this.name = options.name; - this.type = options.type; - this.subscriptions = options.subscriptions || {}; - this.requestManager = null; -}; - - -Subscriptions.prototype.setRequestManager = function (rm) { - this.requestManager = rm; -}; - - -Subscriptions.prototype.attachToObject = function (obj) { - var func = this.buildCall(); - var name = this.name.split('.'); - if (name.length > 1) { - obj[name[0]] = obj[name[0]] || {}; - obj[name[0]][name[1]] = func; - } else { - obj[name[0]] = func; - } -}; - - -Subscriptions.prototype.buildCall = function() { - var _this = this; - - return function(){ - if(!_this.subscriptions[arguments[0]]) { - console.warn('Subscription '+ JSON.stringify(arguments[0]) +' doesn\'t exist. Subscribing anyway.'); - } - - var subscription = new Subscription({ - subscription: _this.subscriptions[arguments[0]], - requestManager: _this.requestManager, - type: _this.type - }); - - return subscription.subscribe.apply(subscription, arguments); - }; -}; - - -module.exports = { - subscriptions: Subscriptions, - subscription: Subscription -}; - -},{"./subscription.js":1800}],1800:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file subscription.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var errors = require('web3-core-helpers').errors; -var EventEmitter = require('eventemitter3'); - -function Subscription(options) { - EventEmitter.call(this); - - this.id = null; - this.callback = _.identity; - this.arguments = null; - this._reconnectIntervalId = null; - - this.options = { - subscription: options.subscription, - type: options.type, - requestManager: options.requestManager - }; -} - -// INHERIT -Subscription.prototype = Object.create(EventEmitter.prototype); -Subscription.prototype.constructor = Subscription; - - -/** - * Should be used to extract callback from array of arguments. Modifies input param - * - * @method extractCallback - * @param {Array} arguments - * @return {Function|Null} callback, if exists - */ - -Subscription.prototype._extractCallback = function (args) { - if (_.isFunction(args[args.length - 1])) { - return args.pop(); // modify the args array! - } -}; - -/** - * Should be called to check if the number of arguments is correct - * - * @method validateArgs - * @param {Array} arguments - * @throws {Error} if it is not - */ - -Subscription.prototype._validateArgs = function (args) { - var subscription = this.options.subscription; - - if(!subscription) - subscription = {}; - - if(!subscription.params) - subscription.params = 0; - - if (args.length !== subscription.params) { - throw errors.InvalidNumberOfParams(args.length, subscription.params + 1, args[0]); - } -}; - -/** - * Should be called to format input args of method - * - * @method formatInput - * @param {Array} - * @return {Array} - */ - -Subscription.prototype._formatInput = function (args) { - var subscription = this.options.subscription; - - if (!subscription) { - return args; - } - - if (!subscription.inputFormatter) { - return args; - } - - var formattedArgs = subscription.inputFormatter.map(function (formatter, index) { - return formatter ? formatter(args[index]) : args[index]; - }); - - return formattedArgs; -}; - -/** - * Should be called to format output(result) of method - * - * @method formatOutput - * @param {Object} - * @return {Object} - */ - -Subscription.prototype._formatOutput = function (result) { - var subscription = this.options.subscription; - - return (subscription && subscription.outputFormatter && result) ? subscription.outputFormatter(result) : result; -}; - -/** - * Should create payload from given input args - * - * @method toPayload - * @param {Array} args - * @return {Object} - */ -Subscription.prototype._toPayload = function (args) { - var params = []; - this.callback = this._extractCallback(args) || _.identity; - - if (!this.subscriptionMethod) { - this.subscriptionMethod = args.shift(); - - // replace subscription with given name - if (this.options.subscription.subscriptionName) { - this.subscriptionMethod = this.options.subscription.subscriptionName; - } - } - - if (!this.arguments) { - this.arguments = this._formatInput(args); - this._validateArgs(this.arguments); - args = []; // make empty after validation - - } - - // re-add subscriptionName - params.push(this.subscriptionMethod); - params = params.concat(this.arguments); - - - if (args.length) { - throw new Error('Only a callback is allowed as parameter on an already instantiated subscription.'); - } - - return { - method: this.options.type + '_subscribe', - params: params - }; -}; - -/** - * Unsubscribes and clears callbacks - * - * @method unsubscribe - * @return {Object} - */ -Subscription.prototype.unsubscribe = function(callback) { - this.options.requestManager.removeSubscription(this.id, callback); - this.id = null; - this.removeAllListeners(); - clearInterval(this._reconnectIntervalId); -}; - -/** - * Subscribes and watches for changes - * - * @method subscribe - * @param {String} subscription the subscription - * @param {Object} options the options object with address topics and fromBlock - * @return {Object} - */ -Subscription.prototype.subscribe = function() { - var _this = this; - var args = Array.prototype.slice.call(arguments); - var payload = this._toPayload(args); - - if(!payload) { - return this; - } - - if(!this.options.requestManager.provider) { - var err1 = new Error('No provider set.'); - this.callback(err1, null, this); - this.emit('error', err1); - return this; - } - - // throw error, if provider doesnt support subscriptions - if(!this.options.requestManager.provider.on) { - var err2 = new Error('The current provider doesn\'t support subscriptions: '+ this.options.requestManager.provider.constructor.name); - this.callback(err2, null, this); - this.emit('error', err2); - return this; - } - - // if id is there unsubscribe first - if (this.id) { - this.unsubscribe(); - } - - // store the params in the options object - this.options.params = payload.params[1]; - - // get past logs, if fromBlock is available - if(payload.params[0] === 'logs' && _.isObject(payload.params[1]) && payload.params[1].hasOwnProperty('fromBlock') && isFinite(payload.params[1].fromBlock)) { - // send the subscription request - this.options.requestManager.send({ - method: 'eth_getLogs', - params: [payload.params[1]] - }, function (err, logs) { - if(!err) { - logs.forEach(function(log){ - var output = _this._formatOutput(log); - _this.callback(null, output, _this); - _this.emit('data', output); - }); - - // TODO subscribe here? after the past logs? - - } else { - _this.callback(err, null, _this); - _this.emit('error', err); - } - }); - } - - // create subscription - // TODO move to separate function? so that past logs can go first? - - if(typeof payload.params[1] === 'object') - delete payload.params[1].fromBlock; - - this.options.requestManager.send(payload, function (err, result) { - if(!err && result) { - _this.id = result; - - // call callback on notifications - _this.options.requestManager.addSubscription(_this.id, payload.params[0] , _this.options.type, function(err, result) { - - if (!err) { - if (!_.isArray(result)) { - result = [result]; - } - - result.forEach(function(resultItem) { - var output = _this._formatOutput(resultItem); - - if (_.isFunction(_this.options.subscription.subscriptionHandler)) { - return _this.options.subscription.subscriptionHandler.call(_this, output); - } else { - _this.emit('data', output); - } - - // call the callback, last so that unsubscribe there won't affect the emit above - _this.callback(null, output, _this); - }); - } else { - // unsubscribe, but keep listeners - _this.options.requestManager.removeSubscription(_this.id); - - // re-subscribe, if connection fails - if(_this.options.requestManager.provider.once) { - _this._reconnectIntervalId = setInterval(function () { - // TODO check if that makes sense! - if (_this.options.requestManager.provider.reconnect) { - _this.options.requestManager.provider.reconnect(); - } - }, 500); - - _this.options.requestManager.provider.once('connect', function () { - clearInterval(_this._reconnectIntervalId); - _this.subscribe(_this.callback); - }); - } - _this.emit('error', err); - - // call the callback, last so that unsubscribe there won't affect the emit above - _this.callback(err, null, _this); - } - }); - } else { - _this.callback(err, null, _this); - _this.emit('error', err); - } - }); - - // return an object to cancel the subscription - return this; -}; - -module.exports = Subscription; - -},{"eventemitter3":369,"underscore":1765,"web3-core-helpers":1792}],1801:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file extend.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - - -var formatters = require('web3-core-helpers').formatters; -var Method = require('web3-core-method'); -var utils = require('web3-utils'); - - -var extend = function (pckg) { - /* jshint maxcomplexity:5 */ - var ex = function (extension) { - - var extendedObject; - if (extension.property) { - if (!pckg[extension.property]) { - pckg[extension.property] = {}; - } - extendedObject = pckg[extension.property]; - } else { - extendedObject = pckg; - } - - if (extension.methods) { - extension.methods.forEach(function (method) { - if(!(method instanceof Method)) { - method = new Method(method); - } - - method.attachToObject(extendedObject); - method.setRequestManager(pckg._requestManager); - }); - } - - return pckg; - }; - - ex.formatters = formatters; - ex.utils = utils; - ex.Method = Method; - - return ex; -}; - - - -module.exports = extend; - - -},{"web3-core-helpers":1792,"web3-core-method":1793,"web3-utils":1835}],1802:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - - -var requestManager = require('web3-core-requestmanager'); -var extend = require('./extend.js'); - -module.exports = { - packageInit: function (pkg, args) { - args = Array.prototype.slice.call(args); - - if (!pkg) { - throw new Error('You need to instantiate using the "new" keyword.'); - } - - - // make property of pkg._provider, which can properly set providers - Object.defineProperty(pkg, 'currentProvider', { - get: function () { - return pkg._provider; - }, - set: function (value) { - return pkg.setProvider(value); - }, - enumerable: true, - configurable: true - }); - - // inherit from web3 umbrella package - if (args[0] && args[0]._requestManager) { - pkg._requestManager = new requestManager.Manager(args[0].currentProvider); - - // set requestmanager on package - } else { - pkg._requestManager = new requestManager.Manager(); - pkg._requestManager.setProvider(args[0], args[1]); - } - - // add givenProvider - pkg.givenProvider = requestManager.Manager.givenProvider; - pkg.providers = requestManager.Manager.providers; - - pkg._provider = pkg._requestManager.provider; - - // add SETPROVIDER function (don't overwrite if already existing) - if (!pkg.setProvider) { - pkg.setProvider = function (provider, net) { - pkg._requestManager.setProvider(provider, net); - pkg._provider = pkg._requestManager.provider; - return true; - }; - } - - // attach batch request creation - pkg.BatchRequest = requestManager.BatchManager.bind(null, pkg._requestManager); - - // attach extend function - pkg.extend = extend(pkg); - }, - addProviders: function (pkg) { - pkg.givenProvider = requestManager.Manager.givenProvider; - pkg.providers = requestManager.Manager.providers; - } -}; - - -},{"./extend.js":1801,"web3-core-requestmanager":1797}],1803:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file index.js - * @author Marek Kotewicz - * @author Fabian Vogelsteller - * @date 2018 - */ - -var _ = require('underscore'); -var utils = require('web3-utils'); - -var EthersAbi = require('ethers/utils/abi-coder').AbiCoder; -var ethersAbiCoder = new EthersAbi(function (type, value) { - if (type.match(/^u?int/) && !_.isArray(value) && (!_.isObject(value) || value.constructor.name !== 'BN')) { - return value.toString(); - } - return value; -}); - -// result method -function Result() { -} - -/** - * ABICoder prototype should be used to encode/decode solidity params of any type - */ -var ABICoder = function () { -}; - -/** - * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. - * - * @method encodeFunctionSignature - * @param {String|Object} functionName - * @return {String} encoded function name - */ -ABICoder.prototype.encodeFunctionSignature = function (functionName) { - if (_.isObject(functionName)) { - functionName = utils._jsonInterfaceMethodToString(functionName); - } - - return utils.sha3(functionName).slice(0, 10); -}; - -/** - * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. - * - * @method encodeEventSignature - * @param {String|Object} functionName - * @return {String} encoded function name - */ -ABICoder.prototype.encodeEventSignature = function (functionName) { - if (_.isObject(functionName)) { - functionName = utils._jsonInterfaceMethodToString(functionName); - } - - return utils.sha3(functionName); -}; - -/** - * Should be used to encode plain param - * - * @method encodeParameter - * @param {String} type - * @param {Object} param - * @return {String} encoded plain param - */ -ABICoder.prototype.encodeParameter = function (type, param) { - return this.encodeParameters([type], [param]); -}; - -/** - * Should be used to encode list of params - * - * @method encodeParameters - * @param {Array} types - * @param {Array} params - * @return {String} encoded list of params - */ -ABICoder.prototype.encodeParameters = function (types, params) { - return ethersAbiCoder.encode(this.mapTypes(types), params); -}; - -/** - * Map types if simplified format is used - * - * @method mapTypes - * @param {Array} types - * @return {Array} - */ -ABICoder.prototype.mapTypes = function (types) { - var self = this; - var mappedTypes = []; - types.forEach(function (type) { - if (self.isSimplifiedStructFormat(type)) { - var structName = Object.keys(type)[0]; - mappedTypes.push( - Object.assign( - self.mapStructNameAndType(structName), - { - components: self.mapStructToCoderFormat(type[structName]) - } - ) - ); - - return; - } - - mappedTypes.push(type); - }); - - return mappedTypes; -}; - -/** - * Check if type is simplified struct format - * - * @method isSimplifiedStructFormat - * @param {string | Object} type - * @returns {boolean} - */ -ABICoder.prototype.isSimplifiedStructFormat = function (type) { - return typeof type === 'object' && typeof type.components === 'undefined' && typeof type.name === 'undefined'; -}; - -/** - * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used - * - * @method mapStructNameAndType - * @param {string} structName - * @return {{type: string, name: *}} - */ -ABICoder.prototype.mapStructNameAndType = function (structName) { - var type = 'tuple'; - - if (structName.indexOf('[]') > -1) { - type = 'tuple[]'; - structName = structName.slice(0, -2); - } - - return {type: type, name: structName}; -}; - -/** - * Maps the simplified format in to the expected format of the ABICoder - * - * @method mapStructToCoderFormat - * @param {Object} struct - * @return {Array} - */ -ABICoder.prototype.mapStructToCoderFormat = function (struct) { - var self = this; - var components = []; - Object.keys(struct).forEach(function (key) { - if (typeof struct[key] === 'object') { - components.push( - Object.assign( - self.mapStructNameAndType(key), - { - components: self.mapStructToCoderFormat(struct[key]) - } - ) - ); - - return; - } - - components.push({ - name: key, - type: struct[key] - }); - }); - - return components; -}; - -/** - * Encodes a function call from its json interface and parameters. - * - * @method encodeFunctionCall - * @param {Array} jsonInterface - * @param {Array} params - * @return {String} The encoded ABI for this function call - */ -ABICoder.prototype.encodeFunctionCall = function (jsonInterface, params) { - return this.encodeFunctionSignature(jsonInterface) + this.encodeParameters(jsonInterface.inputs, params).replace('0x', ''); -}; - -/** - * Should be used to decode bytes to plain param - * - * @method decodeParameter - * @param {String} type - * @param {String} bytes - * @return {Object} plain param - */ -ABICoder.prototype.decodeParameter = function (type, bytes) { - return this.decodeParameters([type], bytes)[0]; -}; - -/** - * Should be used to decode list of params - * - * @method decodeParameter - * @param {Array} outputs - * @param {String} bytes - * @return {Array} array of plain params - */ -ABICoder.prototype.decodeParameters = function (outputs, bytes) { - if (outputs.length > 0 && (!bytes || bytes === '0x' || bytes === '0X')) { - throw new Error('Returned values aren\'t valid, did it run Out of Gas?'); - } - - var res = ethersAbiCoder.decode(this.mapTypes(outputs), '0x' + bytes.replace(/0x/i, '')); - var returnValue = new Result(); - returnValue.__length__ = 0; - - outputs.forEach(function (output, i) { - var decodedValue = res[returnValue.__length__]; - decodedValue = (decodedValue === '0x') ? null : decodedValue; - - returnValue[i] = decodedValue; - - if (_.isObject(output) && output.name) { - returnValue[output.name] = decodedValue; - } - - returnValue.__length__++; - }); - - return returnValue; -}; - -/** - * Decodes events non- and indexed parameters. - * - * @method decodeLog - * @param {Object} inputs - * @param {String} data - * @param {Array} topics - * @return {Array} array of plain params - */ -ABICoder.prototype.decodeLog = function (inputs, data, topics) { - var _this = this; - topics = _.isArray(topics) ? topics : [topics]; - - data = data || ''; - - var notIndexedInputs = []; - var indexedParams = []; - var topicCount = 0; - - // TODO check for anonymous logs? - - inputs.forEach(function (input, i) { - if (input.indexed) { - indexedParams[i] = (['bool', 'int', 'uint', 'address', 'fixed', 'ufixed'].find(function (staticType) { - return input.type.indexOf(staticType) !== -1; - })) ? _this.decodeParameter(input.type, topics[topicCount]) : topics[topicCount]; - topicCount++; - } else { - notIndexedInputs[i] = input; - } - }); - - - var nonIndexedData = data; - var notIndexedParams = (nonIndexedData) ? this.decodeParameters(notIndexedInputs, nonIndexedData) : []; - - var returnValue = new Result(); - returnValue.__length__ = 0; - - - inputs.forEach(function (res, i) { - returnValue[i] = (res.type === 'string') ? '' : null; - - if (typeof notIndexedParams[i] !== 'undefined') { - returnValue[i] = notIndexedParams[i]; - } - if (typeof indexedParams[i] !== 'undefined') { - returnValue[i] = indexedParams[i]; - } - - if (res.name) { - returnValue[res.name] = returnValue[i]; - } - - returnValue.__length__++; - }); - - return returnValue; -}; - -var coder = new ABICoder(); - -module.exports = coder; - -},{"ethers/utils/abi-coder":357,"underscore":1765,"web3-utils":1835}],1804:[function(require,module,exports){ -(function (Buffer){ -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - -var Bytes = require("./bytes"); -var Nat = require("./nat"); -var elliptic = require("elliptic"); -var rlp = require("./rlp"); -var secp256k1 = new elliptic.ec("secp256k1"); // eslint-disable-line - -var _require = require("./hash"), - keccak256 = _require.keccak256, - keccak256s = _require.keccak256s; - -var create = function create(entropy) { - var innerHex = keccak256(Bytes.concat(Bytes.random(32), entropy || Bytes.random(32))); - var middleHex = Bytes.concat(Bytes.concat(Bytes.random(32), innerHex), Bytes.random(32)); - var outerHex = keccak256(middleHex); - return fromPrivate(outerHex); -}; - -var toChecksum = function toChecksum(address) { - var addressHash = keccak256s(address.slice(2)); - var checksumAddress = "0x"; - for (var i = 0; i < 40; i++) { - checksumAddress += parseInt(addressHash[i + 2], 16) > 7 ? address[i + 2].toUpperCase() : address[i + 2]; - }return checksumAddress; -}; - -var fromPrivate = function fromPrivate(privateKey) { - var buffer = new Buffer(privateKey.slice(2), "hex"); - var ecKey = secp256k1.keyFromPrivate(buffer); - var publicKey = "0x" + ecKey.getPublic(false, 'hex').slice(2); - var publicHash = keccak256(publicKey); - var address = toChecksum("0x" + publicHash.slice(-40)); - return { - address: address, - privateKey: privateKey - }; -}; - -var encodeSignature = function encodeSignature(_ref) { - var _ref2 = _slicedToArray(_ref, 3), - v = _ref2[0], - r = Bytes.pad(32, _ref2[1]), - s = Bytes.pad(32, _ref2[2]); - - return Bytes.flatten([r, s, v]); -}; - -var decodeSignature = function decodeSignature(hex) { - return [Bytes.slice(64, Bytes.length(hex), hex), Bytes.slice(0, 32, hex), Bytes.slice(32, 64, hex)]; -}; - -var makeSigner = function makeSigner(addToV) { - return function (hash, privateKey) { - var signature = secp256k1.keyFromPrivate(new Buffer(privateKey.slice(2), "hex")).sign(new Buffer(hash.slice(2), "hex"), { canonical: true }); - return encodeSignature([Nat.fromString(Bytes.fromNumber(addToV + signature.recoveryParam)), Bytes.pad(32, Bytes.fromNat("0x" + signature.r.toString(16))), Bytes.pad(32, Bytes.fromNat("0x" + signature.s.toString(16)))]); - }; -}; - -var sign = makeSigner(27); // v=27|28 instead of 0|1... - -var recover = function recover(hash, signature) { - var vals = decodeSignature(signature); - var vrs = { v: Bytes.toNumber(vals[0]), r: vals[1].slice(2), s: vals[2].slice(2) }; - var ecPublicKey = secp256k1.recoverPubKey(new Buffer(hash.slice(2), "hex"), vrs, vrs.v < 2 ? vrs.v : 1 - vrs.v % 2); // because odd vals mean v=0... sadly that means v=0 means v=1... I hate that - var publicKey = "0x" + ecPublicKey.encode("hex", false).slice(2); - var publicHash = keccak256(publicKey); - var address = toChecksum("0x" + publicHash.slice(-40)); - return address; -}; - -module.exports = { - create: create, - toChecksum: toChecksum, - fromPrivate: fromPrivate, - sign: sign, - makeSigner: makeSigner, - recover: recover, - encodeSignature: encodeSignature, - decodeSignature: decodeSignature -}; -}).call(this,require("buffer").Buffer) -},{"./bytes":1806,"./hash":1807,"./nat":1808,"./rlp":1809,"buffer":217,"elliptic":282}],1805:[function(require,module,exports){ -arguments[4][332][0].apply(exports,arguments) -},{"dup":332}],1806:[function(require,module,exports){ -arguments[4][333][0].apply(exports,arguments) -},{"./array.js":1805,"dup":333}],1807:[function(require,module,exports){ -arguments[4][334][0].apply(exports,arguments) -},{"dup":334}],1808:[function(require,module,exports){ -var BN = require("bn.js"); -var Bytes = require("./bytes"); - -var fromBN = function fromBN(bn) { - return "0x" + bn.toString("hex"); -}; - -var toBN = function toBN(str) { - return new BN(str.slice(2), 16); -}; - -var fromString = function fromString(str) { - var bn = "0x" + (str.slice(0, 2) === "0x" ? new BN(str.slice(2), 16) : new BN(str, 10)).toString("hex"); - return bn === "0x0" ? "0x" : bn; -}; - -var toEther = function toEther(wei) { - return toNumber(div(wei, fromString("10000000000"))) / 100000000; -}; - -var fromEther = function fromEther(eth) { - return mul(fromNumber(Math.floor(eth * 100000000)), fromString("10000000000")); -}; - -var toString = function toString(a) { - return toBN(a).toString(10); -}; - -var fromNumber = function fromNumber(a) { - return typeof a === "string" ? /^0x/.test(a) ? a : "0x" + a : "0x" + new BN(a).toString("hex"); -}; - -var toNumber = function toNumber(a) { - return toBN(a).toNumber(); -}; - -var toUint256 = function toUint256(a) { - return Bytes.pad(32, a); -}; - -var bin = function bin(method) { - return function (a, b) { - return fromBN(toBN(a)[method](toBN(b))); - }; -}; - -var add = bin("add"); -var mul = bin("mul"); -var div = bin("div"); -var sub = bin("sub"); - -module.exports = { - toString: toString, - fromString: fromString, - toNumber: toNumber, - fromNumber: fromNumber, - toEther: toEther, - fromEther: fromEther, - toUint256: toUint256, - add: add, - mul: mul, - div: div, - sub: sub -}; -},{"./bytes":1806,"bn.js":171}],1809:[function(require,module,exports){ -// The RLP format -// Serialization and deserialization for the BytesTree type, under the following grammar: -// | First byte | Meaning | -// | ---------- | -------------------------------------------------------------------------- | -// | 0 to 127 | HEX(leaf) | -// | 128 to 183 | HEX(length_of_leaf + 128) + HEX(leaf) | -// | 184 to 191 | HEX(length_of_length_of_leaf + 128 + 55) + HEX(length_of_leaf) + HEX(leaf) | -// | 192 to 247 | HEX(length_of_node + 192) + HEX(node) | -// | 248 to 255 | HEX(length_of_length_of_node + 128 + 55) + HEX(length_of_node) + HEX(node) | - -var encode = function encode(tree) { - var padEven = function padEven(str) { - return str.length % 2 === 0 ? str : "0" + str; - }; - - var uint = function uint(num) { - return padEven(num.toString(16)); - }; - - var length = function length(len, add) { - return len < 56 ? uint(add + len) : uint(add + uint(len).length / 2 + 55) + uint(len); - }; - - var dataTree = function dataTree(tree) { - if (typeof tree === "string") { - var hex = tree.slice(2); - var pre = hex.length != 2 || hex >= "80" ? length(hex.length / 2, 128) : ""; - return pre + hex; - } else { - var _hex = tree.map(dataTree).join(""); - var _pre = length(_hex.length / 2, 192); - return _pre + _hex; - } - }; - - return "0x" + dataTree(tree); -}; - -var decode = function decode(hex) { - var i = 2; - - var parseTree = function parseTree() { - if (i >= hex.length) throw ""; - var head = hex.slice(i, i + 2); - return head < "80" ? (i += 2, "0x" + head) : head < "c0" ? parseHex() : parseList(); - }; - - var parseLength = function parseLength() { - var len = parseInt(hex.slice(i, i += 2), 16) % 64; - return len < 56 ? len : parseInt(hex.slice(i, i += (len - 55) * 2), 16); - }; - - var parseHex = function parseHex() { - var len = parseLength(); - return "0x" + hex.slice(i, i += len * 2); - }; - - var parseList = function parseList() { - var lim = parseLength() * 2 + i; - var list = []; - while (i < lim) { - list.push(parseTree()); - }return list; - }; - - try { - return parseTree(); - } catch (e) { - return []; - } -}; - -module.exports = { encode: encode, decode: decode }; -},{}],1810:[function(require,module,exports){ -arguments[4][1777][0].apply(exports,arguments) -},{"./v1":1813,"./v4":1814,"dup":1777}],1811:[function(require,module,exports){ -arguments[4][1778][0].apply(exports,arguments) -},{"dup":1778}],1812:[function(require,module,exports){ -arguments[4][1779][0].apply(exports,arguments) -},{"dup":1779}],1813:[function(require,module,exports){ -arguments[4][1780][0].apply(exports,arguments) -},{"./lib/bytesToUuid":1811,"./lib/rng":1812,"dup":1780}],1814:[function(require,module,exports){ -arguments[4][1781][0].apply(exports,arguments) -},{"./lib/bytesToUuid":1811,"./lib/rng":1812,"dup":1781}],1815:[function(require,module,exports){ -(function (global,Buffer){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file accounts.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require("underscore"); -var core = require('web3-core'); -var Method = require('web3-core-method'); -var Promise = require('any-promise'); -var Account = require("eth-lib/lib/account"); -var Hash = require("eth-lib/lib/hash"); -var RLP = require("eth-lib/lib/rlp"); -var Nat = require("eth-lib/lib/nat"); -var Bytes = require("eth-lib/lib/bytes"); -var cryp = (typeof global === 'undefined') ? require('crypto-browserify') : require('crypto'); -var scrypt = require('./scrypt'); -var uuid = require('uuid'); -var utils = require('web3-utils'); -var helpers = require('web3-core-helpers'); - -var isNot = function(value) { - return (_.isUndefined(value) || _.isNull(value)); -}; - -var trimLeadingZero = function (hex) { - while (hex && hex.startsWith('0x0')) { - hex = '0x' + hex.slice(3); - } - return hex; -}; - -var makeEven = function (hex) { - if(hex.length % 2 === 1) { - hex = hex.replace('0x', '0x0'); - } - return hex; -}; - - -var Accounts = function Accounts() { - var _this = this; - - // sets _requestmanager - core.packageInit(this, arguments); - - // remove unecessary core functions - delete this.BatchRequest; - delete this.extend; - - var _ethereumCall = [ - new Method({ - name: 'getId', - call: 'net_version', - params: 0, - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'getGasPrice', - call: 'eth_gasPrice', - params: 0 - }), - new Method({ - name: 'getTransactionCount', - call: 'eth_getTransactionCount', - params: 2, - inputFormatter: [function (address) { - if (utils.isAddress(address)) { - return address; - } else { - throw new Error('Address '+ address +' is not a valid address to get the "transactionCount".'); - } - }, function () { return 'latest'; }] - }) - ]; - // attach methods to this._ethereumCall - this._ethereumCall = {}; - _.each(_ethereumCall, function (method) { - method.attachToObject(_this._ethereumCall); - method.setRequestManager(_this._requestManager); - }); - - - this.wallet = new Wallet(this); -}; - -Accounts.prototype._addAccountFunctions = function (account) { - var _this = this; - - // add sign functions - account.signTransaction = function signTransaction(tx, callback) { - return _this.signTransaction(tx, account.privateKey, callback); - }; - account.sign = function sign(data) { - return _this.sign(data, account.privateKey); - }; - - account.encrypt = function encrypt(password, options) { - return _this.encrypt(account.privateKey, password, options); - }; - - - return account; -}; - -Accounts.prototype.create = function create(entropy) { - return this._addAccountFunctions(Account.create(entropy || utils.randomHex(32))); -}; - -Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(privateKey) { - return this._addAccountFunctions(Account.fromPrivate(privateKey)); -}; - -Accounts.prototype.signTransaction = function signTransaction(tx, privateKey, callback) { - var _this = this, - error = false, - result; - - callback = callback || function () {}; - - if (!tx) { - error = new Error('No transaction object given!'); - - callback(error); - return Promise.reject(error); - } - - function signed (tx) { - - if (!tx.gas && !tx.gasLimit) { - error = new Error('"gas" is missing'); - } - - if (tx.nonce < 0 || - tx.gas < 0 || - tx.gasPrice < 0 || - tx.chainId < 0) { - error = new Error('Gas, gasPrice, nonce or chainId is lower than 0'); - } - - if (error) { - callback(error); - return Promise.reject(error); - } - - try { - tx = helpers.formatters.inputCallFormatter(tx); - - var transaction = tx; - transaction.to = tx.to || '0x'; - transaction.data = tx.data || '0x'; - transaction.value = tx.value || '0x'; - transaction.chainId = utils.numberToHex(tx.chainId); - - var rlpEncoded = RLP.encode([ - Bytes.fromNat(transaction.nonce), - Bytes.fromNat(transaction.gasPrice), - Bytes.fromNat(transaction.gas), - transaction.to.toLowerCase(), - Bytes.fromNat(transaction.value), - transaction.data, - Bytes.fromNat(transaction.chainId || "0x1"), - "0x", - "0x"]); - - - var hash = Hash.keccak256(rlpEncoded); - - var signature = Account.makeSigner(Nat.toNumber(transaction.chainId || "0x1") * 2 + 35)(Hash.keccak256(rlpEncoded), privateKey); - - var rawTx = RLP.decode(rlpEncoded).slice(0, 6).concat(Account.decodeSignature(signature)); - - rawTx[6] = makeEven(trimLeadingZero(rawTx[6])); - rawTx[7] = makeEven(trimLeadingZero(rawTx[7])); - rawTx[8] = makeEven(trimLeadingZero(rawTx[8])); - - var rawTransaction = RLP.encode(rawTx); - - var values = RLP.decode(rawTransaction); - result = { - messageHash: hash, - v: trimLeadingZero(values[6]), - r: trimLeadingZero(values[7]), - s: trimLeadingZero(values[8]), - rawTransaction: rawTransaction - }; - - } catch(e) { - callback(e); - return Promise.reject(e); - } - - callback(null, result); - return result; - } - - // Resolve immediately if nonce, chainId and price are provided - if (tx.nonce !== undefined && tx.chainId !== undefined && tx.gasPrice !== undefined) { - return Promise.resolve(signed(tx)); - } - - - // Otherwise, get the missing info from the Ethereum Node - return Promise.all([ - isNot(tx.chainId) ? _this._ethereumCall.getId() : tx.chainId, - isNot(tx.gasPrice) ? _this._ethereumCall.getGasPrice() : tx.gasPrice, - isNot(tx.nonce) ? _this._ethereumCall.getTransactionCount(_this.privateKeyToAccount(privateKey).address) : tx.nonce - ]).then(function (args) { - if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) { - throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+ JSON.stringify(args)); - } - return signed(_.extend(tx, {chainId: args[0], gasPrice: args[1], nonce: args[2]})); - }); -}; - -/* jshint ignore:start */ -Accounts.prototype.recoverTransaction = function recoverTransaction(rawTx) { - var values = RLP.decode(rawTx); - var signature = Account.encodeSignature(values.slice(6,9)); - var recovery = Bytes.toNumber(values[6]); - var extraData = recovery < 35 ? [] : [Bytes.fromNumber((recovery - 35) >> 1), "0x", "0x"]; - var signingData = values.slice(0,6).concat(extraData); - var signingDataHex = RLP.encode(signingData); - return Account.recover(Hash.keccak256(signingDataHex), signature); -}; -/* jshint ignore:end */ - -Accounts.prototype.hashMessage = function hashMessage(data) { - var message = utils.isHexStrict(data) ? utils.hexToBytes(data) : data; - var messageBuffer = Buffer.from(message); - var preamble = "\x19Ethereum Signed Message:\n" + message.length; - var preambleBuffer = Buffer.from(preamble); - var ethMessage = Buffer.concat([preambleBuffer, messageBuffer]); - return Hash.keccak256s(ethMessage); -}; - -Accounts.prototype.sign = function sign(data, privateKey) { - var hash = this.hashMessage(data); - var signature = Account.sign(hash, privateKey); - var vrs = Account.decodeSignature(signature); - return { - message: data, - messageHash: hash, - v: vrs[0], - r: vrs[1], - s: vrs[2], - signature: signature - }; -}; - -Accounts.prototype.recover = function recover(message, signature, preFixed) { - var args = [].slice.apply(arguments); - - - if (_.isObject(message)) { - return this.recover(message.messageHash, Account.encodeSignature([message.v, message.r, message.s]), true); - } - - if (!preFixed) { - message = this.hashMessage(message); - } - - if (args.length >= 4) { - preFixed = args.slice(-1)[0]; - preFixed = _.isBoolean(preFixed) ? !!preFixed : false; - - return this.recover(message, Account.encodeSignature(args.slice(1, 4)), preFixed); // v, r, s - } - return Account.recover(message, signature); -}; - -// Taken from https://github.com/ethereumjs/ethereumjs-wallet -Accounts.prototype.decrypt = function (v3Keystore, password, nonStrict) { - /* jshint maxcomplexity: 10 */ - - if(!_.isString(password)) { - throw new Error('No password given.'); - } - - var json = (_.isObject(v3Keystore)) ? v3Keystore : JSON.parse(nonStrict ? v3Keystore.toLowerCase() : v3Keystore); - - if (json.version !== 3) { - throw new Error('Not a valid V3 wallet'); - } - - var derivedKey; - var kdfparams; - if (json.crypto.kdf === 'scrypt') { - kdfparams = json.crypto.kdfparams; - - // FIXME: support progress reporting callback - derivedKey = scrypt(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); - } else if (json.crypto.kdf === 'pbkdf2') { - kdfparams = json.crypto.kdfparams; - - if (kdfparams.prf !== 'hmac-sha256') { - throw new Error('Unsupported parameters to PBKDF2'); - } - - derivedKey = cryp.pbkdf2Sync(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); - } else { - throw new Error('Unsupported key derivation scheme'); - } - - var ciphertext = Buffer.from(json.crypto.ciphertext, 'hex'); - - var mac = utils.sha3(Buffer.concat([ derivedKey.slice(16, 32), ciphertext ])).replace('0x',''); - if (mac !== json.crypto.mac) { - throw new Error('Key derivation failed - possibly wrong password'); - } - - var decipher = cryp.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), Buffer.from(json.crypto.cipherparams.iv, 'hex')); - var seed = '0x'+ Buffer.concat([ decipher.update(ciphertext), decipher.final() ]).toString('hex'); - - return this.privateKeyToAccount(seed); -}; - -Accounts.prototype.encrypt = function (privateKey, password, options) { - /* jshint maxcomplexity: 20 */ - var account = this.privateKeyToAccount(privateKey); - - options = options || {}; - var salt = options.salt || cryp.randomBytes(32); - var iv = options.iv || cryp.randomBytes(16); - - var derivedKey; - var kdf = options.kdf || 'scrypt'; - var kdfparams = { - dklen: options.dklen || 32, - salt: salt.toString('hex') - }; - - if (kdf === 'pbkdf2') { - kdfparams.c = options.c || 262144; - kdfparams.prf = 'hmac-sha256'; - derivedKey = cryp.pbkdf2Sync(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); - } else if (kdf === 'scrypt') { - // FIXME: support progress reporting callback - kdfparams.n = options.n || 8192; // 2048 4096 8192 16384 - kdfparams.r = options.r || 8; - kdfparams.p = options.p || 1; - derivedKey = scrypt(Buffer.from(password), Buffer.from(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); - } else { - throw new Error('Unsupported kdf'); - } - - var cipher = cryp.createCipheriv(options.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); - if (!cipher) { - throw new Error('Unsupported cipher'); - } - - var ciphertext = Buffer.concat([ cipher.update(Buffer.from(account.privateKey.replace('0x',''), 'hex')), cipher.final() ]); - - var mac = utils.sha3(Buffer.concat([ derivedKey.slice(16, 32), Buffer.from(ciphertext, 'hex') ])).replace('0x',''); - - return { - version: 3, - id: uuid.v4({ random: options.uuid || cryp.randomBytes(16) }), - address: account.address.toLowerCase().replace('0x',''), - crypto: { - ciphertext: ciphertext.toString('hex'), - cipherparams: { - iv: iv.toString('hex') - }, - cipher: options.cipher || 'aes-128-ctr', - kdf: kdf, - kdfparams: kdfparams, - mac: mac.toString('hex') - } - }; -}; - - -// Note: this is trying to follow closely the specs on -// http://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html - -function Wallet(accounts) { - this._accounts = accounts; - this.length = 0; - this.defaultKeyName = "web3js_wallet"; -} - -Wallet.prototype._findSafeIndex = function (pointer) { - pointer = pointer || 0; - if (_.has(this, pointer)) { - return this._findSafeIndex(pointer + 1); - } else { - return pointer; - } -}; - -Wallet.prototype._currentIndexes = function () { - var keys = Object.keys(this); - var indexes = keys - .map(function(key) { return parseInt(key); }) - .filter(function(n) { return (n < 9e20); }); - - return indexes; -}; - -Wallet.prototype.create = function (numberOfAccounts, entropy) { - for (var i = 0; i < numberOfAccounts; ++i) { - this.add(this._accounts.create(entropy).privateKey); - } - return this; -}; - -Wallet.prototype.add = function (account) { - - if (_.isString(account)) { - account = this._accounts.privateKeyToAccount(account); - } - if (!this[account.address]) { - account = this._accounts.privateKeyToAccount(account.privateKey); - account.index = this._findSafeIndex(); - - this[account.index] = account; - this[account.address] = account; - this[account.address.toLowerCase()] = account; - - this.length++; - - return account; - } else { - return this[account.address]; - } -}; - -Wallet.prototype.remove = function (addressOrIndex) { - var account = this[addressOrIndex]; - - if (account && account.address) { - // address - this[account.address].privateKey = null; - delete this[account.address]; - // address lowercase - this[account.address.toLowerCase()].privateKey = null; - delete this[account.address.toLowerCase()]; - // index - this[account.index].privateKey = null; - delete this[account.index]; - - this.length--; - - return true; - } else { - return false; - } -}; - -Wallet.prototype.clear = function () { - var _this = this; - var indexes = this._currentIndexes(); - - indexes.forEach(function(index) { - _this.remove(index); - }); - - return this; -}; - -Wallet.prototype.encrypt = function (password, options) { - var _this = this; - var indexes = this._currentIndexes(); - - var accounts = indexes.map(function(index) { - return _this[index].encrypt(password, options); - }); - - return accounts; -}; - - -Wallet.prototype.decrypt = function (encryptedWallet, password) { - var _this = this; - - encryptedWallet.forEach(function (keystore) { - var account = _this._accounts.decrypt(keystore, password); - - if (account) { - _this.add(account); - } else { - throw new Error('Couldn\'t decrypt accounts. Password wrong?'); - } - }); - - return this; -}; - -Wallet.prototype.save = function (password, keyName) { - localStorage.setItem(keyName || this.defaultKeyName, JSON.stringify(this.encrypt(password))); - - return true; -}; - -Wallet.prototype.load = function (password, keyName) { - var keystore = localStorage.getItem(keyName || this.defaultKeyName); - - if (keystore) { - try { - keystore = JSON.parse(keystore); - } catch(e) { - - } - } - - return this.decrypt(keystore || [], password); -}; - -if (typeof localStorage === 'undefined') { - delete Wallet.prototype.save; - delete Wallet.prototype.load; -} - - -module.exports = Accounts; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./scrypt":1816,"any-promise":51,"buffer":217,"crypto":236,"crypto-browserify":236,"eth-lib/lib/account":1804,"eth-lib/lib/bytes":1806,"eth-lib/lib/hash":1807,"eth-lib/lib/nat":1808,"eth-lib/lib/rlp":1809,"underscore":1765,"uuid":1810,"web3-core":1802,"web3-core-helpers":1792,"web3-core-method":1793,"web3-utils":1835}],1816:[function(require,module,exports){ -(function (process){ -var scryptsy = require('scryptsy'); - -var scrypt; - -var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; -if (isNode) { - var NODE_MIN_VER_WITH_BUILTIN_SCRYPT = '10.5.0'; - var NODE_MIN_VER_INCOMPAT_SCRYPT_PKG = '12.0.0'; - var semver = require('semver'); - var useNodeBuiltin = isNode && semver.Range('>=' + NODE_MIN_VER_WITH_BUILTIN_SCRYPT).test(process.version); - - var tryScryptPkg = (function() { - var scryptPkg; - return function() { - if (scryptPkg !== undefined) { return scryptPkg; } - try { - scryptPkg = (function(m) { return require(m); })('scrypt'); - } catch (e) { - if (/was compiled against a different/.test(e.message)) { - throw e; - } - scryptPkg = null; - } - return scryptPkg; - }; - })(); - - var canImprove = function(nodeVer) { - return 'can improve web3\'s peformance when running Node.js versions older than ' + nodeVer + ' by installing the (deprecated) scrypt package in your project'; - }; - - if (useNodeBuiltin) { - var crypto = require('crypto'); - var fallbackCount = 0; - scrypt = function(key, salt, N, r, p, dkLen) { - try { - return crypto.scryptSync(key, salt, dkLen, {N: N, r: r, p: p}); - } catch (e) { - if (/scrypt:memory limit exceeded/.test(e.message)) { - var scryptPkg = tryScryptPkg(); - if (scryptPkg) { - return scryptPkg.hashSync(key, {N: N, r: r, p: p}, dkLen, salt); - } - fallbackCount += 1; - console.warn( - '\x1b[33m%s\x1b[0m', - 'Memory limit exceeded for Node\'s built-in crypto.scrypt, falling back to scryptsy (times: ' + fallbackCount + '), if this happens frequently you ' + canImprove(NODE_MIN_VER_INCOMPAT_SCRYPT_PKG) - ); - return scryptsy(key, salt, N, r, p, dkLen); - } - throw e; - } - }; - } else { - var scryptPkg = tryScryptPkg(); - if (scryptPkg) { - scrypt = function(key, salt, N, r, p, dkLen) { - return scryptPkg.hashSync(key, {N: N, r: r, p: p}, dkLen, salt); - }; - } else { - console.warn( - '\x1b[33m%s\x1b[0m', - 'You ' + canImprove(NODE_MIN_VER_WITH_BUILTIN_SCRYPT) - ); - } - } -} - -scrypt = scrypt || scryptsy; - -module.exports = scrypt; - -}).call(this,require('_process')) -},{"_process":1438,"crypto":236,"scryptsy":1596,"semver":1613}],1817:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file contract.js - * - * To initialize a contract use: - * - * var Contract = require('web3-eth-contract'); - * Contract.setProvider('ws://localhost:8546'); - * var contract = new Contract(abi, address, ...); - * - * @author Fabian Vogelsteller - * @date 2017 - */ - - -"use strict"; - - -var _ = require('underscore'); -var core = require('web3-core'); -var Method = require('web3-core-method'); -var utils = require('web3-utils'); -var Subscription = require('web3-core-subscriptions').subscription; -var formatters = require('web3-core-helpers').formatters; -var errors = require('web3-core-helpers').errors; -var promiEvent = require('web3-core-promievent'); -var abi = require('web3-eth-abi'); - - -/** - * Should be called to create new contract instance - * - * @method Contract - * @constructor - * @param {Array} jsonInterface - * @param {String} address - * @param {Object} options - */ -var Contract = function Contract(jsonInterface, address, options) { - var _this = this, - args = Array.prototype.slice.call(arguments); - - if(!(this instanceof Contract)) { - throw new Error('Please use the "new" keyword to instantiate a web3.eth.contract() object!'); - } - - // sets _requestmanager - core.packageInit(this, [this.constructor.currentProvider]); - - this.clearSubscriptions = this._requestManager.clearSubscriptions; - - - - if(!jsonInterface || !(Array.isArray(jsonInterface))) { - throw new Error('You must provide the json interface of the contract when instantiating a contract object.'); - } - - - - // create the options object - this.options = {}; - - var lastArg = args[args.length - 1]; - if(_.isObject(lastArg) && !_.isArray(lastArg)) { - options = lastArg; - - this.options = _.extend(this.options, this._getOrSetDefaultOptions(options)); - if(_.isObject(address)) { - address = null; - } - } - - // set address - Object.defineProperty(this.options, 'address', { - set: function(value){ - if(value) { - _this._address = utils.toChecksumAddress(formatters.inputAddressFormatter(value)); - } - }, - get: function(){ - return _this._address; - }, - enumerable: true - }); - - // add method and event signatures, when the jsonInterface gets set - Object.defineProperty(this.options, 'jsonInterface', { - set: function(value){ - _this.methods = {}; - _this.events = {}; - - _this._jsonInterface = value.map(function(method) { - var func, - funcName; - - // make constant and payable backwards compatible - method.constant = (method.stateMutability === "view" || method.stateMutability === "pure" || method.constant); - method.payable = (method.stateMutability === "payable" || method.payable); - - - if (method.name) { - funcName = utils._jsonInterfaceMethodToString(method); - } - - - // function - if (method.type === 'function') { - method.signature = abi.encodeFunctionSignature(funcName); - func = _this._createTxObject.bind({ - method: method, - parent: _this - }); - - - // add method only if not one already exists - if(!_this.methods[method.name]) { - _this.methods[method.name] = func; - } else { - var cascadeFunc = _this._createTxObject.bind({ - method: method, - parent: _this, - nextMethod: _this.methods[method.name] - }); - _this.methods[method.name] = cascadeFunc; - } - - // definitely add the method based on its signature - _this.methods[method.signature] = func; - - // add method by name - _this.methods[funcName] = func; - - - // event - } else if (method.type === 'event') { - method.signature = abi.encodeEventSignature(funcName); - var event = _this._on.bind(_this, method.signature); - - // add method only if not already exists - if(!_this.events[method.name] || _this.events[method.name].name === 'bound ') - _this.events[method.name] = event; - - // definitely add the method based on its signature - _this.events[method.signature] = event; - - // add event by name - _this.events[funcName] = event; - } - - - return method; - }); - - // add allEvents - _this.events.allEvents = _this._on.bind(_this, 'allevents'); - - return _this._jsonInterface; - }, - get: function(){ - return _this._jsonInterface; - }, - enumerable: true - }); - - // get default account from the Class - var defaultAccount = this.constructor.defaultAccount; - var defaultBlock = this.constructor.defaultBlock || 'latest'; - - Object.defineProperty(this, 'defaultAccount', { - get: function () { - return defaultAccount; - }, - set: function (val) { - if(val) { - defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); - } - - return val; - }, - enumerable: true - }); - Object.defineProperty(this, 'defaultBlock', { - get: function () { - return defaultBlock; - }, - set: function (val) { - defaultBlock = val; - - return val; - }, - enumerable: true - }); - - // properties - this.methods = {}; - this.events = {}; - - this._address = null; - this._jsonInterface = []; - - // set getter/setter properties - this.options.address = address; - this.options.jsonInterface = jsonInterface; - -}; - -Contract.setProvider = function(provider, accounts) { - // Contract.currentProvider = provider; - core.packageInit(this, [provider]); - - this._ethAccounts = accounts; -}; - - -/** - * Get the callback and modiufy the array if necessary - * - * @method _getCallback - * @param {Array} args - * @return {Function} the callback - */ -Contract.prototype._getCallback = function getCallback(args) { - if (args && _.isFunction(args[args.length - 1])) { - return args.pop(); // modify the args array! - } -}; - -/** - * Checks that no listener with name "newListener" or "removeListener" is added. - * - * @method _checkListener - * @param {String} type - * @param {String} event - * @return {Object} the contract instance - */ -Contract.prototype._checkListener = function(type, event){ - if(event === type) { - throw new Error('The event "'+ type +'" is a reserved event name, you can\'t use it.'); - } -}; - - -/** - * Use default values, if options are not available - * - * @method _getOrSetDefaultOptions - * @param {Object} options the options gived by the user - * @return {Object} the options with gaps filled by defaults - */ -Contract.prototype._getOrSetDefaultOptions = function getOrSetDefaultOptions(options) { - var gasPrice = options.gasPrice ? String(options.gasPrice): null; - var from = options.from ? utils.toChecksumAddress(formatters.inputAddressFormatter(options.from)) : null; - - options.data = options.data || this.options.data; - - options.from = from || this.options.from; - options.gasPrice = gasPrice || this.options.gasPrice; - options.gas = options.gas || options.gasLimit || this.options.gas; - - // TODO replace with only gasLimit? - delete options.gasLimit; - - return options; -}; - - -/** - * Should be used to encode indexed params and options to one final object - * - * @method _encodeEventABI - * @param {Object} event - * @param {Object} options - * @return {Object} everything combined together and encoded - */ -Contract.prototype._encodeEventABI = function (event, options) { - options = options || {}; - var filter = options.filter || {}, - result = {}; - - ['fromBlock', 'toBlock'].filter(function (f) { - return options[f] !== undefined; - }).forEach(function (f) { - result[f] = formatters.inputBlockNumberFormatter(options[f]); - }); - - // use given topics - if(_.isArray(options.topics)) { - result.topics = options.topics; - - // create topics based on filter - } else { - - result.topics = []; - - // add event signature - if (event && !event.anonymous && event.name !== 'ALLEVENTS') { - result.topics.push(event.signature); - } - - // add event topics (indexed arguments) - if (event.name !== 'ALLEVENTS') { - var indexedTopics = event.inputs.filter(function (i) { - return i.indexed === true; - }).map(function (i) { - var value = filter[i.name]; - if (!value) { - return null; - } - - // TODO: https://github.com/ethereum/web3.js/issues/344 - // TODO: deal properly with components - - if (_.isArray(value)) { - return value.map(function (v) { - return abi.encodeParameter(i.type, v); - }); - } - return abi.encodeParameter(i.type, value); - }); - - result.topics = result.topics.concat(indexedTopics); - } - - if(!result.topics.length) - delete result.topics; - } - - if(this.options.address) { - result.address = this.options.address.toLowerCase(); - } - - return result; -}; - -/** - * Should be used to decode indexed params and options - * - * @method _decodeEventABI - * @param {Object} data - * @return {Object} result object with decoded indexed && not indexed params - */ -Contract.prototype._decodeEventABI = function (data) { - var event = this; - - data.data = data.data || ''; - data.topics = data.topics || []; - var result = formatters.outputLogFormatter(data); - - // if allEvents get the right event - if(event.name === 'ALLEVENTS') { - event = event.jsonInterface.find(function (intf) { - return (intf.signature === data.topics[0]); - }) || {anonymous: true}; - } - - // create empty inputs if none are present (e.g. anonymous events on allEvents) - event.inputs = event.inputs || []; - - - var argTopics = event.anonymous ? data.topics : data.topics.slice(1); - - result.returnValues = abi.decodeLog(event.inputs, data.data, argTopics); - delete result.returnValues.__length__; - - // add name - result.event = event.name; - - // add signature - result.signature = (event.anonymous || !data.topics[0]) ? null : data.topics[0]; - - // move the data and topics to "raw" - result.raw = { - data: result.data, - topics: result.topics - }; - delete result.data; - delete result.topics; - - - return result; -}; - -/** - * Encodes an ABI for a method, including signature or the method. - * Or when constructor encodes only the constructor parameters. - * - * @method _encodeMethodABI - * @param {Mixed} args the arguments to encode - * @param {String} the encoded ABI - */ -Contract.prototype._encodeMethodABI = function _encodeMethodABI() { - var methodSignature = this._method.signature, - args = this.arguments || []; - - var signature = false, - paramsABI = this._parent.options.jsonInterface.filter(function (json) { - return ((methodSignature === 'constructor' && json.type === methodSignature) || - ((json.signature === methodSignature || json.signature === methodSignature.replace('0x','') || json.name === methodSignature) && json.type === 'function')); - }).map(function (json) { - var inputLength = (_.isArray(json.inputs)) ? json.inputs.length : 0; - - if (inputLength !== args.length) { - throw new Error('The number of arguments is not matching the methods required number. You need to pass '+ inputLength +' arguments.'); - } - - if (json.type === 'function') { - signature = json.signature; - } - return _.isArray(json.inputs) ? json.inputs : []; - }).map(function (inputs) { - return abi.encodeParameters(inputs, args).replace('0x',''); - })[0] || ''; - - // return constructor - if(methodSignature === 'constructor') { - if(!this._deployData) - throw new Error('The contract has no contract data option set. This is necessary to append the constructor parameters.'); - - return this._deployData + paramsABI; - - // return method - } else { - - var returnValue = (signature) ? signature + paramsABI : paramsABI; - - if(!returnValue) { - throw new Error('Couldn\'t find a matching contract method named "'+ this._method.name +'".'); - } else { - return returnValue; - } - } - -}; - - -/** - * Decode method return values - * - * @method _decodeMethodReturn - * @param {Array} outputs - * @param {String} returnValues - * @return {Object} decoded output return values - */ -Contract.prototype._decodeMethodReturn = function (outputs, returnValues) { - if (!returnValues) { - return null; - } - - returnValues = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; - var result = abi.decodeParameters(outputs, returnValues); - - if (result.__length__ === 1) { - return result[0]; - } else { - delete result.__length__; - return result; - } -}; - - -/** - * Deploys a contract and fire events based on its state: transactionHash, receipt - * - * All event listeners will be removed, once the last possible event is fired ("error", or "receipt") - * - * @method deploy - * @param {Object} options - * @param {Function} callback - * @return {Object} EventEmitter possible events are "error", "transactionHash" and "receipt" - */ -Contract.prototype.deploy = function(options, callback){ - - options = options || {}; - - options.arguments = options.arguments || []; - options = this._getOrSetDefaultOptions(options); - - - // return error, if no "data" is specified - if(!options.data) { - return utils._fireError(new Error('No "data" specified in neither the given options, nor the default options.'), null, null, callback); - } - - var constructor = _.find(this.options.jsonInterface, function (method) { - return (method.type === 'constructor'); - }) || {}; - constructor.signature = 'constructor'; - - return this._createTxObject.apply({ - method: constructor, - parent: this, - deployData: options.data, - _ethAccounts: this.constructor._ethAccounts - }, options.arguments); - -}; - -/** - * Gets the event signature and outputformatters - * - * @method _generateEventOptions - * @param {Object} event - * @param {Object} options - * @param {Function} callback - * @return {Object} the event options object - */ -Contract.prototype._generateEventOptions = function() { - var args = Array.prototype.slice.call(arguments); - - // get the callback - var callback = this._getCallback(args); - - // get the options - var options = (_.isObject(args[args.length - 1])) ? args.pop() : {}; - - var event = (_.isString(args[0])) ? args[0] : 'allevents'; - event = (event.toLowerCase() === 'allevents') ? { - name: 'ALLEVENTS', - jsonInterface: this.options.jsonInterface - } : this.options.jsonInterface.find(function (json) { - return (json.type === 'event' && (json.name === event || json.signature === '0x'+ event.replace('0x',''))); - }); - - if (!event) { - throw new Error('Event "' + event.name + '" doesn\'t exist in this contract.'); - } - - if (!utils.isAddress(this.options.address)) { - throw new Error('This contract object doesn\'t have address set yet, please set an address first.'); - } - - return { - params: this._encodeEventABI(event, options), - event: event, - callback: callback - }; -}; - -/** - * Adds event listeners and creates a subscription, and remove it once its fired. - * - * @method clone - * @return {Object} the event subscription - */ -Contract.prototype.clone = function() { - return new this.constructor(this.options.jsonInterface, this.options.address, this.options); -}; - - -/** - * Adds event listeners and creates a subscription, and remove it once its fired. - * - * @method once - * @param {String} event - * @param {Object} options - * @param {Function} callback - * @return {Object} the event subscription - */ -Contract.prototype.once = function(event, options, callback) { - var args = Array.prototype.slice.call(arguments); - - // get the callback - callback = this._getCallback(args); - - if (!callback) { - throw new Error('Once requires a callback as the second parameter.'); - } - - // don't allow fromBlock - if (options) - delete options.fromBlock; - - // don't return as once shouldn't provide "on" - this._on(event, options, function (err, res, sub) { - sub.unsubscribe(); - if(_.isFunction(callback)){ - callback(err, res, sub); - } - }); - - return undefined; -}; - -/** - * Adds event listeners and creates a subscription. - * - * @method _on - * @param {String} event - * @param {Object} options - * @param {Function} callback - * @return {Object} the event subscription - */ -Contract.prototype._on = function(){ - var subOptions = this._generateEventOptions.apply(this, arguments); - - - // prevent the event "newListener" and "removeListener" from being overwritten - this._checkListener('newListener', subOptions.event.name, subOptions.callback); - this._checkListener('removeListener', subOptions.event.name, subOptions.callback); - - // TODO check if listener already exists? and reuse subscription if options are the same. - - // create new subscription - var subscription = new Subscription({ - subscription: { - params: 1, - inputFormatter: [formatters.inputLogFormatter], - outputFormatter: this._decodeEventABI.bind(subOptions.event), - // DUBLICATE, also in web3-eth - subscriptionHandler: function (output) { - if(output.removed) { - this.emit('changed', output); - } else { - this.emit('data', output); - } - - if (_.isFunction(this.callback)) { - this.callback(null, output, this); - } - } - }, - type: 'eth', - requestManager: this._requestManager - }); - subscription.subscribe('logs', subOptions.params, subOptions.callback || function () {}); - - return subscription; -}; - -/** - * Get past events from contracts - * - * @method getPastEvents - * @param {String} event - * @param {Object} options - * @param {Function} callback - * @return {Object} the promievent - */ -Contract.prototype.getPastEvents = function(){ - var subOptions = this._generateEventOptions.apply(this, arguments); - - var getPastLogs = new Method({ - name: 'getPastLogs', - call: 'eth_getLogs', - params: 1, - inputFormatter: [formatters.inputLogFormatter], - outputFormatter: this._decodeEventABI.bind(subOptions.event) - }); - getPastLogs.setRequestManager(this._requestManager); - var call = getPastLogs.buildCall(); - - getPastLogs = null; - - return call(subOptions.params, subOptions.callback); -}; - - -/** - * returns the an object with call, send, estimate functions - * - * @method _createTxObject - * @returns {Object} an object with functions to call the methods - */ -Contract.prototype._createTxObject = function _createTxObject(){ - var args = Array.prototype.slice.call(arguments); - var txObject = {}; - - if(this.method.type === 'function') { - - txObject.call = this.parent._executeMethod.bind(txObject, 'call'); - txObject.call.request = this.parent._executeMethod.bind(txObject, 'call', true); // to make batch requests - - } - - txObject.send = this.parent._executeMethod.bind(txObject, 'send'); - txObject.send.request = this.parent._executeMethod.bind(txObject, 'send', true); // to make batch requests - txObject.encodeABI = this.parent._encodeMethodABI.bind(txObject); - txObject.estimateGas = this.parent._executeMethod.bind(txObject, 'estimate'); - - if (args && this.method.inputs && args.length !== this.method.inputs.length) { - if (this.nextMethod) { - return this.nextMethod.apply(null, args); - } - throw errors.InvalidNumberOfParams(args.length, this.method.inputs.length, this.method.name); - } - - txObject.arguments = args || []; - txObject._method = this.method; - txObject._parent = this.parent; - txObject._ethAccounts = this.parent.constructor._ethAccounts || this._ethAccounts; - - if(this.deployData) { - txObject._deployData = this.deployData; - } - - return txObject; -}; - - -/** - * Generates the options for the execute call - * - * @method _processExecuteArguments - * @param {Array} args - * @param {Promise} defer - */ -Contract.prototype._processExecuteArguments = function _processExecuteArguments(args, defer) { - var processedArgs = {}; - - processedArgs.type = args.shift(); - - // get the callback - processedArgs.callback = this._parent._getCallback(args); - - // get block number to use for call - if(processedArgs.type === 'call' && args[args.length - 1] !== true && (_.isString(args[args.length - 1]) || isFinite(args[args.length - 1]))) - processedArgs.defaultBlock = args.pop(); - - // get the options - processedArgs.options = (_.isObject(args[args.length - 1])) ? args.pop() : {}; - - // get the generateRequest argument for batch requests - processedArgs.generateRequest = (args[args.length - 1] === true)? args.pop() : false; - - processedArgs.options = this._parent._getOrSetDefaultOptions(processedArgs.options); - processedArgs.options.data = this.encodeABI(); - - // add contract address - if(!this._deployData && !utils.isAddress(this._parent.options.address)) - throw new Error('This contract object doesn\'t have address set yet, please set an address first.'); - - if(!this._deployData) - processedArgs.options.to = this._parent.options.address; - - // return error, if no "data" is specified - if(!processedArgs.options.data) - return utils._fireError(new Error('Couldn\'t find a matching contract method, or the number of parameters is wrong.'), defer.eventEmitter, defer.reject, processedArgs.callback); - - return processedArgs; -}; - -/** - * Executes a call, transact or estimateGas on a contract function - * - * @method _executeMethod - * @param {String} type the type this execute function should execute - * @param {Boolean} makeRequest if true, it simply returns the request parameters, rather than executing it - */ -Contract.prototype._executeMethod = function _executeMethod(){ - var _this = this, - args = this._parent._processExecuteArguments.call(this, Array.prototype.slice.call(arguments), defer), - defer = promiEvent((args.type !== 'send')), - ethAccounts = _this.constructor._ethAccounts || _this._ethAccounts; - - // simple return request for batch requests - if(args.generateRequest) { - - var payload = { - params: [formatters.inputCallFormatter.call(this._parent, args.options)], - callback: args.callback - }; - - if(args.type === 'call') { - payload.params.push(formatters.inputDefaultBlockNumberFormatter.call(this._parent, args.defaultBlock)); - payload.method = 'eth_call'; - payload.format = this._parent._decodeMethodReturn.bind(null, this._method.outputs); - } else { - payload.method = 'eth_sendTransaction'; - } - - return payload; - - } else { - - switch (args.type) { - case 'estimate': - - var estimateGas = (new Method({ - name: 'estimateGas', - call: 'eth_estimateGas', - params: 1, - inputFormatter: [formatters.inputCallFormatter], - outputFormatter: utils.hexToNumber, - requestManager: _this._parent._requestManager, - accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) - defaultAccount: _this._parent.defaultAccount, - defaultBlock: _this._parent.defaultBlock - })).createFunction(); - - return estimateGas(args.options, args.callback); - - case 'call': - - // TODO check errors: missing "from" should give error on deploy and send, call ? - - var call = (new Method({ - name: 'call', - call: 'eth_call', - params: 2, - inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter], - // add output formatter for decoding - outputFormatter: function (result) { - return _this._parent._decodeMethodReturn(_this._method.outputs, result); - }, - requestManager: _this._parent._requestManager, - accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) - defaultAccount: _this._parent.defaultAccount, - defaultBlock: _this._parent.defaultBlock - })).createFunction(); - - return call(args.options, args.defaultBlock, args.callback); - - case 'send': - - // return error, if no "from" is specified - if(!utils.isAddress(args.options.from)) { - return utils._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'), defer.eventEmitter, defer.reject, args.callback); - } - - if (_.isBoolean(this._method.payable) && !this._method.payable && args.options.value && args.options.value > 0) { - return utils._fireError(new Error('Can not send value to non-payable contract method or constructor'), defer.eventEmitter, defer.reject, args.callback); - } - - - // make sure receipt logs are decoded - var extraFormatters = { - receiptFormatter: function (receipt) { - if (_.isArray(receipt.logs)) { - - // decode logs - var events = _.map(receipt.logs, function(log) { - return _this._parent._decodeEventABI.call({ - name: 'ALLEVENTS', - jsonInterface: _this._parent.options.jsonInterface - }, log); - }); - - // make log names keys - receipt.events = {}; - var count = 0; - events.forEach(function (ev) { - if (ev.event) { - // if > 1 of the same event, don't overwrite any existing events - if (receipt.events[ev.event]) { - if (Array.isArray(receipt.events[ ev.event ])) { - receipt.events[ ev.event ].push(ev); - } else { - receipt.events[ev.event] = [receipt.events[ev.event], ev]; - } - } else { - receipt.events[ ev.event ] = ev; - } - } else { - receipt.events[count] = ev; - count++; - } - }); - - delete receipt.logs; - } - return receipt; - }, - contractDeployFormatter: function (receipt) { - var newContract = _this._parent.clone(); - newContract.options.address = receipt.contractAddress; - return newContract; - } - }; - - var sendTransaction = (new Method({ - name: 'sendTransaction', - call: 'eth_sendTransaction', - params: 1, - inputFormatter: [formatters.inputTransactionFormatter], - requestManager: _this._parent._requestManager, - accounts: _this.constructor._ethAccounts || _this._ethAccounts, // is eth.accounts (necessary for wallet signing) - defaultAccount: _this._parent.defaultAccount, - defaultBlock: _this._parent.defaultBlock, - extraFormatters: extraFormatters - })).createFunction(); - - return sendTransaction(args.options, args.callback); - - } - - } - -}; - -module.exports = Contract; - -},{"underscore":1765,"web3-core":1802,"web3-core-helpers":1792,"web3-core-method":1793,"web3-core-promievent":1794,"web3-core-subscriptions":1799,"web3-eth-abi":1803,"web3-utils":1835}],1818:[function(require,module,exports){ -/* - This file is part of web3.js. - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file ENS.js - * - * @author Samuel Furter - * @date 2018 - */ - -"use strict"; - -var config = require('./config'); -var Registry = require('./contracts/Registry'); -var ResolverMethodHandler = require('./lib/ResolverMethodHandler'); - -/** - * Constructs a new instance of ENS - * - * @method ENS - * @param {Object} eth - * @constructor - */ -function ENS(eth) { - this.eth = eth; -} - -Object.defineProperty(ENS.prototype, 'registry', { - get: function () { - return new Registry(this); - }, - enumerable: true -}); - -Object.defineProperty(ENS.prototype, 'resolverMethodHandler', { - get: function () { - return new ResolverMethodHandler(this.registry); - }, - enumerable: true -}); - -/** - * @param {string} name - * @returns {Promise} - */ -ENS.prototype.resolver = function (name) { - return this.registry.resolver(name); -}; - -/** - * Returns the address record associated with a name. - * - * @method getAddress - * @param {string} name - * @param {function} callback - * @return {eventifiedPromise} - */ -ENS.prototype.getAddress = function (name, callback) { - return this.resolverMethodHandler.method(name, 'addr', []).call(callback); -}; - -/** - * Sets a new address - * - * @method setAddress - * @param {string} name - * @param {string} address - * @param {Object} sendOptions - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.setAddress = function (name, address, sendOptions, callback) { - return this.resolverMethodHandler.method(name, 'setAddr', [address]).send(sendOptions, callback); -}; - -/** - * Returns the public key - * - * @method getPubkey - * @param {string} name - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.getPubkey = function (name, callback) { - return this.resolverMethodHandler.method(name, 'pubkey', [], callback).call(callback); -}; - -/** - * Set the new public key - * - * @method setPubkey - * @param {string} name - * @param {string} x - * @param {string} y - * @param {Object} sendOptions - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.setPubkey = function (name, x, y, sendOptions, callback) { - return this.resolverMethodHandler.method(name, 'setPubkey', [x, y]).send(sendOptions, callback); -}; - -/** - * Returns the content - * - * @method getContent - * @param {string} name - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.getContent = function (name, callback) { - return this.resolverMethodHandler.method(name, 'content', []).call(callback); -}; - -/** - * Set the content - * - * @method setContent - * @param {string} name - * @param {string} hash - * @param {function} callback - * @param {Object} sendOptions - * @returns {eventifiedPromise} - */ -ENS.prototype.setContent = function (name, hash, sendOptions, callback) { - return this.resolverMethodHandler.method(name, 'setContent', [hash]).send(sendOptions, callback); -}; - -/** - * Get the multihash - * - * @method getMultihash - * @param {string} name - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.getMultihash = function (name, callback) { - return this.resolverMethodHandler.method(name, 'multihash', []).call(callback); -}; - -/** - * Set the multihash - * - * @method setMultihash - * @param {string} name - * @param {string} hash - * @param {Object} sendOptions - * @param {function} callback - * @returns {eventifiedPromise} - */ -ENS.prototype.setMultihash = function (name, hash, sendOptions, callback) { - return this.resolverMethodHandler.method(name, 'multihash', [hash]).send(sendOptions, callback); -}; - -/** - * Checks if the current used network is synced and looks for ENS support there. - * Throws an error if not. - * - * @returns {Promise} - */ -ENS.prototype.checkNetwork = function () { - var self = this; - return self.eth.getBlock('latest').then(function (block) { - var headAge = new Date() / 1000 - block.timestamp; - if (headAge > 3600) { - throw new Error("Network not synced; last block was " + headAge + " seconds ago"); - } - return self.eth.net.getNetworkType(); - }).then(function (networkType) { - var addr = config.addresses[networkType]; - if (typeof addr === 'undefined') { - throw new Error("ENS is not supported on network " + networkType); - } - - return addr; - }); -}; - -module.exports = ENS; - -},{"./config":1819,"./contracts/Registry":1820,"./lib/ResolverMethodHandler":1822}],1819:[function(require,module,exports){ -"use strict"; - -var config = { - addresses: { - main: "0x314159265dD8dbb310642f98f50C066173C1259b", - ropsten: "0x112234455c3a32fd11230c42e7bccd4a84e02010", - rinkeby: "0xe7410170f87102df0055eb195163a03b7f2bff4a" - }, -}; - -module.exports = config; - -},{}],1820:[function(require,module,exports){ -/* - This file is part of web3.js. - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file Registry.js - * - * @author Samuel Furter - * @date 2018 - */ - -"use strict"; - -var _ = require('underscore'); -var Contract = require('web3-eth-contract'); -var namehash = require('eth-ens-namehash'); -var PromiEvent = require('web3-core-promievent'); -var REGISTRY_ABI = require('../ressources/ABI/Registry'); -var RESOLVER_ABI = require('../ressources/ABI/Resolver'); - - -/** - * A wrapper around the ENS registry contract. - * - * @method Registry - * @param {Ens} ens - * @constructor - */ -function Registry(ens) { - var self = this; - this.ens = ens; - this.contract = ens.checkNetwork().then(function (address) { - var contract = new Contract(REGISTRY_ABI, address); - contract.setProvider(self.ens.eth.currentProvider); - - return contract; - }); -} - -/** - * Returns the address of the owner of an ENS name. - * - * @method owner - * @param {string} name - * @param {function} callback - * @return {Promise} - */ -Registry.prototype.owner = function (name, callback) { - var promiEvent = new PromiEvent(true); - - this.contract.then(function (contract) { - contract.methods.owner(namehash.hash(name)).call() - .then(function (receipt) { - promiEvent.resolve(receipt); - - if (_.isFunction(callback)) { - callback(receipt); - } - }) - .catch(function (error) { - promiEvent.reject(error); - - if (_.isFunction(callback)) { - callback(error); - } - }); - }); - - return promiEvent.eventEmitter; -}; - -/** - * Returns the resolver contract associated with a name. - * - * @method resolver - * @param {string} name - * @return {Promise} - */ -Registry.prototype.resolver = function (name) { - var self = this; - - return this.contract.then(function (contract) { - return contract.methods.resolver(namehash.hash(name)).call(); - }).then(function (address) { - var contract = new Contract(RESOLVER_ABI, address); - contract.setProvider(self.ens.eth.currentProvider); - return contract; - }); -}; - -module.exports = Registry; - -},{"../ressources/ABI/Registry":1823,"../ressources/ABI/Resolver":1824,"eth-ens-namehash":330,"underscore":1765,"web3-core-promievent":1794,"web3-eth-contract":1817}],1821:[function(require,module,exports){ -/* - This file is part of web3.js. - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * - * @author Samuel Furter - * @date 2018 - */ - -"use strict"; - -var ENS = require('./ENS'); - -module.exports = ENS; - -},{"./ENS":1818}],1822:[function(require,module,exports){ -/* - This file is part of web3.js. - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file ResolverMethodHandler.js - * - * @author Samuel Furter - * @date 2018 - */ - -"use strict"; - -var PromiEvent = require('web3-core-promievent'); -var namehash = require('eth-ens-namehash'); -var _ = require('underscore'); - -/** - * @param {Registry} registry - * @constructor - */ -function ResolverMethodHandler(registry) { - this.registry = registry; -} - -/** - * Executes an resolver method and returns an eventifiedPromise - * - * @param {string} ensName - * @param {string} methodName - * @param {array} methodArguments - * @param {function} callback - * @returns {Object} - */ -ResolverMethodHandler.prototype.method = function (ensName, methodName, methodArguments, callback) { - return { - call: this.call.bind({ - ensName: ensName, - methodName: methodName, - methodArguments: methodArguments, - callback: callback, - parent: this - }), - send: this.send.bind({ - ensName: ensName, - methodName: methodName, - methodArguments: methodArguments, - callback: callback, - parent: this - }) - }; -}; - -/** - * Executes call - * - * @returns {eventifiedPromise} - */ -ResolverMethodHandler.prototype.call = function (callback) { - var self = this; - var promiEvent = new PromiEvent(); - var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); - - this.parent.registry.resolver(this.ensName).then(function (resolver) { - self.parent.handleCall(promiEvent, resolver.methods[self.methodName], preparedArguments, callback); - }).catch(function (error) { - promiEvent.reject(error); - }); - - return promiEvent.eventEmitter; -}; - - -/** - * Executes send - * - * @param {Object} sendOptions - * @param {function} callback - * @returns {eventifiedPromise} - */ -ResolverMethodHandler.prototype.send = function (sendOptions, callback) { - var self = this; - var promiEvent = new PromiEvent(); - var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); - - this.parent.registry.resolver(this.ensName).then(function (resolver) { - self.parent.handleSend(promiEvent, resolver.methods[self.methodName], preparedArguments, sendOptions, callback); - }).catch(function (error) { - promiEvent.reject(error); - }); - - return promiEvent.eventEmitter; -}; - -/** - * Handles a call method - * - * @param {eventifiedPromise} promiEvent - * @param {function} method - * @param {array} preparedArguments - * @param {function} callback - * @returns {eventifiedPromise} - */ -ResolverMethodHandler.prototype.handleCall = function (promiEvent, method, preparedArguments, callback) { - method.apply(this, preparedArguments).call() - .then(function (receipt) { - promiEvent.resolve(receipt); - - if (_.isFunction(callback)) { - callback(receipt); - } - }).catch(function (error) { - promiEvent.reject(error); - - if (_.isFunction(callback)) { - callback(error); - } - }); - - return promiEvent; -}; - -/** - * Handles a send method - * - * @param {eventifiedPromise} promiEvent - * @param {function} method - * @param {array} preparedArguments - * @param {Object} sendOptions - * @param {function} callback - * @returns {eventifiedPromise} - */ -ResolverMethodHandler.prototype.handleSend = function (promiEvent, method, preparedArguments, sendOptions, callback) { - method.apply(this, preparedArguments).send(sendOptions) - .on('transactionHash', function (hash) { - promiEvent.eventEmitter.emit('transactionHash', hash); - }) - .on('confirmation', function (confirmationNumber, receipt) { - promiEvent.eventEmitter.emit('confirmation', confirmationNumber, receipt); - }) - .on('receipt', function (receipt) { - promiEvent.eventEmitter.emit('receipt', receipt); - promiEvent.resolve(receipt); - - if (_.isFunction(callback)) { - callback(receipt); - } - }) - .on('error', function (error) { - promiEvent.eventEmitter.emit('error', error); - promiEvent.reject(error); - - if (_.isFunction(callback)) { - callback(error); - } - }); - - return promiEvent; -}; - -/** - * Adds the ENS node to the arguments - * - * @param {string} name - * @param {array} methodArguments - * @returns {array} - */ -ResolverMethodHandler.prototype.prepareArguments = function (name, methodArguments) { - var node = namehash.hash(name); - - if (methodArguments.length > 0) { - methodArguments.unshift(node); - - return methodArguments; - } - - return [node]; -}; - -module.exports = ResolverMethodHandler; - -},{"eth-ens-namehash":330,"underscore":1765,"web3-core-promievent":1794}],1823:[function(require,module,exports){ -"use strict"; - -var REGISTRY = [ - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "resolver", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "owner", - "outputs": [ - { - "name": "", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "label", - "type": "bytes32" - }, - { - "name": "owner", - "type": "address" - } - ], - "name": "setSubnodeOwner", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "ttl", - "type": "uint64" - } - ], - "name": "setTTL", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "ttl", - "outputs": [ - { - "name": "", - "type": "uint64" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "resolver", - "type": "address" - } - ], - "name": "setResolver", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "owner", - "type": "address" - } - ], - "name": "setOwner", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "owner", - "type": "address" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": true, - "name": "label", - "type": "bytes32" - }, - { - "indexed": false, - "name": "owner", - "type": "address" - } - ], - "name": "NewOwner", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "resolver", - "type": "address" - } - ], - "name": "NewResolver", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "ttl", - "type": "uint64" - } - ], - "name": "NewTTL", - "type": "event" - } -]; - -module.exports = REGISTRY; - -},{}],1824:[function(require,module,exports){ -"use strict"; - -var RESOLVER = [ - { - "constant": true, - "inputs": [ - { - "name": "interfaceID", - "type": "bytes4" - } - ], - "name": "supportsInterface", - "outputs": [ - { - "name": "", - "type": "bool" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "contentTypes", - "type": "uint256" - } - ], - "name": "ABI", - "outputs": [ - { - "name": "contentType", - "type": "uint256" - }, - { - "name": "data", - "type": "bytes" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "hash", - "type": "bytes" - } - ], - "name": "setMultihash", - "outputs": [], - "payable": false, - "stateMutability": "nonpayable", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "multihash", - "outputs": [ - { - "name": "", - "type": "bytes" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "x", - "type": "bytes32" - }, - { - "name": "y", - "type": "bytes32" - } - ], - "name": "setPubkey", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "content", - "outputs": [ - { - "name": "ret", - "type": "bytes32" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "addr", - "outputs": [ - { - "name": "ret", - "type": "address" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "contentType", - "type": "uint256" - }, - { - "name": "data", - "type": "bytes" - } - ], - "name": "setABI", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "name", - "outputs": [ - { - "name": "ret", - "type": "string" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "name", - "type": "string" - } - ], - "name": "setName", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "hash", - "type": "bytes32" - } - ], - "name": "setContent", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "name": "node", - "type": "bytes32" - } - ], - "name": "pubkey", - "outputs": [ - { - "name": "x", - "type": "bytes32" - }, - { - "name": "y", - "type": "bytes32" - } - ], - "payable": false, - "type": "function" - }, - { - "constant": false, - "inputs": [ - { - "name": "node", - "type": "bytes32" - }, - { - "name": "addr", - "type": "address" - } - ], - "name": "setAddr", - "outputs": [], - "payable": false, - "type": "function" - }, - { - "inputs": [ - { - "name": "ensAddr", - "type": "address" - } - ], - "payable": false, - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "a", - "type": "address" - } - ], - "name": "AddrChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "hash", - "type": "bytes32" - } - ], - "name": "ContentChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "name", - "type": "string" - } - ], - "name": "NameChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": true, - "name": "contentType", - "type": "uint256" - } - ], - "name": "ABIChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "name": "node", - "type": "bytes32" - }, - { - "indexed": false, - "name": "x", - "type": "bytes32" - }, - { - "indexed": false, - "name": "y", - "type": "bytes32" - } - ], - "name": "PubkeyChanged", - "type": "event" - } -]; - -module.exports = RESOLVER; - -},{}],1825:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file iban.js - * - * Details: https://github.com/ethereum/wiki/wiki/ICAP:-Inter-exchange-Client-Address-Protocol - * - * @author Marek Kotewicz - * @date 2015 - */ - -"use strict"; - -var utils = require('web3-utils'); -var BigNumber = require('bn.js'); - - -var leftPad = function (string, bytes) { - var result = string; - while (result.length < bytes * 2) { - result = '0' + result; - } - return result; -}; - -/** - * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to - * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. - * - * @method iso13616Prepare - * @param {String} iban the IBAN - * @returns {String} the prepared IBAN - */ -var iso13616Prepare = function (iban) { - var A = 'A'.charCodeAt(0); - var Z = 'Z'.charCodeAt(0); - - iban = iban.toUpperCase(); - iban = iban.substr(4) + iban.substr(0,4); - - return iban.split('').map(function(n){ - var code = n.charCodeAt(0); - if (code >= A && code <= Z){ - // A = 10, B = 11, ... Z = 35 - return code - A + 10; - } else { - return n; - } - }).join(''); -}; - -/** - * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. - * - * @method mod9710 - * @param {String} iban - * @returns {Number} - */ -var mod9710 = function (iban) { - var remainder = iban, - block; - - while (remainder.length > 2){ - block = remainder.slice(0, 9); - remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); - } - - return parseInt(remainder, 10) % 97; -}; - -/** - * This prototype should be used to create iban object from iban correct string - * - * @param {String} iban - */ -var Iban = function Iban(iban) { - this._iban = iban; -}; - -/** - * This method should be used to create an ethereum address from a direct iban address - * - * @method toAddress - * @param {String} iban address - * @return {String} the ethereum address - */ -Iban.toAddress = function (ib) { - ib = new Iban(ib); - - if(!ib.isDirect()) { - throw new Error('IBAN is indirect and can\'t be converted'); - } - - return ib.toAddress(); -}; - -/** - * This method should be used to create iban address from an ethereum address - * - * @method toIban - * @param {String} address - * @return {String} the IBAN address - */ -Iban.toIban = function (address) { - return Iban.fromAddress(address).toString(); -}; - -/** - * This method should be used to create iban object from an ethereum address - * - * @method fromAddress - * @param {String} address - * @return {Iban} the IBAN object - */ -Iban.fromAddress = function (address) { - if(!utils.isAddress(address)){ - throw new Error('Provided address is not a valid address: '+ address); - } - - address = address.replace('0x','').replace('0X',''); - - var asBn = new BigNumber(address, 16); - var base36 = asBn.toString(36); - var padded = leftPad(base36, 15); - return Iban.fromBban(padded.toUpperCase()); -}; - -/** - * Convert the passed BBAN to an IBAN for this country specification. - * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". - * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits - * - * @method fromBban - * @param {String} bban the BBAN to convert to IBAN - * @returns {Iban} the IBAN object - */ -Iban.fromBban = function (bban) { - var countryCode = 'XE'; - - var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); - var checkDigit = ('0' + (98 - remainder)).slice(-2); - - return new Iban(countryCode + checkDigit + bban); -}; - -/** - * Should be used to create IBAN object for given institution and identifier - * - * @method createIndirect - * @param {Object} options, required options are "institution" and "identifier" - * @return {Iban} the IBAN object - */ -Iban.createIndirect = function (options) { - return Iban.fromBban('ETH' + options.institution + options.identifier); -}; - -/** - * This method should be used to check if given string is valid iban object - * - * @method isValid - * @param {String} iban string - * @return {Boolean} true if it is valid IBAN - */ -Iban.isValid = function (iban) { - var i = new Iban(iban); - return i.isValid(); -}; - -/** - * Should be called to check if iban is correct - * - * @method isValid - * @returns {Boolean} true if it is, otherwise false - */ -Iban.prototype.isValid = function () { - return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && - mod9710(iso13616Prepare(this._iban)) === 1; -}; - -/** - * Should be called to check if iban number is direct - * - * @method isDirect - * @returns {Boolean} true if it is, otherwise false - */ -Iban.prototype.isDirect = function () { - return this._iban.length === 34 || this._iban.length === 35; -}; - -/** - * Should be called to check if iban number if indirect - * - * @method isIndirect - * @returns {Boolean} true if it is, otherwise false - */ -Iban.prototype.isIndirect = function () { - return this._iban.length === 20; -}; - -/** - * Should be called to get iban checksum - * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) - * - * @method checksum - * @returns {String} checksum - */ -Iban.prototype.checksum = function () { - return this._iban.substr(2, 2); -}; - -/** - * Should be called to get institution identifier - * eg. XREG - * - * @method institution - * @returns {String} institution identifier - */ -Iban.prototype.institution = function () { - return this.isIndirect() ? this._iban.substr(7, 4) : ''; -}; - -/** - * Should be called to get client identifier within institution - * eg. GAVOFYORK - * - * @method client - * @returns {String} client identifier - */ -Iban.prototype.client = function () { - return this.isIndirect() ? this._iban.substr(11) : ''; -}; - -/** - * Should be called to get client direct address - * - * @method toAddress - * @returns {String} ethereum address - */ -Iban.prototype.toAddress = function () { - if (this.isDirect()) { - var base36 = this._iban.substr(4); - var asBn = new BigNumber(base36, 36); - return utils.toChecksumAddress(asBn.toString(16, 20)); - } - - return ''; -}; - -Iban.prototype.toString = function () { - return this._iban; -}; - -module.exports = Iban; - -},{"bn.js":171,"web3-utils":1835}],1826:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var core = require('web3-core'); -var Method = require('web3-core-method'); -var utils = require('web3-utils'); -var Net = require('web3-net'); - -var formatters = require('web3-core-helpers').formatters; - - -var Personal = function Personal() { - var _this = this; - - // sets _requestmanager - core.packageInit(this, arguments); - - this.net = new Net(this.currentProvider); - - var defaultAccount = null; - var defaultBlock = 'latest'; - - Object.defineProperty(this, 'defaultAccount', { - get: function () { - return defaultAccount; - }, - set: function (val) { - if(val) { - defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); - } - - // update defaultBlock - methods.forEach(function(method) { - method.defaultAccount = defaultAccount; - }); - - return val; - }, - enumerable: true - }); - Object.defineProperty(this, 'defaultBlock', { - get: function () { - return defaultBlock; - }, - set: function (val) { - defaultBlock = val; - - // update defaultBlock - methods.forEach(function(method) { - method.defaultBlock = defaultBlock; - }); - - return val; - }, - enumerable: true - }); - - - var methods = [ - new Method({ - name: 'getAccounts', - call: 'personal_listAccounts', - params: 0, - outputFormatter: utils.toChecksumAddress - }), - new Method({ - name: 'newAccount', - call: 'personal_newAccount', - params: 1, - inputFormatter: [null], - outputFormatter: utils.toChecksumAddress - }), - new Method({ - name: 'unlockAccount', - call: 'personal_unlockAccount', - params: 3, - inputFormatter: [formatters.inputAddressFormatter, null, null] - }), - new Method({ - name: 'lockAccount', - call: 'personal_lockAccount', - params: 1, - inputFormatter: [formatters.inputAddressFormatter] - }), - new Method({ - name: 'importRawKey', - call: 'personal_importRawKey', - params: 2 - }), - new Method({ - name: 'sendTransaction', - call: 'personal_sendTransaction', - params: 2, - inputFormatter: [formatters.inputTransactionFormatter, null] - }), - new Method({ - name: 'signTransaction', - call: 'personal_signTransaction', - params: 2, - inputFormatter: [formatters.inputTransactionFormatter, null] - }), - new Method({ - name: 'sign', - call: 'personal_sign', - params: 3, - inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null] - }), - new Method({ - name: 'ecRecover', - call: 'personal_ecRecover', - params: 2, - inputFormatter: [formatters.inputSignFormatter, null] - }) - ]; - methods.forEach(function(method) { - method.attachToObject(_this); - method.setRequestManager(_this._requestManager); - method.defaultBlock = _this.defaultBlock; - method.defaultAccount = _this.defaultAccount; - }); -}; - -core.addProviders(Personal); - - - -module.exports = Personal; - - - -},{"web3-core":1802,"web3-core-helpers":1792,"web3-core-method":1793,"web3-net":1829,"web3-utils":1835}],1827:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file getNetworkType.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); - -var getNetworkType = function (callback) { - var _this = this, - id; - - - return this.net.getId() - .then(function (givenId) { - - id = givenId; - - return _this.getBlock(0); - }) - .then(function (genesis) { - var returnValue = 'private'; - - if (genesis.hash === '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' && - id === 1) { - returnValue = 'main'; - } - if (genesis.hash === '0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303' && - id === 2) { - returnValue = 'morden'; - } - if (genesis.hash === '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d' && - id === 3) { - returnValue = 'ropsten'; - } - if (genesis.hash === '0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177' && - id === 4) { - returnValue = 'rinkeby'; - } - if (genesis.hash === '0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9' && - id === 42) { - returnValue = 'kovan'; - } - - if (_.isFunction(callback)) { - callback(null, returnValue); - } - - return returnValue; - }) - .catch(function (err) { - if (_.isFunction(callback)) { - callback(err); - } else { - throw err; - } - }); -}; - -module.exports = getNetworkType; - -},{"underscore":1765}],1828:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var core = require('web3-core'); -var helpers = require('web3-core-helpers'); -var Subscriptions = require('web3-core-subscriptions').subscriptions; -var Method = require('web3-core-method'); -var utils = require('web3-utils'); -var Net = require('web3-net'); - -var ENS = require('web3-eth-ens'); -var Personal = require('web3-eth-personal'); -var BaseContract = require('web3-eth-contract'); -var Iban = require('web3-eth-iban'); -var Accounts = require('web3-eth-accounts'); -var abi = require('web3-eth-abi'); - -var getNetworkType = require('./getNetworkType.js'); -var formatter = helpers.formatters; - - -var blockCall = function (args) { - return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; -}; - -var transactionFromBlockCall = function (args) { - return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; -}; - -var uncleCall = function (args) { - return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; -}; - -var getBlockTransactionCountCall = function (args) { - return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; -}; - -var uncleCountCall = function (args) { - return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; -}; - - -var Eth = function Eth() { - var _this = this; - - // sets _requestmanager - core.packageInit(this, arguments); - - // overwrite setProvider - var setProvider = this.setProvider; - this.setProvider = function () { - setProvider.apply(_this, arguments); - _this.net.setProvider.apply(_this, arguments); - _this.personal.setProvider.apply(_this, arguments); - _this.accounts.setProvider.apply(_this, arguments); - _this.Contract.setProvider(_this.currentProvider, _this.accounts); - }; - - - var defaultAccount = null; - var defaultBlock = 'latest'; - - Object.defineProperty(this, 'defaultAccount', { - get: function () { - return defaultAccount; - }, - set: function (val) { - if(val) { - defaultAccount = utils.toChecksumAddress(formatter.inputAddressFormatter(val)); - } - - // also set on the Contract object - _this.Contract.defaultAccount = defaultAccount; - _this.personal.defaultAccount = defaultAccount; - - // update defaultBlock - methods.forEach(function(method) { - method.defaultAccount = defaultAccount; - }); - - return val; - }, - enumerable: true - }); - Object.defineProperty(this, 'defaultBlock', { - get: function () { - return defaultBlock; - }, - set: function (val) { - defaultBlock = val; - // also set on the Contract object - _this.Contract.defaultBlock = defaultBlock; - _this.personal.defaultBlock = defaultBlock; - - // update defaultBlock - methods.forEach(function(method) { - method.defaultBlock = defaultBlock; - }); - - return val; - }, - enumerable: true - }); - - - this.clearSubscriptions = _this._requestManager.clearSubscriptions; - - // add net - this.net = new Net(this.currentProvider); - // add chain detection - this.net.getNetworkType = getNetworkType.bind(this); - - // add accounts - this.accounts = new Accounts(this.currentProvider); - - // add personal - this.personal = new Personal(this.currentProvider); - this.personal.defaultAccount = this.defaultAccount; - - // create a proxy Contract type for this instance, as a Contract's provider - // is stored as a class member rather than an instance variable. If we do - // not create this proxy type, changing the provider in one instance of - // web3-eth would subsequently change the provider for _all_ contract - // instances! - var self = this; - var Contract = function Contract() { - BaseContract.apply(this, arguments); - - // when Eth.setProvider is called, call packageInit - // on all contract instances instantiated via this Eth - // instances. This will update the currentProvider for - // the contract instances - var _this = this; - var setProvider = self.setProvider; - self.setProvider = function() { - setProvider.apply(self, arguments); - core.packageInit(_this, [self.currentProvider]); - }; - }; - - Contract.setProvider = function() { - BaseContract.setProvider.apply(this, arguments); - }; - - // make our proxy Contract inherit from web3-eth-contract so that it has all - // the right functionality and so that instanceof and friends work properly - Contract.prototype = Object.create(BaseContract.prototype); - Contract.prototype.constructor = Contract; - - // add contract - this.Contract = Contract; - this.Contract.defaultAccount = this.defaultAccount; - this.Contract.defaultBlock = this.defaultBlock; - this.Contract.setProvider(this.currentProvider, this.accounts); - - // add IBAN - this.Iban = Iban; - - // add ABI - this.abi = abi; - - // add ENS - this.ens = new ENS(this); - - var methods = [ - new Method({ - name: 'getNodeInfo', - call: 'web3_clientVersion' - }), - new Method({ - name: 'getProtocolVersion', - call: 'eth_protocolVersion', - params: 0 - }), - new Method({ - name: 'getCoinbase', - call: 'eth_coinbase', - params: 0 - }), - new Method({ - name: 'isMining', - call: 'eth_mining', - params: 0 - }), - new Method({ - name: 'getHashrate', - call: 'eth_hashrate', - params: 0, - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'isSyncing', - call: 'eth_syncing', - params: 0, - outputFormatter: formatter.outputSyncingFormatter - }), - new Method({ - name: 'getGasPrice', - call: 'eth_gasPrice', - params: 0, - outputFormatter: formatter.outputBigNumberFormatter - }), - new Method({ - name: 'getAccounts', - call: 'eth_accounts', - params: 0, - outputFormatter: utils.toChecksumAddress - }), - new Method({ - name: 'getBlockNumber', - call: 'eth_blockNumber', - params: 0, - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'getBalance', - call: 'eth_getBalance', - params: 2, - inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], - outputFormatter: formatter.outputBigNumberFormatter - }), - new Method({ - name: 'getStorageAt', - call: 'eth_getStorageAt', - params: 3, - inputFormatter: [formatter.inputAddressFormatter, utils.numberToHex, formatter.inputDefaultBlockNumberFormatter] - }), - new Method({ - name: 'getCode', - call: 'eth_getCode', - params: 2, - inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter] - }), - new Method({ - name: 'getBlock', - call: blockCall, - params: 2, - inputFormatter: [formatter.inputBlockNumberFormatter, function (val) { return !!val; }], - outputFormatter: formatter.outputBlockFormatter - }), - new Method({ - name: 'getUncle', - call: uncleCall, - params: 2, - inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], - outputFormatter: formatter.outputBlockFormatter, - - }), - new Method({ - name: 'getBlockTransactionCount', - call: getBlockTransactionCountCall, - params: 1, - inputFormatter: [formatter.inputBlockNumberFormatter], - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'getBlockUncleCount', - call: uncleCountCall, - params: 1, - inputFormatter: [formatter.inputBlockNumberFormatter], - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'getTransaction', - call: 'eth_getTransactionByHash', - params: 1, - inputFormatter: [null], - outputFormatter: formatter.outputTransactionFormatter - }), - new Method({ - name: 'getTransactionFromBlock', - call: transactionFromBlockCall, - params: 2, - inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], - outputFormatter: formatter.outputTransactionFormatter - }), - new Method({ - name: 'getTransactionReceipt', - call: 'eth_getTransactionReceipt', - params: 1, - inputFormatter: [null], - outputFormatter: formatter.outputTransactionReceiptFormatter - }), - new Method({ - name: 'getTransactionCount', - call: 'eth_getTransactionCount', - params: 2, - inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'sendSignedTransaction', - call: 'eth_sendRawTransaction', - params: 1, - inputFormatter: [null] - }), - new Method({ - name: 'signTransaction', - call: 'eth_signTransaction', - params: 1, - inputFormatter: [formatter.inputTransactionFormatter] - }), - new Method({ - name: 'sendTransaction', - call: 'eth_sendTransaction', - params: 1, - inputFormatter: [formatter.inputTransactionFormatter] - }), - new Method({ - name: 'sign', - call: 'eth_sign', - params: 2, - inputFormatter: [formatter.inputSignFormatter, formatter.inputAddressFormatter], - transformPayload: function (payload) { - payload.params.reverse(); - return payload; - } - }), - new Method({ - name: 'call', - call: 'eth_call', - params: 2, - inputFormatter: [formatter.inputCallFormatter, formatter.inputDefaultBlockNumberFormatter] - }), - new Method({ - name: 'estimateGas', - call: 'eth_estimateGas', - params: 1, - inputFormatter: [formatter.inputCallFormatter], - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'submitWork', - call: 'eth_submitWork', - params: 3 - }), - new Method({ - name: 'getWork', - call: 'eth_getWork', - params: 0 - }), - new Method({ - name: 'getPastLogs', - call: 'eth_getLogs', - params: 1, - inputFormatter: [formatter.inputLogFormatter], - outputFormatter: formatter.outputLogFormatter - }), - - // subscriptions - new Subscriptions({ - name: 'subscribe', - type: 'eth', - subscriptions: { - 'newBlockHeaders': { - // TODO rename on RPC side? - subscriptionName: 'newHeads', // replace subscription with this name - params: 0, - outputFormatter: formatter.outputBlockFormatter - }, - 'pendingTransactions': { - subscriptionName: 'newPendingTransactions', // replace subscription with this name - params: 0 - }, - 'logs': { - params: 1, - inputFormatter: [formatter.inputLogFormatter], - outputFormatter: formatter.outputLogFormatter, - // DUBLICATE, also in web3-eth-contract - subscriptionHandler: function (output) { - if(output.removed) { - this.emit('changed', output); - } else { - this.emit('data', output); - } - - if (_.isFunction(this.callback)) { - this.callback(null, output, this); - } - } - }, - 'syncing': { - params: 0, - outputFormatter: formatter.outputSyncingFormatter, - subscriptionHandler: function (output) { - var _this = this; - - // fire TRUE at start - if(this._isSyncing !== true) { - this._isSyncing = true; - this.emit('changed', _this._isSyncing); - - if (_.isFunction(this.callback)) { - this.callback(null, _this._isSyncing, this); - } - - setTimeout(function () { - _this.emit('data', output); - - if (_.isFunction(_this.callback)) { - _this.callback(null, output, _this); - } - }, 0); - - // fire sync status - } else { - this.emit('data', output); - if (_.isFunction(_this.callback)) { - this.callback(null, output, this); - } - - // wait for some time before fireing the FALSE - clearTimeout(this._isSyncingTimeout); - this._isSyncingTimeout = setTimeout(function () { - if(output.currentBlock > output.highestBlock - 200) { - _this._isSyncing = false; - _this.emit('changed', _this._isSyncing); - - if (_.isFunction(_this.callback)) { - _this.callback(null, _this._isSyncing, _this); - } - } - }, 500); - } - } - } - } - }) - ]; - - methods.forEach(function(method) { - method.attachToObject(_this); - method.setRequestManager(_this._requestManager, _this.accounts); // second param means is eth.accounts (necessary for wallet signing) - method.defaultBlock = _this.defaultBlock; - method.defaultAccount = _this.defaultAccount; - }); - -}; - -core.addProviders(Eth); - - -module.exports = Eth; - - -},{"./getNetworkType.js":1827,"underscore":1765,"web3-core":1802,"web3-core-helpers":1792,"web3-core-method":1793,"web3-core-subscriptions":1799,"web3-eth-abi":1803,"web3-eth-accounts":1815,"web3-eth-contract":1817,"web3-eth-ens":1821,"web3-eth-iban":1825,"web3-eth-personal":1826,"web3-net":1829,"web3-utils":1835}],1829:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var core = require('web3-core'); -var Method = require('web3-core-method'); -var utils = require('web3-utils'); - - -var Net = function () { - var _this = this; - - // sets _requestmanager - core.packageInit(this, arguments); - - - [ - new Method({ - name: 'getId', - call: 'net_version', - params: 0, - outputFormatter: utils.hexToNumber - }), - new Method({ - name: 'isListening', - call: 'net_listening', - params: 0 - }), - new Method({ - name: 'getPeerCount', - call: 'net_peerCount', - params: 0, - outputFormatter: utils.hexToNumber - }) - ].forEach(function(method) { - method.attachToObject(_this); - method.setRequestManager(_this._requestManager); - }); - -}; - -core.addProviders(Net); - - -module.exports = Net; - - - -},{"web3-core":1802,"web3-core-method":1793,"web3-utils":1835}],1830:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** @file httpprovider.js - * @authors: - * Marek Kotewicz - * Marian Oancea - * Fabian Vogelsteller - * @date 2015 - */ - -var errors = require('web3-core-helpers').errors; -var XHR2 = require('xhr2-cookies').XMLHttpRequest // jshint ignore: line -var http = require('http'); -var https = require('https'); - - -/** - * HttpProvider should be used to send rpc calls over http - */ -var HttpProvider = function HttpProvider(host, options) { - options = options || {}; - - var keepAlive = - (options.keepAlive === true || options.keepAlive !== false) ? - true : - false; - this.host = host || 'http://localhost:8545'; - if (this.host.substring(0,5) === "https") { - this.httpsAgent = new https.Agent({ keepAlive: keepAlive }); - }else{ - this.httpAgent = new http.Agent({ keepAlive: keepAlive }); - } - this.timeout = options.timeout || 0; - this.headers = options.headers; - this.connected = false; -}; - -HttpProvider.prototype._prepareRequest = function(){ - var request = new XHR2(); - request.nodejsSet({ - httpsAgent:this.httpsAgent, - httpAgent:this.httpAgent - }); - - request.open('POST', this.host, true); - request.setRequestHeader('Content-Type','application/json'); - request.timeout = this.timeout && this.timeout !== 1 ? this.timeout : 0; - request.withCredentials = true; - - if(this.headers) { - this.headers.forEach(function(header) { - request.setRequestHeader(header.name, header.value); - }); - } - - return request; -}; - -/** - * Should be used to make async request - * - * @method send - * @param {Object} payload - * @param {Function} callback triggered on end with (err, result) - */ -HttpProvider.prototype.send = function (payload, callback) { - var _this = this; - var request = this._prepareRequest(); - - request.onreadystatechange = function() { - if (request.readyState === 4 && request.timeout !== 1) { - var result = request.responseText; - var error = null; - - try { - result = JSON.parse(result); - } catch(e) { - error = errors.InvalidResponse(request.responseText); - } - - _this.connected = true; - callback(error, result); - } - }; - - request.ontimeout = function() { - _this.connected = false; - callback(errors.ConnectionTimeout(this.timeout)); - }; - - try { - request.send(JSON.stringify(payload)); - } catch(error) { - this.connected = false; - callback(errors.InvalidConnection(this.host)); - } -}; - -HttpProvider.prototype.disconnect = function () { - //NO OP -}; - - -module.exports = HttpProvider; - -},{"http":1716,"https":446,"web3-core-helpers":1792,"xhr2-cookies":1852}],1831:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** @file index.js - * @authors: - * Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var errors = require('web3-core-helpers').errors; -var oboe = require('oboe'); - - -var IpcProvider = function IpcProvider(path, net) { - var _this = this; - this.responseCallbacks = {}; - this.notificationCallbacks = []; - this.path = path; - this.connected = false; - - this.connection = net.connect({path: this.path}); - - this.addDefaultEvents(); - - // LISTEN FOR CONNECTION RESPONSES - var callback = function(result) { - /*jshint maxcomplexity: 6 */ - - var id = null; - - // get the id which matches the returned id - if(_.isArray(result)) { - result.forEach(function(load){ - if(_this.responseCallbacks[load.id]) - id = load.id; - }); - } else { - id = result.id; - } - - // notification - if(!id && result.method.indexOf('_subscription') !== -1) { - _this.notificationCallbacks.forEach(function(callback){ - if(_.isFunction(callback)) - callback(result); - }); - - // fire the callback - } else if(_this.responseCallbacks[id]) { - _this.responseCallbacks[id](null, result); - delete _this.responseCallbacks[id]; - } - }; - - // use oboe.js for Sockets - if (net.constructor.name === 'Socket') { - oboe(this.connection) - .done(callback); - } else { - this.connection.on('data', function(data){ - _this._parseResponse(data.toString()).forEach(callback); - }); - } -}; - -/** -Will add the error and end event to timeout existing calls - -@method addDefaultEvents -*/ -IpcProvider.prototype.addDefaultEvents = function(){ - var _this = this; - - this.connection.on('connect', function(){ - _this.connected = true; - }); - - this.connection.on('close', function(){ - _this.connected = false; - }); - - this.connection.on('error', function(){ - _this._timeout(); - }); - - this.connection.on('end', function(){ - _this._timeout(); - }); - - this.connection.on('timeout', function(){ - _this._timeout(); - }); -}; - - -/** - Will parse the response and make an array out of it. - - NOTE, this exists for backwards compatibility reasons. - - @method _parseResponse - @param {String} data - */ -IpcProvider.prototype._parseResponse = function(data) { - var _this = this, - returnValues = []; - - // DE-CHUNKER - var dechunkedData = data - .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ - .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ - .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ - .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ - .split('|--|'); - - dechunkedData.forEach(function(data){ - - // prepend the last chunk - if(_this.lastChunk) - data = _this.lastChunk + data; - - var result = null; - - try { - result = JSON.parse(data); - - } catch(e) { - - _this.lastChunk = data; - - // start timeout to cancel all requests - clearTimeout(_this.lastChunkTimeout); - _this.lastChunkTimeout = setTimeout(function(){ - _this._timeout(); - throw errors.InvalidResponse(data); - }, 1000 * 15); - - return; - } - - // cancel timeout and set chunk to null - clearTimeout(_this.lastChunkTimeout); - _this.lastChunk = null; - - if(result) - returnValues.push(result); - }); - - return returnValues; -}; - - -/** -Get the adds a callback to the responseCallbacks object, -which will be called if a response matching the response Id will arrive. - -@method _addResponseCallback -*/ -IpcProvider.prototype._addResponseCallback = function(payload, callback) { - var id = payload.id || payload[0].id; - var method = payload.method || payload[0].method; - - this.responseCallbacks[id] = callback; - this.responseCallbacks[id].method = method; -}; - -/** -Timeout all requests when the end/error event is fired - -@method _timeout -*/ -IpcProvider.prototype._timeout = function() { - for(var key in this.responseCallbacks) { - if(this.responseCallbacks.hasOwnProperty(key)){ - this.responseCallbacks[key](errors.InvalidConnection('on IPC')); - delete this.responseCallbacks[key]; - } - } -}; - -/** - Try to reconnect - - @method reconnect - */ -IpcProvider.prototype.reconnect = function() { - this.connection.connect({path: this.path}); -}; - - -IpcProvider.prototype.send = function (payload, callback) { - // try reconnect, when connection is gone - if(!this.connection.writable) - this.connection.connect({path: this.path}); - - - this.connection.write(JSON.stringify(payload)); - this._addResponseCallback(payload, callback); -}; - -/** -Subscribes to provider events.provider - -@method on -@param {String} type 'notification', 'connect', 'error', 'end' or 'data' -@param {Function} callback the callback to call -*/ -IpcProvider.prototype.on = function (type, callback) { - - if(typeof callback !== 'function') - throw new Error('The second parameter callback must be a function.'); - - switch(type){ - case 'data': - this.notificationCallbacks.push(callback); - break; - - // adds error, end, timeout, connect - default: - this.connection.on(type, callback); - break; - } -}; - -/** - Subscribes to provider events.provider - - @method on - @param {String} type 'connect', 'error', 'end' or 'data' - @param {Function} callback the callback to call - */ -IpcProvider.prototype.once = function (type, callback) { - - if(typeof callback !== 'function') - throw new Error('The second parameter callback must be a function.'); - - this.connection.once(type, callback); -}; - -/** -Removes event listener - -@method removeListener -@param {String} type 'data', 'connect', 'error', 'end' or 'data' -@param {Function} callback the callback to call -*/ -IpcProvider.prototype.removeListener = function (type, callback) { - var _this = this; - - switch(type){ - case 'data': - this.notificationCallbacks.forEach(function(cb, index){ - if(cb === callback) - _this.notificationCallbacks.splice(index, 1); - }); - break; - - default: - this.connection.removeListener(type, callback); - break; - } -}; - -/** -Removes all event listeners - -@method removeAllListeners -@param {String} type 'data', 'connect', 'error', 'end' or 'data' -*/ -IpcProvider.prototype.removeAllListeners = function (type) { - switch(type){ - case 'data': - this.notificationCallbacks = []; - break; - - default: - this.connection.removeAllListeners(type); - break; - } -}; - -/** -Resets the providers, clears all callbacks - -@method reset -*/ -IpcProvider.prototype.reset = function () { - this._timeout(); - this.notificationCallbacks = []; - - this.connection.removeAllListeners('error'); - this.connection.removeAllListeners('end'); - this.connection.removeAllListeners('timeout'); - - this.addDefaultEvents(); -}; - -module.exports = IpcProvider; - - -},{"oboe":1392,"underscore":1765,"web3-core-helpers":1792}],1832:[function(require,module,exports){ -(function (process,Buffer){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** @file WebsocketProvider.js - * @authors: - * Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var _ = require('underscore'); -var errors = require('web3-core-helpers').errors; -var Ws = require('websocket').w3cwebsocket; - -var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; - -var _btoa = null; -var parseURL = null; -if (isNode) { - _btoa = function(str) { - return Buffer.from(str).toString('base64'); - }; - var url = require('url'); - if (url.URL) { - // Use the new Node 6+ API for parsing URLs that supports username/password - var newURL = url.URL; - parseURL = function(url) { - return new newURL(url); - }; - } - else { - // Web3 supports Node.js 5, so fall back to the legacy URL API if necessary - parseURL = require('url').parse; - } -} else { - _btoa = btoa; - parseURL = function(url) { - return new URL(url); - }; -} -// Default connection ws://localhost:8546 - - - - -var WebsocketProvider = function WebsocketProvider(url, options) { - if (!Ws) { - throw new Error('websocket is not available'); - } - - var _this = this; - this.responseCallbacks = {}; - this.notificationCallbacks = []; - - options = options || {}; - this._customTimeout = options.timeout; - - // The w3cwebsocket implementation does not support Basic Auth - // username/password in the URL. So generate the basic auth header, and - // pass through with any additional headers supplied in constructor - var parsedURL = parseURL(url); - var headers = options.headers || {}; - var protocol = options.protocol || undefined; - if (parsedURL.username && parsedURL.password) { - headers.authorization = 'Basic ' + _btoa(parsedURL.username + ':' + parsedURL.password); - } - - // Allow a custom client configuration - var clientConfig = options.clientConfig || undefined; - - // Allow a custom request options - // https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketClient.md#connectrequesturl-requestedprotocols-origin-headers-requestoptions - var requestOptions = options.requestOptions || undefined; - - // When all node core implementations that do not have the - // WHATWG compatible URL parser go out of service this line can be removed. - if (parsedURL.auth) { - headers.authorization = 'Basic ' + _btoa(parsedURL.auth); - } - this.connection = new Ws(url, protocol, undefined, headers, requestOptions, clientConfig); - - this.addDefaultEvents(); - - - // LISTEN FOR CONNECTION RESPONSES - this.connection.onmessage = function(e) { - /*jshint maxcomplexity: 6 */ - var data = (typeof e.data === 'string') ? e.data : ''; - - _this._parseResponse(data).forEach(function(result){ - - var id = null; - - // get the id which matches the returned id - if(_.isArray(result)) { - result.forEach(function(load){ - if(_this.responseCallbacks[load.id]) - id = load.id; - }); - } else { - id = result.id; - } - - // notification - if(!id && result && result.method && result.method.indexOf('_subscription') !== -1) { - _this.notificationCallbacks.forEach(function(callback){ - if(_.isFunction(callback)) - callback(result); - }); - - // fire the callback - } else if(_this.responseCallbacks[id]) { - _this.responseCallbacks[id](null, result); - delete _this.responseCallbacks[id]; - } - }); - }; - - // make property `connected` which will return the current connection status - Object.defineProperty(this, 'connected', { - get: function () { - return this.connection && this.connection.readyState === this.connection.OPEN; - }, - enumerable: true, - }); -}; - -/** - Will add the error and end event to timeout existing calls - - @method addDefaultEvents - */ -WebsocketProvider.prototype.addDefaultEvents = function(){ - var _this = this; - - this.connection.onerror = function(){ - _this._timeout(); - }; - - this.connection.onclose = function(){ - _this._timeout(); - - // reset all requests and callbacks - _this.reset(); - }; - - // this.connection.on('timeout', function(){ - // _this._timeout(); - // }); -}; - -/** - Will parse the response and make an array out of it. - - @method _parseResponse - @param {String} data - */ -WebsocketProvider.prototype._parseResponse = function(data) { - var _this = this, - returnValues = []; - - // DE-CHUNKER - var dechunkedData = data - .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ - .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ - .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ - .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ - .split('|--|'); - - dechunkedData.forEach(function(data){ - - // prepend the last chunk - if(_this.lastChunk) - data = _this.lastChunk + data; - - var result = null; - - try { - result = JSON.parse(data); - - } catch(e) { - - _this.lastChunk = data; - - // start timeout to cancel all requests - clearTimeout(_this.lastChunkTimeout); - _this.lastChunkTimeout = setTimeout(function(){ - _this._timeout(); - throw errors.InvalidResponse(data); - }, 1000 * 15); - - return; - } - - // cancel timeout and set chunk to null - clearTimeout(_this.lastChunkTimeout); - _this.lastChunk = null; - - if(result) - returnValues.push(result); - }); - - return returnValues; -}; - - -/** - Adds a callback to the responseCallbacks object, - which will be called if a response matching the response Id will arrive. - - @method _addResponseCallback - */ -WebsocketProvider.prototype._addResponseCallback = function(payload, callback) { - var id = payload.id || payload[0].id; - var method = payload.method || payload[0].method; - - this.responseCallbacks[id] = callback; - this.responseCallbacks[id].method = method; - - var _this = this; - - // schedule triggering the error response if a custom timeout is set - if (this._customTimeout) { - setTimeout(function () { - if (_this.responseCallbacks[id]) { - _this.responseCallbacks[id](errors.ConnectionTimeout(_this._customTimeout)); - delete _this.responseCallbacks[id]; - } - }, this._customTimeout); - } -}; - -/** - Timeout all requests when the end/error event is fired - - @method _timeout - */ -WebsocketProvider.prototype._timeout = function() { - for(var key in this.responseCallbacks) { - if(this.responseCallbacks.hasOwnProperty(key)){ - this.responseCallbacks[key](errors.InvalidConnection('on WS')); - delete this.responseCallbacks[key]; - } - } -}; - - -WebsocketProvider.prototype.send = function (payload, callback) { - var _this = this; - - if (this.connection.readyState === this.connection.CONNECTING) { - setTimeout(function () { - _this.send(payload, callback); - }, 10); - return; - } - - // try reconnect, when connection is gone - // if(!this.connection.writable) - // this.connection.connect({url: this.url}); - if (this.connection.readyState !== this.connection.OPEN) { - console.error('connection not open on send()'); - if (typeof this.connection.onerror === 'function') { - this.connection.onerror(new Error('connection not open')); - } else { - console.error('no error callback'); - } - callback(new Error('connection not open')); - return; - } - - this.connection.send(JSON.stringify(payload)); - this._addResponseCallback(payload, callback); -}; - -/** - Subscribes to provider events.provider - - @method on - @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' - @param {Function} callback the callback to call - */ -WebsocketProvider.prototype.on = function (type, callback) { - - if(typeof callback !== 'function') - throw new Error('The second parameter callback must be a function.'); - - switch(type){ - case 'data': - this.notificationCallbacks.push(callback); - break; - - case 'connect': - this.connection.onopen = callback; - break; - - case 'end': - this.connection.onclose = callback; - break; - - case 'error': - this.connection.onerror = callback; - break; - - // default: - // this.connection.on(type, callback); - // break; - } -}; - -// TODO add once - -/** - Removes event listener - - @method removeListener - @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' - @param {Function} callback the callback to call - */ -WebsocketProvider.prototype.removeListener = function (type, callback) { - var _this = this; - - switch(type){ - case 'data': - this.notificationCallbacks.forEach(function(cb, index){ - if(cb === callback) - _this.notificationCallbacks.splice(index, 1); - }); - break; - - // TODO remvoving connect missing - - // default: - // this.connection.removeListener(type, callback); - // break; - } -}; - -/** - Removes all event listeners - - @method removeAllListeners - @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' - */ -WebsocketProvider.prototype.removeAllListeners = function (type) { - switch(type){ - case 'data': - this.notificationCallbacks = []; - break; - - // TODO remvoving connect properly missing - - case 'connect': - this.connection.onopen = null; - break; - - case 'end': - this.connection.onclose = null; - break; - - case 'error': - this.connection.onerror = null; - break; - - default: - // this.connection.removeAllListeners(type); - break; - } -}; - -/** - Resets the providers, clears all callbacks - - @method reset - */ -WebsocketProvider.prototype.reset = function () { - this._timeout(); - this.notificationCallbacks = []; - - // this.connection.removeAllListeners('error'); - // this.connection.removeAllListeners('end'); - // this.connection.removeAllListeners('timeout'); - - this.addDefaultEvents(); -}; - -WebsocketProvider.prototype.disconnect = function () { - if (this.connection) { - this.connection.close(); - } -}; - -module.exports = WebsocketProvider; - -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":1438,"buffer":217,"underscore":1765,"url":1769,"web3-core-helpers":1792,"websocket":1841}],1833:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -"use strict"; - -var core = require('web3-core'); -var Subscriptions = require('web3-core-subscriptions').subscriptions; -var Method = require('web3-core-method'); -// var formatters = require('web3-core-helpers').formatters; -var Net = require('web3-net'); - - -var Shh = function Shh() { - var _this = this; - - // sets _requestmanager - core.packageInit(this, arguments); - - // overwrite setProvider - var setProvider = this.setProvider; - this.setProvider = function () { - setProvider.apply(_this, arguments); - _this.net.setProvider.apply(_this, arguments); - }; - - this.net = new Net(this.currentProvider); - - [ - new Subscriptions({ - name: 'subscribe', - type: 'shh', - subscriptions: { - 'messages': { - params: 1 - // inputFormatter: [formatters.inputPostFormatter], - // outputFormatter: formatters.outputPostFormatter - } - } - }), - - new Method({ - name: 'getVersion', - call: 'shh_version', - params: 0 - }), - new Method({ - name: 'getInfo', - call: 'shh_info', - params: 0 - }), - new Method({ - name: 'setMaxMessageSize', - call: 'shh_setMaxMessageSize', - params: 1 - }), - new Method({ - name: 'setMinPoW', - call: 'shh_setMinPoW', - params: 1 - }), - new Method({ - name: 'markTrustedPeer', - call: 'shh_markTrustedPeer', - params: 1 - }), - new Method({ - name: 'newKeyPair', - call: 'shh_newKeyPair', - params: 0 - }), - new Method({ - name: 'addPrivateKey', - call: 'shh_addPrivateKey', - params: 1 - }), - new Method({ - name: 'deleteKeyPair', - call: 'shh_deleteKeyPair', - params: 1 - }), - new Method({ - name: 'hasKeyPair', - call: 'shh_hasKeyPair', - params: 1 - }), - new Method({ - name: 'getPublicKey', - call: 'shh_getPublicKey', - params: 1 - }), - new Method({ - name: 'getPrivateKey', - call: 'shh_getPrivateKey', - params: 1 - }), - new Method({ - name: 'newSymKey', - call: 'shh_newSymKey', - params: 0 - }), - new Method({ - name: 'addSymKey', - call: 'shh_addSymKey', - params: 1 - }), - new Method({ - name: 'generateSymKeyFromPassword', - call: 'shh_generateSymKeyFromPassword', - params: 1 - }), - new Method({ - name: 'hasSymKey', - call: 'shh_hasSymKey', - params: 1 - }), - new Method({ - name: 'getSymKey', - call: 'shh_getSymKey', - params: 1 - }), - new Method({ - name: 'deleteSymKey', - call: 'shh_deleteSymKey', - params: 1 - }), - - new Method({ - name: 'newMessageFilter', - call: 'shh_newMessageFilter', - params: 1 - }), - new Method({ - name: 'getFilterMessages', - call: 'shh_getFilterMessages', - params: 1 - }), - new Method({ - name: 'deleteMessageFilter', - call: 'shh_deleteMessageFilter', - params: 1 - }), - - new Method({ - name: 'post', - call: 'shh_post', - params: 1, - inputFormatter: [null] - }), - - new Method({ - name: 'unsubscribe', - call: 'shh_unsubscribe', - params: 1 - }) - ].forEach(function(method) { - method.attachToObject(_this); - method.setRequestManager(_this._requestManager); - }); -}; - -Shh.prototype.clearSubscriptions = function () { - this._requestManager.clearSubscriptions(); -}; - -core.addProviders(Shh); - - - -module.exports = Shh; - - - -},{"web3-core":1802,"web3-core-method":1793,"web3-core-subscriptions":1799,"web3-net":1829}],1834:[function(require,module,exports){ -arguments[4][334][0].apply(exports,arguments) -},{"dup":334}],1835:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file utils.js - * @author Marek Kotewicz - * @author Fabian Vogelsteller - * @date 2017 - */ - - -var _ = require('underscore'); -var ethjsUnit = require('ethjs-unit'); -var utils = require('./utils.js'); -var soliditySha3 = require('./soliditySha3.js'); -var randomHex = require('randomhex'); - - - -/** - * Fires an error in an event emitter and callback and returns the eventemitter - * - * @method _fireError - * @param {Object} error a string, a error, or an object with {message, data} - * @param {Object} emitter - * @param {Function} reject - * @param {Function} callback - * @return {Object} the emitter - */ -var _fireError = function (error, emitter, reject, callback) { - /*jshint maxcomplexity: 10 */ - - // add data if given - if(_.isObject(error) && !(error instanceof Error) && error.data) { - if(_.isObject(error.data) || _.isArray(error.data)) { - error.data = JSON.stringify(error.data, null, 2); - } - - error = error.message +"\n"+ error.data; - } - - if(_.isString(error)) { - error = new Error(error); - } - - if (_.isFunction(callback)) { - callback(error); - } - if (_.isFunction(reject)) { - // suppress uncatched error if an error listener is present - // OR suppress uncatched error if an callback listener is present - if (emitter && - (_.isFunction(emitter.listeners) && - emitter.listeners('error').length) || _.isFunction(callback)) { - emitter.catch(function(){}); - } - // reject later, to be able to return emitter - setTimeout(function () { - reject(error); - }, 1); - } - - if(emitter && _.isFunction(emitter.emit)) { - // emit later, to be able to return emitter - setTimeout(function () { - emitter.emit('error', error); - emitter.removeAllListeners(); - }, 1); - } - - return emitter; -}; - -/** - * Should be used to create full function/event name from json abi - * - * @method _jsonInterfaceMethodToString - * @param {Object} json - * @return {String} full function/event name - */ -var _jsonInterfaceMethodToString = function (json) { - if (_.isObject(json) && json.name && json.name.indexOf('(') !== -1) { - return json.name; - } - - return json.name + '(' + _flattenTypes(false, json.inputs).join(',') + ')'; -}; - - -/** - * Should be used to flatten json abi inputs/outputs into an array of type-representing-strings - * - * @method _flattenTypes - * @param {bool} includeTuple - * @param {Object} puts - * @return {Array} parameters as strings - */ -var _flattenTypes = function(includeTuple, puts) -{ - // console.log("entered _flattenTypes. inputs/outputs: " + puts) - var types = []; - - puts.forEach(function(param) { - if (typeof param.components === 'object') { - if (param.type.substring(0, 5) !== 'tuple') { - throw new Error('components found but type is not tuple; report on GitHub'); - } - var suffix = ''; - var arrayBracket = param.type.indexOf('['); - if (arrayBracket >= 0) { suffix = param.type.substring(arrayBracket); } - var result = _flattenTypes(includeTuple, param.components); - // console.log("result should have things: " + result) - if(_.isArray(result) && includeTuple) { - // console.log("include tuple word, and its an array. joining...: " + result.types) - types.push('tuple(' + result.join(',') + ')' + suffix); - } - else if(!includeTuple) { - // console.log("don't include tuple, but its an array. joining...: " + result) - types.push('(' + result.join(',') + ')' + suffix); - } - else { - // console.log("its a single type within a tuple: " + result.types) - types.push('(' + result + ')'); - } - } else { - // console.log("its a type and not directly in a tuple: " + param.type) - types.push(param.type); - } - }); - - return types; -}; - - -/** - * Should be called to get ascii from it's hex representation - * - * @method hexToAscii - * @param {String} hex - * @returns {String} ascii string representation of hex value - */ -var hexToAscii = function(hex) { - if (!utils.isHexStrict(hex)) - throw new Error('The parameter must be a valid HEX string.'); - - var str = ""; - var i = 0, l = hex.length; - if (hex.substring(0, 2) === '0x') { - i = 2; - } - for (; i < l; i+=2) { - var code = parseInt(hex.substr(i, 2), 16); - str += String.fromCharCode(code); - } - - return str; -}; - -/** - * Should be called to get hex representation (prefixed by 0x) of ascii string - * - * @method asciiToHex - * @param {String} str - * @returns {String} hex representation of input string - */ -var asciiToHex = function(str) { - if(!str) - return "0x00"; - var hex = ""; - for(var i = 0; i < str.length; i++) { - var code = str.charCodeAt(i); - var n = code.toString(16); - hex += n.length < 2 ? '0' + n : n; - } - - return "0x" + hex; -}; - - - -/** - * Returns value of unit in Wei - * - * @method getUnitValue - * @param {String} unit the unit to convert to, default ether - * @returns {BN} value of the unit (in Wei) - * @throws error if the unit is not correct:w - */ -var getUnitValue = function (unit) { - unit = unit ? unit.toLowerCase() : 'ether'; - if (!ethjsUnit.unitMap[unit]) { - throw new Error('This unit "'+ unit +'" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); - } - return unit; -}; - -/** - * Takes a number of wei and converts it to any other ether unit. - * - * Possible units are: - * SI Short SI Full Effigy Other - * - kwei femtoether babbage - * - mwei picoether lovelace - * - gwei nanoether shannon nano - * - -- microether szabo micro - * - -- milliether finney milli - * - ether -- -- - * - kether -- grand - * - mether - * - gether - * - tether - * - * @method fromWei - * @param {Number|String} number can be a number, number string or a HEX of a decimal - * @param {String} unit the unit to convert to, default ether - * @return {String|Object} When given a BN object it returns one as well, otherwise a number - */ -var fromWei = function(number, unit) { - unit = getUnitValue(unit); - - if(!utils.isBN(number) && !_.isString(number)) { - throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.'); - } - - return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); -}; - -/** - * Takes a number of a unit and converts it to wei. - * - * Possible units are: - * SI Short SI Full Effigy Other - * - kwei femtoether babbage - * - mwei picoether lovelace - * - gwei nanoether shannon nano - * - -- microether szabo micro - * - -- microether szabo micro - * - -- milliether finney milli - * - ether -- -- - * - kether -- grand - * - mether - * - gether - * - tether - * - * @method toWei - * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal - * @param {String} unit the unit to convert from, default ether - * @return {String|Object} When given a BN object it returns one as well, otherwise a number - */ -var toWei = function(number, unit) { - unit = getUnitValue(unit); - - if(!utils.isBN(number) && !_.isString(number)) { - throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.'); - } - - return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10); -}; - - - - -/** - * Converts to a checksum address - * - * @method toChecksumAddress - * @param {String} address the given HEX address - * @return {String} - */ -var toChecksumAddress = function (address) { - if (typeof address === 'undefined') return ''; - - if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) - throw new Error('Given address "'+ address +'" is not a valid Ethereum address.'); - - - - address = address.toLowerCase().replace(/^0x/i,''); - var addressHash = utils.sha3(address).replace(/^0x/i,''); - var checksumAddress = '0x'; - - for (var i = 0; i < address.length; i++ ) { - // If ith character is 9 to f then make it uppercase - if (parseInt(addressHash[i], 16) > 7) { - checksumAddress += address[i].toUpperCase(); - } else { - checksumAddress += address[i]; - } - } - return checksumAddress; -}; - - - -module.exports = { - _fireError: _fireError, - _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, - _flattenTypes: _flattenTypes, - // extractDisplayName: extractDisplayName, - // extractTypeName: extractTypeName, - randomHex: randomHex, - _: _, - BN: utils.BN, - isBN: utils.isBN, - isBigNumber: utils.isBigNumber, - isHex: utils.isHex, - isHexStrict: utils.isHexStrict, - sha3: utils.sha3, - keccak256: utils.sha3, - soliditySha3: soliditySha3, - isAddress: utils.isAddress, - checkAddressChecksum: utils.checkAddressChecksum, - toChecksumAddress: toChecksumAddress, - toHex: utils.toHex, - toBN: utils.toBN, - - bytesToHex: utils.bytesToHex, - hexToBytes: utils.hexToBytes, - - hexToNumberString: utils.hexToNumberString, - - hexToNumber: utils.hexToNumber, - toDecimal: utils.hexToNumber, // alias - - numberToHex: utils.numberToHex, - fromDecimal: utils.numberToHex, // alias - - hexToUtf8: utils.hexToUtf8, - hexToString: utils.hexToUtf8, - toUtf8: utils.hexToUtf8, - - utf8ToHex: utils.utf8ToHex, - stringToHex: utils.utf8ToHex, - fromUtf8: utils.utf8ToHex, - - hexToAscii: hexToAscii, - toAscii: hexToAscii, - asciiToHex: asciiToHex, - fromAscii: asciiToHex, - - unitMap: ethjsUnit.unitMap, - toWei: toWei, - fromWei: fromWei, - - padLeft: utils.leftPad, - leftPad: utils.leftPad, - padRight: utils.rightPad, - rightPad: utils.rightPad, - toTwosComplement: utils.toTwosComplement -}; - - -},{"./soliditySha3.js":1836,"./utils.js":1837,"ethjs-unit":367,"randomhex":1556,"underscore":1765}],1836:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file soliditySha3.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -var _ = require('underscore'); -var BN = require('bn.js'); -var utils = require('./utils.js'); - - -var _elementaryName = function (name) { - /*jshint maxcomplexity:false */ - - if (name.startsWith('int[')) { - return 'int256' + name.slice(3); - } else if (name === 'int') { - return 'int256'; - } else if (name.startsWith('uint[')) { - return 'uint256' + name.slice(4); - } else if (name === 'uint') { - return 'uint256'; - } else if (name.startsWith('fixed[')) { - return 'fixed128x128' + name.slice(5); - } else if (name === 'fixed') { - return 'fixed128x128'; - } else if (name.startsWith('ufixed[')) { - return 'ufixed128x128' + name.slice(6); - } else if (name === 'ufixed') { - return 'ufixed128x128'; - } - return name; -}; - -// Parse N from type -var _parseTypeN = function (type) { - var typesize = /^\D+(\d+).*$/.exec(type); - return typesize ? parseInt(typesize[1], 10) : null; -}; - -// Parse N from type[] -var _parseTypeNArray = function (type) { - var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type); - return arraySize ? parseInt(arraySize[1], 10) : null; -}; - -var _parseNumber = function (arg) { - var type = typeof arg; - if (type === 'string') { - if (utils.isHexStrict(arg)) { - return new BN(arg.replace(/0x/i,''), 16); - } else { - return new BN(arg, 10); - } - } else if (type === 'number') { - return new BN(arg); - } else if (utils.isBigNumber(arg)) { - return new BN(arg.toString(10)); - } else if (utils.isBN(arg)) { - return arg; - } else { - throw new Error(arg +' is not a number'); - } -}; - -var _solidityPack = function (type, value, arraySize) { - /*jshint maxcomplexity:false */ - - var size, num; - type = _elementaryName(type); - - - if (type === 'bytes') { - - if (value.replace(/^0x/i,'').length % 2 !== 0) { - throw new Error('Invalid bytes characters '+ value.length); - } - - return value; - } else if (type === 'string') { - return utils.utf8ToHex(value); - } else if (type === 'bool') { - return value ? '01' : '00'; - } else if (type.startsWith('address')) { - if(arraySize) { - size = 64; - } else { - size = 40; - } - - if(!utils.isAddress(value)) { - throw new Error(value +' is not a valid address, or the checksum is invalid.'); - } - - return utils.leftPad(value.toLowerCase(), size); - } - - size = _parseTypeN(type); - - if (type.startsWith('bytes')) { - - if(!size) { - throw new Error('bytes[] not yet supported in solidity'); - } - - // must be 32 byte slices when in an array - if(arraySize) { - size = 32; - } - - if (size < 1 || size > 32 || size < value.replace(/^0x/i,'').length / 2 ) { - throw new Error('Invalid bytes' + size +' for '+ value); - } - - return utils.rightPad(value, size * 2); - } else if (type.startsWith('uint')) { - - if ((size % 8) || (size < 8) || (size > 256)) { - throw new Error('Invalid uint'+size+' size'); - } - - num = _parseNumber(value); - if (num.bitLength() > size) { - throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()); - } - - if(num.lt(new BN(0))) { - throw new Error('Supplied uint '+ num.toString() +' is negative'); - } - - return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; - } else if (type.startsWith('int')) { - - if ((size % 8) || (size < 8) || (size > 256)) { - throw new Error('Invalid int'+size+' size'); - } - - num = _parseNumber(value); - if (num.bitLength() > size) { - throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()); - } - - if(num.lt(new BN(0))) { - return num.toTwos(size).toString('hex'); - } else { - return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; - } - - } else { - // FIXME: support all other types - throw new Error('Unsupported or invalid type: ' + type); - } -}; - - -var _processSoliditySha3Args = function (arg) { - /*jshint maxcomplexity:false */ - - if(_.isArray(arg)) { - throw new Error('Autodetection of array types is not supported.'); - } - - var type, value = ''; - var hexArg, arraySize; - - // if type is given - if (_.isObject(arg) && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) { - type = arg.hasOwnProperty('t') ? arg.t : arg.type; - value = arg.hasOwnProperty('v') ? arg.v : arg.value; - - // otherwise try to guess the type - } else { - - type = utils.toHex(arg, true); - value = utils.toHex(arg); - - if (!type.startsWith('int') && !type.startsWith('uint')) { - type = 'bytes'; - } - } - - if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) { - value = new BN(value); - } - - // get the array size - if(_.isArray(value)) { - arraySize = _parseTypeNArray(type); - if(arraySize && value.length !== arraySize) { - throw new Error(type +' is not matching the given array '+ JSON.stringify(value)); - } else { - arraySize = value.length; - } - } - - - if (_.isArray(value)) { - hexArg = value.map(function (val) { - return _solidityPack(type, val, arraySize).toString('hex').replace('0x',''); - }); - return hexArg.join(''); - } else { - hexArg = _solidityPack(type, value, arraySize); - return hexArg.toString('hex').replace('0x',''); - } - -}; - -/** - * Hashes solidity values to a sha3 hash using keccak 256 - * - * @method soliditySha3 - * @return {Object} the sha3 - */ -var soliditySha3 = function () { - /*jshint maxcomplexity:false */ - - var args = Array.prototype.slice.call(arguments); - - var hexArgs = _.map(args, _processSoliditySha3Args); - - // console.log(args, hexArgs); - // console.log('0x'+ hexArgs.join('')); - - return utils.sha3('0x'+ hexArgs.join('')); -}; - - -module.exports = soliditySha3; - -},{"./utils.js":1837,"bn.js":171,"underscore":1765}],1837:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . - */ -/** - * @file utils.js - * @author Fabian Vogelsteller - * @date 2017 - */ - -var _ = require('underscore'); -var BN = require('bn.js'); -var numberToBN = require('number-to-bn'); -var utf8 = require('utf8'); -var Hash = require("eth-lib/lib/hash"); - - -/** - * Returns true if object is BN, otherwise false - * - * @method isBN - * @param {Object} object - * @return {Boolean} - */ -var isBN = function (object) { - return object instanceof BN || - (object && object.constructor && object.constructor.name === 'BN'); -}; - -/** - * Returns true if object is BigNumber, otherwise false - * - * @method isBigNumber - * @param {Object} object - * @return {Boolean} - */ -var isBigNumber = function (object) { - return object && object.constructor && object.constructor.name === 'BigNumber'; -}; - -/** - * Takes an input and transforms it into an BN - * - * @method toBN - * @param {Number|String|BN} number, string, HEX string or BN - * @return {BN} BN - */ -var toBN = function(number){ - try { - return numberToBN.apply(null, arguments); - } catch(e) { - throw new Error(e + ' Given value: "'+ number +'"'); - } -}; - - -/** - * Takes and input transforms it into BN and if it is negative value, into two's complement - * - * @method toTwosComplement - * @param {Number|String|BN} number - * @return {String} - */ -var toTwosComplement = function (number) { - return '0x'+ toBN(number).toTwos(256).toString(16, 64); -}; - -/** - * Checks if the given string is an address - * - * @method isAddress - * @param {String} address the given HEX address - * @return {Boolean} - */ -var isAddress = function (address) { - // check if it has the basic requirements of an address - if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { - return false; - // If it's ALL lowercase or ALL upppercase - } else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { - return true; - // Otherwise check each case - } else { - return checkAddressChecksum(address); - } -}; - - - -/** - * Checks if the given string is a checksummed address - * - * @method checkAddressChecksum - * @param {String} address the given HEX address - * @return {Boolean} - */ -var checkAddressChecksum = function (address) { - // Check each case - address = address.replace(/^0x/i,''); - var addressHash = sha3(address.toLowerCase()).replace(/^0x/i,''); - - for (var i = 0; i < 40; i++ ) { - // the nth letter should be uppercase if the nth digit of casemap is 1 - if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { - return false; - } - } - return true; -}; - -/** - * Should be called to pad string to expected length - * - * @method leftPad - * @param {String} string to be padded - * @param {Number} chars that result string should have - * @param {String} sign, by default 0 - * @returns {String} right aligned string - */ -var leftPad = function (string, chars, sign) { - var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; - string = string.toString(16).replace(/^0x/i,''); - - var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; - - return (hasPrefix ? '0x' : '') + new Array(padding).join(sign ? sign : "0") + string; -}; - -/** - * Should be called to pad string to expected length - * - * @method rightPad - * @param {String} string to be padded - * @param {Number} chars that result string should have - * @param {String} sign, by default 0 - * @returns {String} right aligned string - */ -var rightPad = function (string, chars, sign) { - var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; - string = string.toString(16).replace(/^0x/i,''); - - var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; - - return (hasPrefix ? '0x' : '') + string + (new Array(padding).join(sign ? sign : "0")); -}; - - -/** - * Should be called to get hex representation (prefixed by 0x) of utf8 string - * - * @method utf8ToHex - * @param {String} str - * @returns {String} hex representation of input string - */ -var utf8ToHex = function(str) { - str = utf8.encode(str); - var hex = ""; - - // remove \u0000 padding from either side - str = str.replace(/^(?:\u0000)*/,''); - str = str.split("").reverse().join(""); - str = str.replace(/^(?:\u0000)*/,''); - str = str.split("").reverse().join(""); - - for(var i = 0; i < str.length; i++) { - var code = str.charCodeAt(i); - // if (code !== 0) { - var n = code.toString(16); - hex += n.length < 2 ? '0' + n : n; - // } - } - - return "0x" + hex; -}; - -/** - * Should be called to get utf8 from it's hex representation - * - * @method hexToUtf8 - * @param {String} hex - * @returns {String} ascii string representation of hex value - */ -var hexToUtf8 = function(hex) { - if (!isHexStrict(hex)) - throw new Error('The parameter "'+ hex +'" must be a valid HEX string.'); - - var str = ""; - var code = 0; - hex = hex.replace(/^0x/i,''); - - // remove 00 padding from either side - hex = hex.replace(/^(?:00)*/,''); - hex = hex.split("").reverse().join(""); - hex = hex.replace(/^(?:00)*/,''); - hex = hex.split("").reverse().join(""); - - var l = hex.length; - - for (var i=0; i < l; i+=2) { - code = parseInt(hex.substr(i, 2), 16); - // if (code !== 0) { - str += String.fromCharCode(code); - // } - } - - return utf8.decode(str); -}; - - -/** - * Converts value to it's number representation - * - * @method hexToNumber - * @param {String|Number|BN} value - * @return {String} - */ -var hexToNumber = function (value) { - if (!value) { - return value; - } - - return toBN(value).toNumber(); -}; - -/** - * Converts value to it's decimal representation in string - * - * @method hexToNumberString - * @param {String|Number|BN} value - * @return {String} - */ -var hexToNumberString = function (value) { - if (!value) return value; - - return toBN(value).toString(10); -}; - - -/** - * Converts value to it's hex representation - * - * @method numberToHex - * @param {String|Number|BN} value - * @return {String} - */ -var numberToHex = function (value) { - if (_.isNull(value) || _.isUndefined(value)) { - return value; - } - - if (!isFinite(value) && !isHexStrict(value)) { - throw new Error('Given input "'+value+'" is not a number.'); - } - - var number = toBN(value); - var result = number.toString(16); - - return number.lt(new BN(0)) ? '-0x' + result.substr(1) : '0x' + result; -}; - - -/** - * Convert a byte array to a hex string - * - * Note: Implementation from crypto-js - * - * @method bytesToHex - * @param {Array} bytes - * @return {String} the hex string - */ -var bytesToHex = function(bytes) { - for (var hex = [], i = 0; i < bytes.length; i++) { - /* jshint ignore:start */ - hex.push((bytes[i] >>> 4).toString(16)); - hex.push((bytes[i] & 0xF).toString(16)); - /* jshint ignore:end */ - } - return '0x'+ hex.join(""); -}; - -/** - * Convert a hex string to a byte array - * - * Note: Implementation from crypto-js - * - * @method hexToBytes - * @param {string} hex - * @return {Array} the byte array - */ -var hexToBytes = function(hex) { - hex = hex.toString(16); - - if (!isHexStrict(hex)) { - throw new Error('Given value "'+ hex +'" is not a valid hex string.'); - } - - hex = hex.replace(/^0x/i,''); - - for (var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); - return bytes; -}; - -/** - * Auto converts any given value into it's hex representation. - * - * And even stringifys objects before. - * - * @method toHex - * @param {String|Number|BN|Object} value - * @param {Boolean} returnType - * @return {String} - */ -var toHex = function (value, returnType) { - /*jshint maxcomplexity: false */ - - if (isAddress(value)) { - return returnType ? 'address' : '0x'+ value.toLowerCase().replace(/^0x/i,''); - } - - if (_.isBoolean(value)) { - return returnType ? 'bool' : value ? '0x01' : '0x00'; - } - - - if (_.isObject(value) && !isBigNumber(value) && !isBN(value)) { - return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); - } - - // if its a negative number, pass it through numberToHex - if (_.isString(value)) { - if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) { - return returnType ? 'int256' : numberToHex(value); - } else if(value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { - return returnType ? 'bytes' : value; - } else if (!isFinite(value)) { - return returnType ? 'string' : utf8ToHex(value); - } - } - - return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); -}; - - -/** - * Check if string is HEX, requires a 0x in front - * - * @method isHexStrict - * @param {String} hex to be checked - * @returns {Boolean} - */ -var isHexStrict = function (hex) { - return ((_.isString(hex) || _.isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex)); -}; - -/** - * Check if string is HEX - * - * @method isHex - * @param {String} hex to be checked - * @returns {Boolean} - */ -var isHex = function (hex) { - return ((_.isString(hex) || _.isNumber(hex)) && /^(-0x|0x)?[0-9a-f]*$/i.test(hex)); -}; - - -/** - * Returns true if given string is a valid Ethereum block header bloom. - * - * TODO UNDOCUMENTED - * - * @method isBloom - * @param {String} hex encoded bloom filter - * @return {Boolean} - */ -var isBloom = function (bloom) { - if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { - return false; - } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { - return true; - } - return false; -}; - -/** - * Returns true if given string is a valid log topic. - * - * TODO UNDOCUMENTED - * - * @method isTopic - * @param {String} hex encoded topic - * @return {Boolean} - */ -var isTopic = function (topic) { - if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { - return false; - } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { - return true; - } - return false; -}; - - -/** - * Hashes values to a sha3 hash using keccak 256 - * - * To hash a HEX string the hex must have 0x in front. - * - * @method sha3 - * @return {String} the sha3 string - */ -var SHA3_NULL_S = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; - -var sha3 = function (value) { - if (isBN(value)) { - value = value.toString(); - } - - if (isHexStrict(value) && /^0x/i.test((value).toString())) { - value = hexToBytes(value); - } - - var returnValue = Hash.keccak256(value); // jshint ignore:line - - if(returnValue === SHA3_NULL_S) { - return null; - } else { - return returnValue; - } -}; -// expose the under the hood keccak256 -sha3._Hash = Hash; - - -module.exports = { - BN: BN, - isBN: isBN, - isBigNumber: isBigNumber, - toBN: toBN, - isAddress: isAddress, - isBloom: isBloom, // TODO UNDOCUMENTED - isTopic: isTopic, // TODO UNDOCUMENTED - checkAddressChecksum: checkAddressChecksum, - utf8ToHex: utf8ToHex, - hexToUtf8: hexToUtf8, - hexToNumber: hexToNumber, - hexToNumberString: hexToNumberString, - numberToHex: numberToHex, - toHex: toHex, - hexToBytes: hexToBytes, - bytesToHex: bytesToHex, - isHex: isHex, - isHexStrict: isHexStrict, - leftPad: leftPad, - rightPad: rightPad, - toTwosComplement: toTwosComplement, - sha3: sha3 -}; - -},{"bn.js":171,"eth-lib/lib/hash":1834,"number-to-bn":1386,"underscore":1765,"utf8":1772}],1838:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - "web3", - "/var/www/html/ethoFSV2" - ] - ], - "_from": "web3@latest", - "_hasShrinkwrap": false, - "_id": "web3@1.2.1", - "_inCache": true, - "_installable": true, - "_location": "/web3", - "_nodeVersion": "10.16.0", - "_npmOperationalInternal": { - "host": "s3://npm-registry-packages", - "tmp": "tmp/web3_1.2.1_1565085131334_0.13749713127512586" - }, - "_npmUser": { - "email": "samuel@ethereum.org", - "name": "nivida" - }, - "_npmVersion": "6.9.0", - "_phantomChildren": {}, - "_requested": { - "name": "web3", - "raw": "web3", - "rawSpec": "", - "scope": null, - "spec": "latest", - "type": "tag" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmjs.org/web3/-/web3-1.2.1.tgz", - "_shasum": "5d8158bcca47838ab8c2b784a2dee4c3ceb4179b", - "_shrinkwrap": null, - "_spec": "web3", - "_where": "/var/www/html/ethoFSV2", - "author": { - "name": "ethereum.org" - }, - "authors": [ - { - "name": "Fabian Vogelsteller", - "email": "fabian@ethereum.org", - "homepage": "http://frozeman.de" - }, - { - "name": "Marek Kotewicz", - "email": "marek@parity.io", - "url": "https://github.com/debris" - }, - { - "name": "Marian Oancea", - "url": "https://github.com/cubedro" - }, - { - "name": "Gav Wood", - "email": "g@parity.io", - "homepage": "http://gavwood.com" - }, - { - "name": "Jeffery Wilcke", - "email": "jeffrey.wilcke@ethereum.org", - "url": "https://github.com/obscuren" - } - ], - "bugs": { - "url": "https://github.com/ethereum/web3.js/issues" - }, - "dependencies": { - "web3-bzz": "1.2.1", - "web3-core": "1.2.1", - "web3-eth": "1.2.1", - "web3-eth-personal": "1.2.1", - "web3-net": "1.2.1", - "web3-shh": "1.2.1", - "web3-utils": "1.2.1" - }, - "description": "Ethereum JavaScript API", - "devDependencies": {}, - "directories": {}, - "dist": { - "fileCount": 3, - "integrity": "sha512-nNMzeCK0agb5i/oTWNdQ1aGtwYfXzHottFP2Dz0oGIzavPMGSKyVlr8ibVb1yK5sJBjrWVnTdGaOC2zKDFuFRw==", - "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdSU3LCRA9TVsSAnZWagAAfssQAJFyl0p7/pXsXDx5wOXk\nV8cHpombPyBd0DvgwdKp0NGpkA829EduJfnGJvvO4IoSlZu+f802vy3cTaT3\nwFUAkVDx1Wf/qGlxlZgoe7F0ptsA+Pwaia4vKY7oocBee++/hKANDRl/WW+s\n04VWtUowSW29AS9q2N4E14yB3zN9P+WnPcg59cUvUJU++e2EszZ5+9HVKJOF\nJNudQW5dIb2lgk4Sf0zYhtpd2DcyTCLeqMolXSvUrKu5atYb5hBB0ClbWjjT\nYvmflYDY4G/34gE41E1wJweE6o9ZYvFGU1A8KlGsE9ULuemldcIYoJNL559w\ntDBR98ARkdqdf54hl3TVNs5BycbTCfydz7TvFSzMqYMlMOoSDbh7/sC8pV6U\nwepPTTFLPYOr6X/U+5rfv59qxVxZ7ukNikupR4ACSS94aX1lMaxbKUMEaqVs\nRB9Xw6LJnyoIgcIX7w68vTwcQpyph2iTfMWjBh+axhCRgVBWVLS+6iGR6gWT\nC+ZnX70lg6yR3lhR6eWS5qnFk+FO5Yam1iZjjMixn0XOqlsnoAqWidFfRIrT\nMQflFN4o5TK24PM6U6mwkVXspx0TjXjn/mWY9+FIkVLkf83jfCPfMOm1gej5\n6f8akj5XX8h1aJPqTWfC7ou04njnkYKvuPCmwuLhlYtEWqX4adBgU9mvyUA1\nemOc\r\n=OZ/P\r\n-----END PGP SIGNATURE-----\r\n", - "shasum": "5d8158bcca47838ab8c2b784a2dee4c3ceb4179b", - "tarball": "https://registry.npmjs.org/web3/-/web3-1.2.1.tgz", - "unpackedSize": 3766 - }, - "engines": { - "node": ">=8.0.0" - }, - "keywords": [ - "API", - "Ethereum", - "JavaScript" - ], - "license": "LGPL-3.0", - "main": "src/index.js", - "maintainers": [ - { - "name": "frozeman", - "email": "fabian@frozeman.de" - }, - { - "name": "nivida", - "email": "samuel@ethereum.org" - } - ], - "name": "web3", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "https://github.com/ethereum/web3.js/tree/1.x/packages/web3" - }, - "version": "1.2.1" -} - -},{}],1839:[function(require,module,exports){ -/* - This file is part of web3.js. - - web3.js is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - web3.js is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with web3.js. If not, see . -*/ -/** - * @file index.js - * @authors: - * Fabian Vogelsteller - * Gav Wood - * Jeffrey Wilcke - * Marek Kotewicz - * Marian Oancea - * @date 2017 - */ - -"use strict"; - - -var version = require('../package.json').version; -var core = require('web3-core'); -var Eth = require('web3-eth'); -var Net = require('web3-net'); -var Personal = require('web3-eth-personal'); -var Shh = require('web3-shh'); -var Bzz = require('web3-bzz'); -var utils = require('web3-utils'); - -var Web3 = function Web3() { - var _this = this; - - // sets _requestmanager etc - core.packageInit(this, arguments); - - this.version = version; - this.utils = utils; - - this.eth = new Eth(this); - this.shh = new Shh(this); - this.bzz = new Bzz(this); - - // overwrite package setProvider - var setProvider = this.setProvider; - this.setProvider = function (provider, net) { - setProvider.apply(_this, arguments); - - this.eth.setProvider(provider, net); - this.shh.setProvider(provider, net); - this.bzz.setProvider(provider); - - return true; - }; -}; - -Web3.version = version; -Web3.utils = utils; -Web3.modules = { - Eth: Eth, - Net: Net, - Personal: Personal, - Shh: Shh, - Bzz: Bzz -}; - -core.addProviders(Web3); - -module.exports = Web3; - - -},{"../package.json":1838,"web3-bzz":1789,"web3-core":1802,"web3-eth":1828,"web3-eth-personal":1826,"web3-net":1829,"web3-shh":1833,"web3-utils":1835}],1840:[function(require,module,exports){ +},{}],1524:[function(require,module,exports){ /* global self */ // created by @HenrikJoreteg @@ -248419,175 +165982,7 @@ module.exports = { getUserMedia: getUserMedia } -},{}],1841:[function(require,module,exports){ -var _globalThis; -try { - _globalThis = require('es5-ext/global'); -} catch (error) { -} finally { - if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; } - if (!_globalThis) { throw new Error('Could not determine global this'); } -} - -var NativeWebSocket = _globalThis.WebSocket || _globalThis.MozWebSocket; -var websocket_version = require('./version'); - - -/** - * Expose a W3C WebSocket class with just one or two arguments. - */ -function W3CWebSocket(uri, protocols) { - var native_instance; - - if (protocols) { - native_instance = new NativeWebSocket(uri, protocols); - } - else { - native_instance = new NativeWebSocket(uri); - } - - /** - * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket - * class). Since it is an Object it will be returned as it is when creating an - * instance of W3CWebSocket via 'new W3CWebSocket()'. - * - * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 - */ - return native_instance; -} -if (NativeWebSocket) { - ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { - Object.defineProperty(W3CWebSocket, prop, { - get: function() { return NativeWebSocket[prop]; } - }); - }); -} - -/** - * Module exports. - */ -module.exports = { - 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, - 'version' : websocket_version -}; - -},{"./version":1842,"es5-ext/global":329}],1842:[function(require,module,exports){ -module.exports = require('../package.json').version; - -},{"../package.json":1843}],1843:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - "websocket@github:web3-js/WebSocket-Node#polyfill/globalThis", - "/var/www/html/ethoFSV2/node_modules/web3-providers-ws" - ] - ], - "_from": "web3-js/WebSocket-Node#polyfill/globalThis", - "_id": "websocket@1.0.29", - "_inCache": true, - "_installable": true, - "_location": "/websocket", - "_phantomChildren": {}, - "_requested": { - "hosted": { - "directUrl": "https://raw.githubusercontent.com/web3-js/WebSocket-Node/polyfill%2FglobalThis/package.json", - "gitUrl": "git://github.com/web3-js/WebSocket-Node.git#polyfill/globalThis", - "httpsUrl": "git+https://github.com/web3-js/WebSocket-Node.git#polyfill/globalThis", - "shortcut": "github:web3-js/WebSocket-Node#polyfill/globalThis", - "ssh": "git@github.com:web3-js/WebSocket-Node.git#polyfill/globalThis", - "sshUrl": "git+ssh://git@github.com/web3-js/WebSocket-Node.git#polyfill/globalThis", - "type": "github" - }, - "name": "websocket", - "raw": "websocket@github:web3-js/WebSocket-Node#polyfill/globalThis", - "rawSpec": "github:web3-js/WebSocket-Node#polyfill/globalThis", - "scope": null, - "spec": "github:web3-js/WebSocket-Node#polyfill/globalThis", - "type": "hosted" - }, - "_requiredBy": [ - "/web3-providers-ws" - ], - "_resolved": "git://github.com/web3-js/WebSocket-Node.git#905deb4812572b344f5801f8c9ce8bb02799d82e", - "_shasum": "8a69be3953ebc888f0a6b37776117839f446731d", - "_shrinkwrap": null, - "_spec": "websocket@github:web3-js/WebSocket-Node#polyfill/globalThis", - "_where": "/var/www/html/ethoFSV2/node_modules/web3-providers-ws", - "author": { - "email": "theturtle32@gmail.com", - "name": "Brian McKelvey", - "url": "https://github.com/theturtle32" - }, - "browser": "lib/browser.js", - "bugs": { - "url": "https://github.com/theturtle32/WebSocket-Node/issues" - }, - "config": { - "verbose": false - }, - "contributors": [ - { - "name": "Iñaki Baz Castillo", - "email": "ibc@aliax.net", - "url": "http://dev.sipdoc.net" - } - ], - "dependencies": { - "debug": "^2.2.0", - "es5-ext": "^0.10.50", - "nan": "^2.14.0", - "typedarray-to-buffer": "^3.1.5", - "yaeti": "^0.0.6" - }, - "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", - "devDependencies": { - "buffer-equal": "^1.0.0", - "faucet": "^0.0.1", - "gulp": "^4.0.2", - "gulp-jshint": "^2.0.4", - "jshint": "^2.0.0", - "jshint-stylish": "^2.2.1", - "tape": "^4.9.1" - }, - "directories": { - "lib": "./lib" - }, - "engines": { - "node": ">=0.10.0" - }, - "gitHead": "905deb4812572b344f5801f8c9ce8bb02799d82e", - "homepage": "https://github.com/theturtle32/WebSocket-Node", - "keywords": [ - "RFC-6455", - "client", - "comet", - "networking", - "push", - "realtime", - "server", - "socket", - "websocket", - "websockets" - ], - "license": "Apache-2.0", - "main": "index", - "name": "websocket", - "optionalDependencies": {}, - "readme": "WebSocket Client & Server Implementation for Node\n=================================================\n\n[![npm version](https://badge.fury.io/js/websocket.svg)](http://badge.fury.io/js/websocket)\n\n[![NPM Downloads](https://img.shields.io/npm/dm/websocket.svg)](https://www.npmjs.com/package/websocket)\n\n[![NPM](https://nodei.co/npm/websocket.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/websocket/)\n\n[![NPM](https://nodei.co/npm-dl/websocket.png?height=3)](https://nodei.co/npm/websocket/)\n\n[ ![Codeship Status for theturtle32/WebSocket-Node](https://codeship.com/projects/70458270-8ee7-0132-7756-0a0cf4fe8e66/status?branch=master)](https://codeship.com/projects/61106)\n\nOverview\n--------\nThis is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the \"test/scripts\" folder.\n\nFor a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/theturtle32/AS3WebSocket) project.\n\n\nDocumentation\n=============\n\n[You can read the full API documentation in the docs folder.](docs/index.md)\n\n\nChangelog\n---------\n\n***Current Version: 1.0.29*** — Released 2019-07-03\n\n* Updated some dependencies and updated the .gitignore and .npmignore files\n\n[View the full changelog](CHANGELOG.md)\n\nBrowser Support\n---------------\n\nAll current browsers are fully supported.\n\n* Firefox 7-9 (Old) (Protocol Version 8)\n* Firefox 10+ (Protocol Version 13)\n* Chrome 14,15 (Old) (Protocol Version 8)\n* Chrome 16+ (Protocol Version 13)\n* Internet Explorer 10+ (Protocol Version 13)\n* Safari 6+ (Protocol Version 13)\n\n***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets***\n\n***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579***\n\nBenchmarks\n----------\nThere are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.\n\nAutobahn Tests\n--------------\nThe very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability.\n\n- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/)\n\nInstallation\n------------\n\nA few users have reported difficulties building the native extensions without first manually installing node-gyp. If you have trouble building the native extensions, make sure you've got a C++ compiler, and have done `npm install -g node-gyp` first. \n\nNative extensions are optional, however, and WebSocket-Node will work even if the extensions cannot be compiled.\n\nIn your project root:\n\n $ npm install websocket\n \nThen in your code:\n\n```javascript\nvar WebSocketServer = require('websocket').server;\nvar WebSocketClient = require('websocket').client;\nvar WebSocketFrame = require('websocket').frame;\nvar WebSocketRouter = require('websocket').router;\nvar W3CWebSocket = require('websocket').w3cwebsocket;\n```\n\nNote for Windows Users\n----------------------\nBecause there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module:\n\n- [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express)\n- [Python 2.7](http://www.python.org/download/) (NOT Python 3.x)\n\n\nCurrent Features:\n-----------------\n- Licensed under the Apache License, Version 2.0\n- Protocol version \"8\" and \"13\" (Draft-08 through the final RFC) framing and handshake\n- Can handle/aggregate received fragmented messages\n- Can fragment outgoing messages\n- Router to mount multiple applications to various path and protocol combinations\n- TLS supported for outbound connections via WebSocketClient\n- TLS supported for server connections (use https.createServer instead of http.createServer)\n - Thanks to [pors](https://github.com/pors) for confirming this!\n- Cookie setting and parsing\n- Tunable settings\n - Max Receivable Frame Size\n - Max Aggregate ReceivedMessage Size\n - Whether to fragment outgoing messages\n - Fragmentation chunk size for outgoing messages\n - Whether to automatically send ping frames for the purposes of keepalive\n - Keep-alive ping interval\n - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)\n - How long to wait after sending a close frame for acknowledgment before closing the socket.\n- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class). \n\n\nKnown Issues/Missing Features:\n------------------------------\n- No API for user-provided protocol extensions.\n\n\nUsage Examples\n==============\n\nServer Example\n--------------\n\nHere's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.\n\n```javascript\n#!/usr/bin/env node\nvar WebSocketServer = require('websocket').server;\nvar http = require('http');\n\nvar server = http.createServer(function(request, response) {\n console.log((new Date()) + ' Received request for ' + request.url);\n response.writeHead(404);\n response.end();\n});\nserver.listen(8080, function() {\n console.log((new Date()) + ' Server is listening on port 8080');\n});\n\nwsServer = new WebSocketServer({\n httpServer: server,\n // You should not use autoAcceptConnections for production\n // applications, as it defeats all standard cross-origin protection\n // facilities built into the protocol and the browser. You should\n // *always* verify the connection's origin and decide whether or not\n // to accept it.\n autoAcceptConnections: false\n});\n\nfunction originIsAllowed(origin) {\n // put logic here to detect whether the specified origin is allowed.\n return true;\n}\n\nwsServer.on('request', function(request) {\n if (!originIsAllowed(request.origin)) {\n // Make sure we only accept requests from an allowed origin\n request.reject();\n console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');\n return;\n }\n \n var connection = request.accept('echo-protocol', request.origin);\n console.log((new Date()) + ' Connection accepted.');\n connection.on('message', function(message) {\n if (message.type === 'utf8') {\n console.log('Received Message: ' + message.utf8Data);\n connection.sendUTF(message.utf8Data);\n }\n else if (message.type === 'binary') {\n console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');\n connection.sendBytes(message.binaryData);\n }\n });\n connection.on('close', function(reasonCode, description) {\n console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');\n });\n});\n```\n\nClient Example\n--------------\n\nThis is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.\n\n*This code demonstrates a client in Node.js, not in the browser*\n\n```javascript\n#!/usr/bin/env node\nvar WebSocketClient = require('websocket').client;\n\nvar client = new WebSocketClient();\n\nclient.on('connectFailed', function(error) {\n console.log('Connect Error: ' + error.toString());\n});\n\nclient.on('connect', function(connection) {\n console.log('WebSocket Client Connected');\n connection.on('error', function(error) {\n console.log(\"Connection Error: \" + error.toString());\n });\n connection.on('close', function() {\n console.log('echo-protocol Connection Closed');\n });\n connection.on('message', function(message) {\n if (message.type === 'utf8') {\n console.log(\"Received: '\" + message.utf8Data + \"'\");\n }\n });\n \n function sendNumber() {\n if (connection.connected) {\n var number = Math.round(Math.random() * 0xFFFFFF);\n connection.sendUTF(number.toString());\n setTimeout(sendNumber, 1000);\n }\n }\n sendNumber();\n});\n\nclient.connect('ws://localhost:8080/', 'echo-protocol');\n```\n\nClient Example using the *W3C WebSocket API*\n--------------------------------------------\n\nSame example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/).\n\n```javascript\nvar W3CWebSocket = require('websocket').w3cwebsocket;\n\nvar client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');\n\nclient.onerror = function() {\n console.log('Connection Error');\n};\n\nclient.onopen = function() {\n console.log('WebSocket Client Connected');\n\n function sendNumber() {\n if (client.readyState === client.OPEN) {\n var number = Math.round(Math.random() * 0xFFFFFF);\n client.send(number.toString());\n setTimeout(sendNumber, 1000);\n }\n }\n sendNumber();\n};\n\nclient.onclose = function() {\n console.log('echo-protocol Client Closed');\n};\n\nclient.onmessage = function(e) {\n if (typeof e.data === 'string') {\n console.log(\"Received: '\" + e.data + \"'\");\n }\n};\n```\n \nRequest Router Example\n----------------------\n\nFor an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder.\n\n\nResources\n---------\n\nA presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered)\n", - "readmeFilename": "README.md", - "repository": { - "type": "git", - "url": "git+https://github.com/theturtle32/WebSocket-Node.git" - }, - "scripts": { - "gulp": "gulp", - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "faucet test/unit" - }, - "version": "1.0.29" -} - -},{}],1844:[function(require,module,exports){ +},{}],1525:[function(require,module,exports){ // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. @@ -248622,1041 +166017,7 @@ function wrappy (fn, cb) { } } -},{}],1845:[function(require,module,exports){ -var request = require('xhr-request') - -module.exports = function (url, options) { - return new Promise(function (resolve, reject) { - request(url, options, function (err, data) { - if (err) reject(err); - else resolve(data); - }); - }); -}; - -},{"xhr-request":1846}],1846:[function(require,module,exports){ -var queryString = require('query-string') -var setQuery = require('url-set-query') -var assign = require('object-assign') -var ensureHeader = require('./lib/ensure-header.js') - -// this is replaced in the browser -var request = require('./lib/request.js') - -var mimeTypeJson = 'application/json' -var noop = function () {} - -module.exports = xhrRequest -function xhrRequest (url, opt, cb) { - if (!url || typeof url !== 'string') { - throw new TypeError('must specify a URL') - } - if (typeof opt === 'function') { - cb = opt - opt = {} - } - if (cb && typeof cb !== 'function') { - throw new TypeError('expected cb to be undefined or a function') - } - - cb = cb || noop - opt = opt || {} - - var defaultResponse = opt.json ? 'json' : 'text' - opt = assign({ responseType: defaultResponse }, opt) - - var headers = opt.headers || {} - var method = (opt.method || 'GET').toUpperCase() - var query = opt.query - if (query) { - if (typeof query !== 'string') { - query = queryString.stringify(query) - } - url = setQuery(url, query) - } - - // allow json response - if (opt.responseType === 'json') { - ensureHeader(headers, 'Accept', mimeTypeJson) - } - - // if body content is json - if (opt.json && method !== 'GET' && method !== 'HEAD') { - ensureHeader(headers, 'Content-Type', mimeTypeJson) - opt.body = JSON.stringify(opt.body) - } - - opt.method = method - opt.url = url - opt.headers = headers - delete opt.query - delete opt.json - - return request(opt, cb) -} - -},{"./lib/ensure-header.js":1847,"./lib/request.js":1849,"object-assign":1388,"query-string":1544,"url-set-query":1768}],1847:[function(require,module,exports){ -module.exports = ensureHeader -function ensureHeader (headers, key, value) { - var lower = key.toLowerCase() - if (!headers[key] && !headers[lower]) { - headers[key] = value - } -} - -},{}],1848:[function(require,module,exports){ -module.exports = getResponse -function getResponse (opt, resp) { - if (!resp) return null - return { - statusCode: resp.statusCode, - headers: resp.headers, - method: opt.method, - url: opt.url, - // the XHR object in browser, http response in Node - rawRequest: resp.rawRequest ? resp.rawRequest : resp - } -} - -},{}],1849:[function(require,module,exports){ -var xhr = require('xhr') -var normalize = require('./normalize-response') -var noop = function () {} - -module.exports = xhrRequest -function xhrRequest (opt, cb) { - delete opt.uri - - // for better JSON.parse error handling than xhr module - var useJson = false - if (opt.responseType === 'json') { - opt.responseType = 'text' - useJson = true - } - - var req = xhr(opt, function xhrRequestResult (err, resp, body) { - if (useJson && !err) { - try { - var text = resp.rawRequest.responseText - body = JSON.parse(text) - } catch (e) { - err = e - } - } - - resp = normalize(opt, resp) - if (err) cb(err, null, resp) - else cb(err, body, resp) - cb = noop - }) - - // Patch abort() so that it also calls the callback, but with an error - var onabort = req.onabort - req.onabort = function () { - var ret = onabort.apply(req, Array.prototype.slice.call(arguments)) - cb(new Error('XHR Aborted')) - cb = noop - return ret - } - - return req -} - -},{"./normalize-response":1848,"xhr":1850}],1850:[function(require,module,exports){ -"use strict"; -var window = require("global/window") -var isFunction = require("is-function") -var parseHeaders = require("parse-headers") -var xtend = require("xtend") - -module.exports = createXHR -// Allow use of default import syntax in TypeScript -module.exports.default = createXHR; -createXHR.XMLHttpRequest = window.XMLHttpRequest || noop -createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest - -forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { - createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { - options = initParams(uri, options, callback) - options.method = method.toUpperCase() - return _createXHR(options) - } -}) - -function forEachArray(array, iterator) { - for (var i = 0; i < array.length; i++) { - iterator(array[i]) - } -} - -function isEmpty(obj){ - for(var i in obj){ - if(obj.hasOwnProperty(i)) return false - } - return true -} - -function initParams(uri, options, callback) { - var params = uri - - if (isFunction(options)) { - callback = options - if (typeof uri === "string") { - params = {uri:uri} - } - } else { - params = xtend(options, {uri: uri}) - } - - params.callback = callback - return params -} - -function createXHR(uri, options, callback) { - options = initParams(uri, options, callback) - return _createXHR(options) -} - -function _createXHR(options) { - if(typeof options.callback === "undefined"){ - throw new Error("callback argument missing") - } - - var called = false - var callback = function cbOnce(err, response, body){ - if(!called){ - called = true - options.callback(err, response, body) - } - } - - function readystatechange() { - if (xhr.readyState === 4) { - setTimeout(loadFunc, 0) - } - } - - function getBody() { - // Chrome with requestType=blob throws errors arround when even testing access to responseText - var body = undefined - - if (xhr.response) { - body = xhr.response - } else { - body = xhr.responseText || getXml(xhr) - } - - if (isJson) { - try { - body = JSON.parse(body) - } catch (e) {} - } - - return body - } - - function errorFunc(evt) { - clearTimeout(timeoutTimer) - if(!(evt instanceof Error)){ - evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) - } - evt.statusCode = 0 - return callback(evt, failureResponse) - } - - // will load the data & process the response in a special response object - function loadFunc() { - if (aborted) return - var status - clearTimeout(timeoutTimer) - if(options.useXDR && xhr.status===undefined) { - //IE8 CORS GET successful response doesn't have a status field, but body is fine - status = 200 - } else { - status = (xhr.status === 1223 ? 204 : xhr.status) - } - var response = failureResponse - var err = null - - if (status !== 0){ - response = { - body: getBody(), - statusCode: status, - method: method, - headers: {}, - url: uri, - rawRequest: xhr - } - if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE - response.headers = parseHeaders(xhr.getAllResponseHeaders()) - } - } else { - err = new Error("Internal XMLHttpRequest Error") - } - return callback(err, response, response.body) - } - - var xhr = options.xhr || null - - if (!xhr) { - if (options.cors || options.useXDR) { - xhr = new createXHR.XDomainRequest() - }else{ - xhr = new createXHR.XMLHttpRequest() - } - } - - var key - var aborted - var uri = xhr.url = options.uri || options.url - var method = xhr.method = options.method || "GET" - var body = options.body || options.data - var headers = xhr.headers = options.headers || {} - var sync = !!options.sync - var isJson = false - var timeoutTimer - var failureResponse = { - body: undefined, - headers: {}, - statusCode: 0, - method: method, - url: uri, - rawRequest: xhr - } - - if ("json" in options && options.json !== false) { - isJson = true - headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user - if (method !== "GET" && method !== "HEAD") { - headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user - body = JSON.stringify(options.json === true ? body : options.json) - } - } - - xhr.onreadystatechange = readystatechange - xhr.onload = loadFunc - xhr.onerror = errorFunc - // IE9 must have onprogress be set to a unique function. - xhr.onprogress = function () { - // IE must die - } - xhr.onabort = function(){ - aborted = true; - } - xhr.ontimeout = errorFunc - xhr.open(method, uri, !sync, options.username, options.password) - //has to be after open - if(!sync) { - xhr.withCredentials = !!options.withCredentials - } - // Cannot set timeout with sync request - // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly - // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent - if (!sync && options.timeout > 0 ) { - timeoutTimer = setTimeout(function(){ - if (aborted) return - aborted = true//IE9 may still call readystatechange - xhr.abort("timeout") - var e = new Error("XMLHttpRequest timeout") - e.code = "ETIMEDOUT" - errorFunc(e) - }, options.timeout ) - } - - if (xhr.setRequestHeader) { - for(key in headers){ - if(headers.hasOwnProperty(key)){ - xhr.setRequestHeader(key, headers[key]) - } - } - } else if (options.headers && !isEmpty(options.headers)) { - throw new Error("Headers cannot be set on an XDomainRequest object") - } - - if ("responseType" in options) { - xhr.responseType = options.responseType - } - - if ("beforeSend" in options && - typeof options.beforeSend === "function" - ) { - options.beforeSend(xhr) - } - - // Microsoft Edge browser sends "undefined" when send is called with undefined value. - // XMLHttpRequest spec says to pass null as body to indicate no body - // See https://github.com/naugtur/xhr/issues/100. - xhr.send(body || null) - - return xhr - - -} - -function getXml(xhr) { - // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException" - // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML. - try { - if (xhr.responseType === "document") { - return xhr.responseXML - } - var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" - if (xhr.responseType === "" && !firefoxBugTakenEffect) { - return xhr.responseXML - } - } catch (e) {} - - return null -} - -function noop() {} - -},{"global/window":389,"is-function":772,"parse-headers":1422,"xtend":1860}],1851:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var SecurityError = /** @class */ (function (_super) { - __extends(SecurityError, _super); - function SecurityError() { - return _super !== null && _super.apply(this, arguments) || this; - } - return SecurityError; -}(Error)); -exports.SecurityError = SecurityError; -var InvalidStateError = /** @class */ (function (_super) { - __extends(InvalidStateError, _super); - function InvalidStateError() { - return _super !== null && _super.apply(this, arguments) || this; - } - return InvalidStateError; -}(Error)); -exports.InvalidStateError = InvalidStateError; -var NetworkError = /** @class */ (function (_super) { - __extends(NetworkError, _super); - function NetworkError() { - return _super !== null && _super.apply(this, arguments) || this; - } - return NetworkError; -}(Error)); -exports.NetworkError = NetworkError; -var SyntaxError = /** @class */ (function (_super) { - __extends(SyntaxError, _super); - function SyntaxError() { - return _super !== null && _super.apply(this, arguments) || this; - } - return SyntaxError; -}(Error)); -exports.SyntaxError = SyntaxError; - -},{}],1852:[function(require,module,exports){ -"use strict"; -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -__export(require("./xml-http-request")); -var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); -exports.XMLHttpRequestEventTarget = xml_http_request_event_target_1.XMLHttpRequestEventTarget; - -},{"./xml-http-request":1856,"./xml-http-request-event-target":1854}],1853:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var ProgressEvent = /** @class */ (function () { - function ProgressEvent(type) { - this.type = type; - this.bubbles = false; - this.cancelable = false; - this.loaded = 0; - this.lengthComputable = false; - this.total = 0; - } - return ProgressEvent; -}()); -exports.ProgressEvent = ProgressEvent; - -},{}],1854:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var XMLHttpRequestEventTarget = /** @class */ (function () { - function XMLHttpRequestEventTarget() { - this.listeners = {}; - } - XMLHttpRequestEventTarget.prototype.addEventListener = function (eventType, listener) { - eventType = eventType.toLowerCase(); - this.listeners[eventType] = this.listeners[eventType] || []; - this.listeners[eventType].push(listener.handleEvent || listener); - }; - XMLHttpRequestEventTarget.prototype.removeEventListener = function (eventType, listener) { - eventType = eventType.toLowerCase(); - if (!this.listeners[eventType]) { - return; - } - var index = this.listeners[eventType].indexOf(listener.handleEvent || listener); - if (index < 0) { - return; - } - this.listeners[eventType].splice(index, 1); - }; - XMLHttpRequestEventTarget.prototype.dispatchEvent = function (event) { - var eventType = event.type.toLowerCase(); - event.target = this; // TODO: set event.currentTarget? - if (this.listeners[eventType]) { - for (var _i = 0, _a = this.listeners[eventType]; _i < _a.length; _i++) { - var listener_1 = _a[_i]; - listener_1.call(this, event); - } - } - var listener = this["on" + eventType]; - if (listener) { - listener.call(this, event); - } - return true; - }; - return XMLHttpRequestEventTarget; -}()); -exports.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget; - -},{}],1855:[function(require,module,exports){ -(function (Buffer){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); -var XMLHttpRequestUpload = /** @class */ (function (_super) { - __extends(XMLHttpRequestUpload, _super); - function XMLHttpRequestUpload() { - var _this = _super.call(this) || this; - _this._contentType = null; - _this._body = null; - _this._reset(); - return _this; - } - XMLHttpRequestUpload.prototype._reset = function () { - this._contentType = null; - this._body = null; - }; - XMLHttpRequestUpload.prototype._setData = function (data) { - if (data == null) { - return; - } - if (typeof data === 'string') { - if (data.length !== 0) { - this._contentType = 'text/plain;charset=UTF-8'; - } - this._body = new Buffer(data, 'utf-8'); - } - else if (Buffer.isBuffer(data)) { - this._body = data; - } - else if (data instanceof ArrayBuffer) { - var body = new Buffer(data.byteLength); - var view = new Uint8Array(data); - for (var i = 0; i < data.byteLength; i++) { - body[i] = view[i]; - } - this._body = body; - } - else if (data.buffer && data.buffer instanceof ArrayBuffer) { - var body = new Buffer(data.byteLength); - var offset = data.byteOffset; - var view = new Uint8Array(data.buffer); - for (var i = 0; i < data.byteLength; i++) { - body[i] = view[i + offset]; - } - this._body = body; - } - else { - throw new Error("Unsupported send() data " + data); - } - }; - XMLHttpRequestUpload.prototype._finalizeHeaders = function (headers, loweredHeaders) { - if (this._contentType && !loweredHeaders['content-type']) { - headers['Content-Type'] = this._contentType; - } - if (this._body) { - headers['Content-Length'] = this._body.length.toString(); - } - }; - XMLHttpRequestUpload.prototype._startUpload = function (request) { - if (this._body) { - request.write(this._body); - } - request.end(); - }; - return XMLHttpRequestUpload; -}(xml_http_request_event_target_1.XMLHttpRequestEventTarget)); -exports.XMLHttpRequestUpload = XMLHttpRequestUpload; - -}).call(this,require("buffer").Buffer) -},{"./xml-http-request-event-target":1854,"buffer":217}],1856:[function(require,module,exports){ -(function (process,Buffer){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -var http = require("http"); -var https = require("https"); -var os = require("os"); -var url = require("url"); -var progress_event_1 = require("./progress-event"); -var errors_1 = require("./errors"); -var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); -var xml_http_request_upload_1 = require("./xml-http-request-upload"); -var Cookie = require("cookiejar"); -var XMLHttpRequest = /** @class */ (function (_super) { - __extends(XMLHttpRequest, _super); - function XMLHttpRequest(options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this) || this; - _this.UNSENT = XMLHttpRequest.UNSENT; - _this.OPENED = XMLHttpRequest.OPENED; - _this.HEADERS_RECEIVED = XMLHttpRequest.HEADERS_RECEIVED; - _this.LOADING = XMLHttpRequest.LOADING; - _this.DONE = XMLHttpRequest.DONE; - _this.onreadystatechange = null; - _this.readyState = XMLHttpRequest.UNSENT; - _this.response = null; - _this.responseText = ''; - _this.responseType = ''; - _this.status = 0; // TODO: UNSENT? - _this.statusText = ''; - _this.timeout = 0; - _this.upload = new xml_http_request_upload_1.XMLHttpRequestUpload(); - _this.responseUrl = ''; - _this.withCredentials = false; - _this._method = null; - _this._url = null; - _this._sync = false; - _this._headers = {}; - _this._loweredHeaders = {}; - _this._mimeOverride = null; // TODO: is type right? - _this._request = null; - _this._response = null; - _this._responseParts = null; - _this._responseHeaders = null; - _this._aborting = null; // TODO: type? - _this._error = null; // TODO: type? - _this._loadedBytes = 0; - _this._totalBytes = 0; - _this._lengthComputable = false; - _this._restrictedMethods = { CONNECT: true, TRACE: true, TRACK: true }; - _this._restrictedHeaders = { - 'accept-charset': true, - 'accept-encoding': true, - 'access-control-request-headers': true, - 'access-control-request-method': true, - connection: true, - 'content-length': true, - cookie: true, - cookie2: true, - date: true, - dnt: true, - expect: true, - host: true, - 'keep-alive': true, - origin: true, - referer: true, - te: true, - trailer: true, - 'transfer-encoding': true, - upgrade: true, - 'user-agent': true, - via: true - }; - _this._privateHeaders = { 'set-cookie': true, 'set-cookie2': true }; - _this._userAgent = "Mozilla/5.0 (" + os.type() + " " + os.arch() + ") node.js/" + process.versions.node + " v8/" + process.versions.v8; - _this._anonymous = options.anon || false; - return _this; - } - XMLHttpRequest.prototype.open = function (method, url, async, user, password) { - if (async === void 0) { async = true; } - method = method.toUpperCase(); - if (this._restrictedMethods[method]) { - throw new XMLHttpRequest.SecurityError("HTTP method " + method + " is not allowed in XHR"); - } - ; - var xhrUrl = this._parseUrl(url, user, password); - if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED || this.readyState === XMLHttpRequest.LOADING) { - // TODO(pwnall): terminate abort(), terminate send() - } - this._method = method; - this._url = xhrUrl; - this._sync = !async; - this._headers = {}; - this._loweredHeaders = {}; - this._mimeOverride = null; - this._setReadyState(XMLHttpRequest.OPENED); - this._request = null; - this._response = null; - this.status = 0; - this.statusText = ''; - this._responseParts = []; - this._responseHeaders = null; - this._loadedBytes = 0; - this._totalBytes = 0; - this._lengthComputable = false; - }; - XMLHttpRequest.prototype.setRequestHeader = function (name, value) { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); - } - var loweredName = name.toLowerCase(); - if (this._restrictedHeaders[loweredName] || /^sec-/.test(loweredName) || /^proxy-/.test(loweredName)) { - console.warn("Refused to set unsafe header \"" + name + "\""); - return; - } - value = value.toString(); - if (this._loweredHeaders[loweredName] != null) { - name = this._loweredHeaders[loweredName]; - this._headers[name] = this._headers[name] + ", " + value; - } - else { - this._loweredHeaders[loweredName] = name; - this._headers[name] = value; - } - }; - XMLHttpRequest.prototype.send = function (data) { - if (this.readyState !== XMLHttpRequest.OPENED) { - throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); - } - if (this._request) { - throw new XMLHttpRequest.InvalidStateError('send() already called'); - } - switch (this._url.protocol) { - case 'file:': - return this._sendFile(data); - case 'http:': - case 'https:': - return this._sendHttp(data); - default: - throw new XMLHttpRequest.NetworkError("Unsupported protocol " + this._url.protocol); - } - }; - XMLHttpRequest.prototype.abort = function () { - if (this._request == null) { - return; - } - this._request.abort(); - this._setError(); - this._dispatchProgress('abort'); - this._dispatchProgress('loadend'); - }; - XMLHttpRequest.prototype.getResponseHeader = function (name) { - if (this._responseHeaders == null || name == null) { - return null; - } - var loweredName = name.toLowerCase(); - return this._responseHeaders.hasOwnProperty(loweredName) - ? this._responseHeaders[name.toLowerCase()] - : null; - }; - XMLHttpRequest.prototype.getAllResponseHeaders = function () { - var _this = this; - if (this._responseHeaders == null) { - return ''; - } - return Object.keys(this._responseHeaders).map(function (key) { return key + ": " + _this._responseHeaders[key]; }).join('\r\n'); - }; - XMLHttpRequest.prototype.overrideMimeType = function (mimeType) { - if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) { - throw new XMLHttpRequest.InvalidStateError('overrideMimeType() not allowed in LOADING or DONE'); - } - this._mimeOverride = mimeType.toLowerCase(); - }; - XMLHttpRequest.prototype.nodejsSet = function (options) { - this.nodejsHttpAgent = options.httpAgent || this.nodejsHttpAgent; - this.nodejsHttpsAgent = options.httpsAgent || this.nodejsHttpsAgent; - if (options.hasOwnProperty('baseUrl')) { - if (options.baseUrl != null) { - var parsedUrl = url.parse(options.baseUrl, false, true); - if (!parsedUrl.protocol) { - throw new XMLHttpRequest.SyntaxError("baseUrl must be an absolute URL"); - } - } - this.nodejsBaseUrl = options.baseUrl; - } - }; - XMLHttpRequest.nodejsSet = function (options) { - XMLHttpRequest.prototype.nodejsSet(options); - }; - XMLHttpRequest.prototype._setReadyState = function (readyState) { - this.readyState = readyState; - this.dispatchEvent(new progress_event_1.ProgressEvent('readystatechange')); - }; - XMLHttpRequest.prototype._sendFile = function (data) { - // TODO - throw new Error('Protocol file: not implemented'); - }; - XMLHttpRequest.prototype._sendHttp = function (data) { - if (this._sync) { - throw new Error('Synchronous XHR processing not implemented'); - } - if (data && (this._method === 'GET' || this._method === 'HEAD')) { - console.warn("Discarding entity body for " + this._method + " requests"); - data = null; - } - else { - data = data || ''; - } - this.upload._setData(data); - this._finalizeHeaders(); - this._sendHxxpRequest(); - }; - XMLHttpRequest.prototype._sendHxxpRequest = function () { - var _this = this; - if (this.withCredentials) { - var cookie = XMLHttpRequest.cookieJar - .getCookies(Cookie.CookieAccessInfo(this._url.hostname, this._url.pathname, this._url.protocol === 'https:')).toValueString(); - this._headers.cookie = this._headers.cookie2 = cookie; - } - var _a = this._url.protocol === 'http:' ? [http, this.nodejsHttpAgent] : [https, this.nodejsHttpsAgent], hxxp = _a[0], agent = _a[1]; - var requestMethod = hxxp.request.bind(hxxp); - var request = requestMethod({ - hostname: this._url.hostname, - port: +this._url.port, - path: this._url.path, - auth: this._url.auth, - method: this._method, - headers: this._headers, - agent: agent - }); - this._request = request; - if (this.timeout) { - request.setTimeout(this.timeout, function () { return _this._onHttpTimeout(request); }); - } - request.on('response', function (response) { return _this._onHttpResponse(request, response); }); - request.on('error', function (error) { return _this._onHttpRequestError(request, error); }); - this.upload._startUpload(request); - if (this._request === request) { - this._dispatchProgress('loadstart'); - } - }; - XMLHttpRequest.prototype._finalizeHeaders = function () { - this._headers = __assign({}, this._headers, { Connection: 'keep-alive', Host: this._url.host, 'User-Agent': this._userAgent }, this._anonymous ? { Referer: 'about:blank' } : {}); - this.upload._finalizeHeaders(this._headers, this._loweredHeaders); - }; - XMLHttpRequest.prototype._onHttpResponse = function (request, response) { - var _this = this; - if (this._request !== request) { - return; - } - if (this.withCredentials && (response.headers['set-cookie'] || response.headers['set-cookie2'])) { - XMLHttpRequest.cookieJar - .setCookies(response.headers['set-cookie'] || response.headers['set-cookie2']); - } - if ([301, 302, 303, 307, 308].indexOf(response.statusCode) >= 0) { - this._url = this._parseUrl(response.headers.location); - this._method = 'GET'; - if (this._loweredHeaders['content-type']) { - delete this._headers[this._loweredHeaders['content-type']]; - delete this._loweredHeaders['content-type']; - } - if (this._headers['Content-Type'] != null) { - delete this._headers['Content-Type']; - } - delete this._headers['Content-Length']; - this.upload._reset(); - this._finalizeHeaders(); - this._sendHxxpRequest(); - return; - } - this._response = response; - this._response.on('data', function (data) { return _this._onHttpResponseData(response, data); }); - this._response.on('end', function () { return _this._onHttpResponseEnd(response); }); - this._response.on('close', function () { return _this._onHttpResponseClose(response); }); - this.responseUrl = this._url.href.split('#')[0]; - this.status = response.statusCode; - this.statusText = http.STATUS_CODES[this.status]; - this._parseResponseHeaders(response); - var lengthString = this._responseHeaders['content-length'] || ''; - this._totalBytes = +lengthString; - this._lengthComputable = !!lengthString; - this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED); - }; - XMLHttpRequest.prototype._onHttpResponseData = function (response, data) { - if (this._response !== response) { - return; - } - this._responseParts.push(new Buffer(data)); - this._loadedBytes += data.length; - if (this.readyState !== XMLHttpRequest.LOADING) { - this._setReadyState(XMLHttpRequest.LOADING); - } - this._dispatchProgress('progress'); - }; - XMLHttpRequest.prototype._onHttpResponseEnd = function (response) { - if (this._response !== response) { - return; - } - this._parseResponse(); - this._request = null; - this._response = null; - this._setReadyState(XMLHttpRequest.DONE); - this._dispatchProgress('load'); - this._dispatchProgress('loadend'); - }; - XMLHttpRequest.prototype._onHttpResponseClose = function (response) { - if (this._response !== response) { - return; - } - var request = this._request; - this._setError(); - request.abort(); - this._setReadyState(XMLHttpRequest.DONE); - this._dispatchProgress('error'); - this._dispatchProgress('loadend'); - }; - XMLHttpRequest.prototype._onHttpTimeout = function (request) { - if (this._request !== request) { - return; - } - this._setError(); - request.abort(); - this._setReadyState(XMLHttpRequest.DONE); - this._dispatchProgress('timeout'); - this._dispatchProgress('loadend'); - }; - XMLHttpRequest.prototype._onHttpRequestError = function (request, error) { - if (this._request !== request) { - return; - } - this._setError(); - request.abort(); - this._setReadyState(XMLHttpRequest.DONE); - this._dispatchProgress('error'); - this._dispatchProgress('loadend'); - }; - XMLHttpRequest.prototype._dispatchProgress = function (eventType) { - var event = new XMLHttpRequest.ProgressEvent(eventType); - event.lengthComputable = this._lengthComputable; - event.loaded = this._loadedBytes; - event.total = this._totalBytes; - this.dispatchEvent(event); - }; - XMLHttpRequest.prototype._setError = function () { - this._request = null; - this._response = null; - this._responseHeaders = null; - this._responseParts = null; - }; - XMLHttpRequest.prototype._parseUrl = function (urlString, user, password) { - var absoluteUrl = this.nodejsBaseUrl == null ? urlString : url.resolve(this.nodejsBaseUrl, urlString); - var xhrUrl = url.parse(absoluteUrl, false, true); - xhrUrl.hash = null; - var _a = (xhrUrl.auth || '').split(':'), xhrUser = _a[0], xhrPassword = _a[1]; - if (xhrUser || xhrPassword || user || password) { - xhrUrl.auth = (user || xhrUser || '') + ":" + (password || xhrPassword || ''); - } - return xhrUrl; - }; - XMLHttpRequest.prototype._parseResponseHeaders = function (response) { - this._responseHeaders = {}; - for (var name_1 in response.headers) { - var loweredName = name_1.toLowerCase(); - if (this._privateHeaders[loweredName]) { - continue; - } - this._responseHeaders[loweredName] = response.headers[name_1]; - } - if (this._mimeOverride != null) { - this._responseHeaders['content-type'] = this._mimeOverride; - } - }; - XMLHttpRequest.prototype._parseResponse = function () { - var buffer = Buffer.concat(this._responseParts); - this._responseParts = null; - switch (this.responseType) { - case 'json': - this.responseText = null; - try { - this.response = JSON.parse(buffer.toString('utf-8')); - } - catch (_a) { - this.response = null; - } - return; - case 'buffer': - this.responseText = null; - this.response = buffer; - return; - case 'arraybuffer': - this.responseText = null; - var arrayBuffer = new ArrayBuffer(buffer.length); - var view = new Uint8Array(arrayBuffer); - for (var i = 0; i < buffer.length; i++) { - view[i] = buffer[i]; - } - this.response = arrayBuffer; - return; - case 'text': - default: - try { - this.responseText = buffer.toString(this._parseResponseEncoding()); - } - catch (_b) { - this.responseText = buffer.toString('binary'); - } - this.response = this.responseText; - } - }; - XMLHttpRequest.prototype._parseResponseEncoding = function () { - return /;\s*charset=(.*)$/.exec(this._responseHeaders['content-type'] || '')[1] || 'utf-8'; - }; - XMLHttpRequest.ProgressEvent = progress_event_1.ProgressEvent; - XMLHttpRequest.InvalidStateError = errors_1.InvalidStateError; - XMLHttpRequest.NetworkError = errors_1.NetworkError; - XMLHttpRequest.SecurityError = errors_1.SecurityError; - XMLHttpRequest.SyntaxError = errors_1.SyntaxError; - XMLHttpRequest.XMLHttpRequestUpload = xml_http_request_upload_1.XMLHttpRequestUpload; - XMLHttpRequest.UNSENT = 0; - XMLHttpRequest.OPENED = 1; - XMLHttpRequest.HEADERS_RECEIVED = 2; - XMLHttpRequest.LOADING = 3; - XMLHttpRequest.DONE = 4; - XMLHttpRequest.cookieJar = Cookie.CookieJar(); - return XMLHttpRequest; -}(xml_http_request_event_target_1.XMLHttpRequestEventTarget)); -exports.XMLHttpRequest = XMLHttpRequest; -XMLHttpRequest.prototype.nodejsHttpAgent = http.globalAgent; -XMLHttpRequest.prototype.nodejsHttpsAgent = https.globalAgent; -XMLHttpRequest.prototype.nodejsBaseUrl = null; - -}).call(this,require('_process'),require("buffer").Buffer) -},{"./errors":1851,"./progress-event":1853,"./xml-http-request-event-target":1854,"./xml-http-request-upload":1855,"_process":1438,"buffer":217,"cookiejar":229,"http":1716,"https":446,"os":1395,"url":1769}],1857:[function(require,module,exports){ +},{}],1526:[function(require,module,exports){ (function (Buffer){ module.exports = dist @@ -249689,7 +166050,7 @@ dist.eq = function eq (a, b) { } }).call(this,require("buffer").Buffer) -},{"buffer":217}],1858:[function(require,module,exports){ +},{"buffer":181}],1527:[function(require,module,exports){ var xsalsa20 = require('./xsalsa20')() var SIGMA = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]) @@ -250137,7 +166498,7 @@ function core_hsalsa20(o,p,k,c) { o[31] = x9 >>> 24 & 0xff } -},{"./xsalsa20":1859}],1859:[function(require,module,exports){ +},{"./xsalsa20":1528}],1528:[function(require,module,exports){ module.exports = loadWebAssembly @@ -250200,47 +166561,7 @@ function charCodeAt (c) { return c.charCodeAt(0) } -},{}],1860:[function(require,module,exports){ -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - -},{}],1861:[function(require,module,exports){ -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - -},{}],1862:[function(require,module,exports){ +},{}],1529:[function(require,module,exports){ 'use strict'; var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') diff --git a/assets/dashboard/js/misc.js b/assets/dashboard/js/misc.js deleted file mode 100644 index e7766d4..0000000 --- a/assets/dashboard/js/misc.js +++ /dev/null @@ -1,657 +0,0 @@ -/*SET CONTRACTS UP HERE*/ -var GlobalChannelString = "ethoFSPinningChannel_alpha11"; -var GlobalControllerContractAddress = "0xc38B47169950D8A28bC77a6Fa7467464f25ADAFc"; -var GlobalControllerABI = JSON.parse('[ { "constant": true, "inputs": [], "name": "last_completed_migration", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [ { "name": "completed", "type": "uint256" } ], "name": "setCompleted", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "new_address", "type": "address" } ], "name": "upgrade", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinToAdd", "type": "string" }, { "name": "pinSize", "type": "uint32" } ], "name": "PinAdd", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pin", "type": "string" } ], "name": "PinRemove", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [], "name": "deleteContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "hostingCost", "type": "uint256" } ], "name": "SetHostingCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinStorageAddress", "type": "address" } ], "name": "SetPinStorageAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSDashboardAddress", "type": "address" } ], "name": "SetEthoFSDashboardAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSHostingContractsAddress", "type": "address" } ], "name": "SetEthoFSHostingContractsAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountName", "type": "string" } ], "name": "AddNewUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "RemoveUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "pinSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddNewContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "MainContentHash", "type": "string" } ], "name": "RemoveHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubHostingContracts", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool", "value": false } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "newOperator", "type": "address" } ], "name": "changeOperator", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "newContractAddress", "type": "address" }, { "name": "UserAddress", "type": "address" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" } ], "name": "AddHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" } ], "name": "RemoveHostingContract1", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubContractList", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "uint256" } ], "name": "SetHostingContractCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendHostingContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddHostingContract", "outputs": [ { "name": "value", "type": "address" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "CustomerAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" }, { "name": "AccountCollectionAddress", "type": "address" } ], "name": "RemoveHostingContract2", "outputs": [ { "name": "value", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountCollectionAddress", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]'); -/*END OF CONTRACT SETUP*/ -const $miningMessage = document.querySelector('.mining-message') - -/*START OF MISC GLOBAL VARIABLES*/ -var privateKeyLogin = false; -var GlobalPrivateKey; -var minimumContractCost = 10000000000000000; - -var GlobalUploadName = ""; -var GlobalUserAddress = ""; -var GlobalHostingCost = 1.0; -var GlobalHostingCostWei = GlobalHostingCost * 1000000000000000000; -var GlobalUploadSize = 0; -var GlobalHashArray = new Array(); -var GlobalSizeArray = new Array(); -var GlobalPathArray = new Array(); -var GlobalMainHashArray = new Array(); -var GlobalMainPathArray = new Array(); -var GlobalMainContentHash = ""; -var GlobalUploadHash = ""; -var GlobalUploadPath = ""; -var GlobalContractDuration = ""; -var GlobalHostingContractArray = new Array(); -var GlobalTotalContractCount = 0; -var GlobalHostingContractDetailArray = new Array(); -var GlobalExtensionDuration; -/*END OF MISC GLOBAL VARIABLES*/ - - -fetch('https://api.coinmarketcap.com/v2/ticker/3452/').then(response => { - return response.json(); -}).then(data => { - var ethoPriceUSD = data.data.quotes.USD.price; - document.getElementById("ethoprice").textContent = round(ethoPriceUSD, 4); -}).catch(err => {}); - -if (typeof web3 == 'undefined') { - var web3 = new Web3() - web3.setProvider(new Web3.providers.HttpProvider('https://rpc.ether1.org')) - $('#ethofsLoginModal').modal('show'); -} else { - ethofsLogin(""); -} - - -function ethofsLogin(privateKey) { - $('#ethofsLoginModal').modal('hide'); - $('#ethofsRegistrationModal').modal('hide'); - //CREATE ETHER-1 CHAIN CONNECTION AND LOOK FOR EXISTING USER ACCOUNT - if (privateKey != "") { - GlobalPrivateKey = privateKey; - privateKeyLogin = true; - web3.eth.net.isListening() - .then(function() { - console.log('ethoFS is connected') - let account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey); - console.log(account); - web3.eth.accounts.wallet.add(account) - web3.eth.defaultAccount = account.address; - startEthofs() - }) - } else { - privateKeyLogin = false; - window.web3 = new Web3(window.web3.currentProvider); - web3.eth.getAccounts(function(err, accounts) { - if (err != null) { - console.error("An error occurred: " + err); - outputNoAddressContractTable(); - } else if (accounts.length == 0) { - $('#ethofsLoginModal').modal('show'); - console.log("User is not logged in"); - document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension"; - document.getElementById("accountaddress").textContent = "Address Not Found"; - outputNoAddressContractTable(); - } else { - console.log("User is logged in"); - web3.eth.defaultAccount = accounts[0]; - startEthofs(); - } - }); - } -} - -function startEthofs() { - console.log("Starting ethoFS"); - GlobalUserAddress = web3.eth.defaultAccount; - var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - ethoFSAccounts.methods.CheckAccountExistence(GlobalUserAddress).call(function(error, result) { - if (!error) { - if (result) { - document.getElementById("accountaddress").textContent = web3.eth.defaultAccount; - ethoFSAccounts.methods.GetUserAccountName(GlobalUserAddress).call(function(error, result) { - if (!error) { - if (result) { - getBlockHeight(web3); - getBalance(web3); - document.getElementById("welcome-name").textContent = "Welcome Back " + result; - updateContractTable(); - window.startApplication(); - } - } else { - console.log("Error getting user account name"); - } - }); - } else { - document.getElementById("welcome-name").textContent = "User Not Found"; - document.getElementById("accountaddress").textContent = "Address Not Found"; - console.log("User Not Found"); - $('#ethofsRegistrationModal').modal('show'); - } - } else { - document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension"; - document.getElementById("accountaddress").textContent = "Address Not Found"; - console.log("Blockchain Access Error"); - } - }); -} - -/*************************************************************************************************************/ -function AddNewUser(userName) { - console.log("Initiating New User Addition... " + userName); - var controller = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - - if (privateKeyLogin == true) { - const tx = { - to: GlobalControllerContractAddress, - from: GlobalUserAddress, - gas: 4000000, - data: controller.methods.AddNewUserPublic(userName).encodeABI() - }; - var privateKey = '0x' + GlobalPrivateKey; - web3.eth.accounts.signTransaction(tx, privateKey) - .then(function(signedTransactionData) { - web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { - if (!error) { - if (result) { - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - ethofsLogin(GlobalPrivateKey); - }); - } else { - console.log("There was a problem adding new contract"); - } - } else { - console.error(error); - } - }); - }); - } else { - controller.methods.AddNewUserPublic(userName).send(function(error, result) { - if (!error) { - if (result) { - document.getElementById("wait").innerHTML = 'Waiting For Add User Confirmation.'; - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - ethofsLogin(""); - }); - } else { - console.log("There was a problem adding new user"); - $('#ethofsLoginModal').modal('show'); - } - } else { - console.error(error); - $('#ethofsLoginModal').modal('show'); - } - }); - } -} -/*************************************************************************************************************/ -function getBlockHeight(web3) { - console.log("Starting Block Height Detection.."); - web3.eth.getBlockNumber(function(err, data) { - document.getElementById("blocknumber").textContent = data; - console.log("ETHO Block Number: " + data); - }); -} -/*************************************************************************************************************/ -function getBalance(web3) { - console.log("Starting Balance Detection.."); - web3.eth.getBalance(web3.eth.defaultAccount, function(err, data) { - var balance = "ETHO Balance: " + Number(web3.utils.fromWei(data, "ether")).toFixed(2); - document.getElementById("ethobalance").textContent = balance; - console.log("ETHO Balance: " + data); - }); -} -/*************************************************************************************************************/ -//CALCULATE AMOUNT TO BE SENT -function calculateCost(contractSize, contractDuration, hostingCost) { - var cost = ((((contractSize / 1048576) * hostingCost) * (contractDuration / 46522))); - if (cost < minimumContractCost) { - cost = minimumContractCost; - } - return cost; -} -/*************************************************************************************************************/ -//CHECK FOR TX - BLOCK TO BE MINED -function waitForReceipt(hash, cb) { - web3.eth.getTransactionReceipt(hash, function(err, receipt) { - document.getElementById("mining-status-message").textContent = "In Progress"; - $miningMessage.innerText = "Waiting For Transaction Confirmation"; - web3.eth.getBlock('latest', function(e, res) { - if (!e) { - document.getElementById("block-height").textContent = res.number; - } - }); - if (err) { - error(err); - $miningMessage.innerText = "Error Conneting To Ether-1 Network"; - } - if (receipt !== null) { - $miningMessage.innerText = "Transaction Confirmed"; - document.getElementById("mining-status-message").textContent = "Complete"; - if (cb) { - cb(receipt); - } - } else { - window.setTimeout(function() { - waitForReceipt(hash, cb); - }, 10000); - } - }); -} -/*************************************************************************************************************/ -//CREATE ETHER-1 CHAIN CONNECTION AND REMOVE CONTRACT -function RemoveContract(hostingAddress, contentHash) { - var pinRemoving = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - if (privateKeyLogin == true) { - const tx = { - to: GlobalControllerContractAddress, - from: GlobalUserAddress, - gas: 4000000, - data: pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).encodeABI() - }; - var privateKey = '0x' + GlobalPrivateKey; - console.log("Private Key: " + privateKey); - web3.eth.accounts.signTransaction(tx, privateKey) - .then(function(signedTransactionData) { - console.log("Signed TX Data: " + signedTransactionData.rawTransaction); - web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { - if (!error) { - if (result) { - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - updateContractTable(); - }); - } else { - console.log("There was a problem adding new contract"); - } - } else { - console.error(error); - } - }); - }); - } else { - const tx = { - to: GlobalControllerContractAddress, - from: GlobalUserAddress, - }; - pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).send(tx, function(error, result) { - if (!error) { - if (result) { - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - updateContractTable(); - }); - } else { - console.log("There was a problem removing contract"); - } - } else { - console.error(error); - } - }); - } -} - -function updateContractTable() { - /*************************************************************************************************************/ - //CREATE ETHER-1 CHAIN CONNECTION AND GET USER ACCOUNT & CONTRACTS - var ethoFSHostingContracts = new Array(); - var hostingContracts = ""; - var TotalContractCount = 0; - var blockHeight = 0; - web3.eth.getBlockNumber(function(error, result) { - if (!error) { - blockHeight = result; - } else - console.error(error); - }); - var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - ethoFSAccounts.methods.GetUserAccountTotalContractCount(web3.eth.defaultAccount).call(function(error, result) { - TotalContractCount = result; - GlobalTotalContractCount = result; - const getContractData = async (ethoFSAccounts, account, TotalContractCount) => { - if (TotalContractCount == 0) { - outputNoAddressContractTableWithButton(); - } - for (i = 0; i < TotalContractCount; i++) { - const promisify = (inner) => - new Promise((resolve, reject) => - inner((err, res) => { - if (err) { - reject(err); - } else { - resolve(res); - } - }) - ); - counter = i; - GlobalHostingContractArray[counter] = new Array(); - ethoFSHostingContractAddress = promisify(cb => ethoFSAccounts.methods.GetHostingContractAddress(account, counter).call(cb)); - await Promise.all([getAdditionalContractData(await ethoFSHostingContractAddress, counter, ethoFSAccounts)]); - - async function getAdditionalContractData(ethoFSHostingContractAddress, counter, ethoFSAccounts) { - const promisify = (inner) => - new Promise((resolve, reject) => - inner((err, res) => { - if (err) { - reject(err); - } else { - resolve(res); - } - }) - ); - ethoFSHostingContractCost = counter; - ethoFSHostingContractName = promisify(cb => ethoFSAccounts.methods.GetHostingContractName(ethoFSHostingContractAddress).call(cb)); - ethoFSHostingContractMainHash = promisify(cb => ethoFSAccounts.methods.GetMainContentHash(ethoFSHostingContractAddress).call(cb)); - ethoFSHostingContractHashString = promisify(cb => ethoFSAccounts.methods.GetContentHashString(ethoFSHostingContractAddress).call(cb)); - ethoFSHostingContractPathString = promisify(cb => ethoFSAccounts.methods.GetContentPathString(ethoFSHostingContractAddress).call(cb)); - - ethoFSHostingContractStorage = promisify(cb => ethoFSAccounts.methods.GetHostingContractStorageUsed(ethoFSHostingContractAddress).call(cb)); - ethoFSHostingContractStartBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractDeployedBlockHeight(ethoFSHostingContractAddress).call(cb)); - ethoFSHostingContractEndBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractExpirationBlockHeight(ethoFSHostingContractAddress).call(cb)); - - GlobalHostingContractArray[counter]['address'] = await ethoFSHostingContractAddress; - GlobalHostingContractArray[counter]['name'] = await ethoFSHostingContractName; - GlobalHostingContractArray[counter]['mainhash'] = await ethoFSHostingContractMainHash; - GlobalHostingContractArray[counter]['hashstring'] = await ethoFSHostingContractHashString; - GlobalHostingContractArray[counter]['pathstring'] = await ethoFSHostingContractPathString; - GlobalHostingContractArray[counter]['storage'] = await ethoFSHostingContractStorage; - GlobalHostingContractArray[counter]['startblock'] = await ethoFSHostingContractStartBlock; - GlobalHostingContractArray[counter]['endblock'] = await ethoFSHostingContractEndBlock; - - GlobalHostingContractArray[counter]['hash'] = new Array(); - GlobalHostingContractArray[counter]['path'] = new Array(); - - ContractHashArray = new Array(); - ContractPathArray = new Array(); - var splitHashArray = await Promise.all([splitString(await ethoFSHostingContractHashString, ":")]); - var splitPathArray = await Promise.all([splitString(await ethoFSHostingContractPathString, ":")]); - - function splitString(stringToSplit, splitDelimeter) { - return stringToSplit.split(splitDelimeter); - } - await Promise.all([loopSplitStrings(await splitHashArray[0], await splitPathArray[0], counter)]); - - function loopSplitStrings(splitHashArray, splitPathArray, counter) { - for (j = 1; j < splitHashArray.length; j++) { - GlobalHostingContractArray[counter]['hash'][j] = splitHashArray[j]; - GlobalHostingContractArray[counter]['path'][j] = splitPathArray[j]; - } - } - - await Promise.all([addNewTableEntry(await ethoFSHostingContractAddress, await ethoFSHostingContractMainHash, await ethoFSHostingContractName, await ethoFSHostingContractAddress, await ethoFSHostingContractStorage, await ethoFSHostingContractStartBlock, await ethoFSHostingContractEndBlock, await ethoFSHostingContractCost, await counter, await blockHeight)]); - } - } - //END GET ADDITIONAL CONTACT DATA - }; - getContractData(ethoFSAccounts, web3.eth.defaultAccount, TotalContractCount); - - function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractMainHash, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractCost, counter, blockHeight) { - if (blockHeight > ethoFSHostingContractEndBlock) { - ethoFSHostingContractStatus = "Expired"; - hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
    '; - } else { - ethoFSHostingContractStatus = "Active"; - hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
    '; - } - GlobalHostingContractArray[counter]['status'] = ethoFSHostingContractStatus; - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; - } - }); -} -/*************************************************************************************************************/ -//UPDATE CONTRACT DURATION AND CONTRACT COST -function contractDurationChange(selectObj) { - var duration = document.getElementById('contract-duration').value; - GlobalContractDuration = duration; - var ContractCost = (((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522)); - document.getElementById("contract-cost").innerHTML = round(ContractCost, 2); - return false; -} -/*************************************************************************************************************/ -//MISC ROUNDING FUNCTION -function round(value, decimals) { - return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals); -} -/*************************************************************************************************************/ -function finishUploadModal() { - $('#uploadTrackerModal').modal('hide'); - window.stopApplication(); - resetUploadSystem(); - updateContractTable(); - return false; -} - -function resetUploadModal() { - window.stopApplication(); - resetUploadSystem(); - updateContractTable(); - return false; -} -/*************************************************************************************************************/ -//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT -function checkForUploadedContentAvailability(HostingContractName) { - document.getElementById("upload-check-button").style.visibility = "hidden"; - $('#uploadTrackerModal').modal('show'); - document.getElementById("upload-hash").innerHTML = HostingContractName; - return false; -} -/*************************************************************************************************************/ -/*************************************************************************************************************/ -function resetUploadSystem() { - GlobalMainHashArray = new Array(); - GlobalMainPathArray = new Array(); - GlobalHashArray = new Array(); - GlobalPathArray = new Array(); - GlobalUploadHash = ""; - GlobalUploadPath = ""; - GlobalUploadSize = 0; - var TableBody = document.getElementById("file-history-body"); - TableBody.innerHTML = 'There are no files awaiting upload'; - var duration = document.getElementById('contract-duration').value; - GlobalContractDuration = duration; - var ContractCost = ((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522); - document.getElementById("contract-cost").innerHTML = round(ContractCost, 2); - document.getElementById("upload-hash").innerHTML = ""; - document.getElementById("upload-size").innerHTML = 0; - return false; -} -/*************************************************************************************************************/ -/*************************************************************************************************************/ -//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT -function sortContractTable() { - var hostingContracts = ""; - var i; - var localContractArray = GlobalHostingContractArray; - var tableSortDirection = ""; - var sortSelection = document.getElementById('sort-contracts'); - var tableSorter = sortSelection.value; - var filterSelection = document.getElementById('filter-contracts'); - var tableFilterer = filterSelection.value; - - if (tableSorter == "Ascending") { - tableSortDirection = "asc"; - } else { - tableSortDirection = "desc"; - } - localContractArray = multiSort(localContractArray, { - startblock: tableSortDirection - }); - var filterCounter = 0; - for (i = 0; i < GlobalTotalContractCount; i++) { - if ((localContractArray[i]['status'] != "Expired" && tableFilterer == "Active Contracts") || (localContractArray[i]['status'] != "Active" && tableFilterer == "Expired Contracts") || tableFilterer == "All Contracts") { - addNewTableEntry(localContractArray[i]['address'], localContractArray[i]['name'], localContractArray[i]['hash'], localContractArray[i]['storage'], localContractArray[i]['startblock'], localContractArray[i]['endblock'], localContractArray[i]['status'], localContractArray[i]['cost'], i); - filterCounter++; - } else { - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; - } - } - if (GlobalTotalContractCount == 0 || filterCounter == 0) { - hostingContracts = 'No Hosting Contracts Found
    '; - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; - - } - - function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractStatus, ethoFSHostingContractCost, counter) { - if (ethoFSHostingContractStatus == "Active") { - hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
    '; - } else { - hostingContracts += '' + ethoFSHostingContractName + '' + ethoFSHostingContractHash + '' + ethoFSHostingContractStartBlock + '' + ethoFSHostingContractEndBlock + '' + ethoFSHostingContractStatus + '
    '; - } - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; - } - - function multiSort(array, sortObject = {}) { - const sortKeys = Object.keys(sortObject); - // Return array if no sort object is supplied. - if (!sortKeys.length) { - return array; - } - // Change the values of the sortObject keys to -1, 0, or 1. - for (let key in sortObject) { - sortObject[key] = sortObject[key] === 'desc' || sortObject[key] === -1 ? -1 : - (sortObject[key] === 'skip' || sortObject[key] === 0 ? 0 : 1); - } - const keySort = (a, b, direction) => { - direction = direction !== null ? direction : 1; - if (a === b) { // If the values are the same, do not switch positions. - return 0; - } - // If b > a, multiply by -1 to get the reverse direction. - return a > b ? direction : -1 * direction; - }; - return array.sort((a, b) => { - let sorted = 0; - let index = 0; - // Loop until sorted (-1 or 1) or until the sort keys have been processed. - while (sorted === 0 && index < sortKeys.length) { - const key = sortKeys[index]; - if (key) { - const direction = sortObject[key]; - sorted = keySort(a[key], b[key], direction); - index++; - } - } - return sorted; - }); - } -} -/*************************************************************************************************************/ -//SHOW MODAL WITH HOSTING CONTRACT DETAILS -function showHostingContractDetails(counter) { - resetContractExtensionChange(); - - GlobalHostingContractDetailArray = GlobalHostingContractArray[counter]; - $('#contractDetailModal').modal('show'); - document.getElementById("contract-detail-name").innerHTML = GlobalHostingContractDetailArray['name']; - var hashOutputString = ""; - var hostingContractEntry = ""; - for (i = 1; GlobalHostingContractDetailArray['hash'].length > i; i++) { - addNewTableEntry(GlobalHostingContractDetailArray['hash'][i], GlobalHostingContractDetailArray['path'][i], i); - } - document.getElementById("contract-detail-startblock").innerHTML = GlobalHostingContractDetailArray['startblock']; - document.getElementById("contract-detail-endblock").innerHTML = GlobalHostingContractDetailArray['endblock']; - document.getElementById("contract-detail-status").innerHTML = GlobalHostingContractDetailArray['status']; - document.getElementById("contract-detail-size").innerHTML = (GlobalHostingContractDetailArray['storage'] / 1048576); - - function addNewTableEntry(ethoFSHostingContractHash, ethoFSHostingContractPath, count) { - var table = document.getElementById("contract-detail-table"); - var row = table.insertRow(count + 10); - var cell1 = row.insertCell(0); - //var cell2 = row.insertCell(1); - //cell1.innerHTML = ethoFSHostingContractPath; - cell1.innerHTML = '' + ethoFSHostingContractHash + ''; - } - -} - -function resetContractDetailTableRows() { - var x = document.getElementById("contract-detail-table").rows.length; - for (var y = (x - 1); y > 10; y--) { - document.getElementById("contract-detail-table").deleteRow(y); - } -} -/*************************************************************************************************************/ -//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT -function outputNoAddressContractTable() { - hostingContracts = 'No Hosting Contracts Found
    '; - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; -} -//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT -function outputNoAddressContractTableWithButton() { - hostingContracts = 'No Hosting Contracts Found
    '; - document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts; -} -/*************************************************************************************************************/ -function resetContractExtensionChange() { - GlobalExtensionDuration = 0; - document.getElementById("contract-extension-cost").innerHTML = 0; - document.getElementById("extend-contract").selectedIndex = "0"; -} -/*************************************************************************************************************/ -//CONTRACT EXTENSION VALUE CHANGE -function contractExtensionChange(selectObj) { - var index = selectObj.selectedIndex; - var extensionDuration = selectObj.options[index].value; - GlobalExtensionDuration = extensionDuration; - document.getElementById("contract-extension-button").style.visibility = "visible"; - var extensionCost = ((GlobalHostingContractDetailArray['storage'] / 1048576) * GlobalHostingCost) * (extensionDuration / 46522); - document.getElementById("contract-extension-cost").innerHTML = round(extensionCost, 2); -} -/*************************************************************************************************************/ -//CONTRACT EXTENSION CONFIRM -function contractExtensionConfirmation() { - if (GlobalExtensionDuration > 0) { - var extensionDuration = GlobalExtensionDuration; - var ethoFSController = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress); - - var extensionCost = calculateCost(GlobalHostingContractDetailArray['storage'], extensionDuration, GlobalHostingCostWei); - const transactionObject = { - from: GlobalUserAddress, - value: extensionCost - }; - if (privateKeyLogin == true) { - const tx = { - to: GlobalControllerContractAddress, - from: GlobalUserAddress, - value: extensionCost, - gas: 4000000, - data: ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).encodeABI() - }; - var privateKey = '0x' + GlobalPrivateKey; - console.log("Private Key: " + privateKey); - web3.eth.accounts.signTransaction(tx, privateKey) - .then(function(signedTransactionData) { - console.log("Signed TX Data: " + signedTransactionData.rawTransaction); - web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) { - if (!error) { - if (result) { - $('#contractDetailModal').modal('hide'); - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - updateContractTable(); - }); - } else { - console.log("There was a problem adding new contract"); - } - } else { - console.error(error); - } - }); - }); - } else { - - ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).send(transactionObject, function(error, result) { - if (!error) { - if (result) { - $('#contractDetailModal').modal('hide'); - $('#minedBlockTrackerModal').modal('show'); - waitForReceipt(result, function(receipt) { - console.log("Transaction Has Been Mined: " + receipt); - $('#minedBlockTrackerModal').modal('hide'); - updateContractTable(); - }); - } - } else { - console.log(error); - } - }); - } - } -} -/*************************************************************************************************************/ diff --git a/assets/dashboard/js/node.js b/assets/dashboard/js/node.js new file mode 100644 index 0000000..a7f918b --- /dev/null +++ b/assets/dashboard/js/node.js @@ -0,0 +1,83 @@ +'use strict' +const IPFS = require('ipfs'); +const Protector = require('libp2p-pnet'); + +process.env.LIBP2P_FORCE_PNET = 1 +window.node = null; +window.info = null; + +const swarmKey = "/key/swarm/psk/1.0.0/\n/base16/\n38307a74b2176d0054ffa2864e31ee22d0fc6c3266dd856f6d41bddf14e2ad63"; +var swarmKeyBuffer = Buffer.from(swarmKey); + +/* =========================================================================== + Start the IPFS node + =========================================================================== */ +function start() { + console.log("Starting ethoFS Node..."); + if (!node) { + console.log("Setting Up ethoFS Node Options..."); + const options = { + libp2p: { + modules: { + connProtector: new Protector(swarmKeyBuffer) + }, + config: { + dht: { + enabled: false + } + } + }, + config: { + Bootstrap: [ + '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', + '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst', + '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu', + '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ', + '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw', + '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', + '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX', + '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu', + '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', + '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', + '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ' + ], + Addresses: { + Swarm: [ + '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', + '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst', + '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu', + '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ', + '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw', + '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', + '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX', + '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu', + '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W', + '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ', + '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ' + ] + } + } + } + console.log("Launching ethoFS Node..."); + window.node = new IPFS(options) + console.log("Waiting For ethoFS Node Launch Confirmation..."); + window.node.once('start', () => { + console.log("ethoFS Node Startup Confirmed..."); + window.node.id() + .then((id) => { + + window.info = id + console.log("Getting ethoFS Node ID..."); + subscribeToHealthChannel() + updateView('ready', window.node) + onSuccess('Node is ready.') + setInterval(refreshPeerList, 10000) + setInterval(sendFileList, 10000) + }) + .catch((error) => onError(error)) + }) + } +} +window.startNode = function() { + start() +} \ No newline at end of file diff --git a/assets/templates/uploads.html b/assets/templates/uploads.html index 262ed22..6fbf70e 100644 --- a/assets/templates/uploads.html +++ b/assets/templates/uploads.html @@ -173,7 +173,7 @@ @@ -201,7 +201,7 @@ @@ -356,7 +356,7 @@ @@ -665,7 +665,7 @@ - +