diff --git a/.eslintignore b/.eslintignore index e4cade21c..44b38c3de 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,6 +1,20 @@ +node_modules/** +dist/** +builds/** +docs/** + +development/bundle.js +development/states.js + app/scripts/lib/extension-instance.js +app/scripts/chromereload.js + +ui/lib/blockies.js + +mascara/src/app/first-time/spinner.js +mascara/test/jquery-3.1.0.min.js + test/integration/bundle.js test/integration/jquery-3.1.0.min.js test/integration/helpers.js test/integration/lib/first-time.js -ui/lib/blockies.js \ No newline at end of file diff --git a/.eslintrc b/.eslintrc index b49a7a28a..1317864d1 100644 --- a/.eslintrc +++ b/.eslintrc @@ -37,7 +37,9 @@ "document": false, "navigator": false, "web3": true, - "window": false + "window": false, + "$": false, + "QUnit": false }, "rules": { @@ -159,5 +161,6 @@ "yield-star-spacing": [2, "both"], "yoda": [2, "never"], "prefer-const": 1, + "mocha/no-exclusive-tests": "error" } } diff --git a/.nsprc b/.nsprc index cb37fad49..bd3a4f039 100644 --- a/.nsprc +++ b/.nsprc @@ -1,6 +1,7 @@ { "exceptions": [ "https://nodesecurity.io/advisories/566", - "https://nodesecurity.io/advisories/157" + "https://nodesecurity.io/advisories/157", + "https://nodesecurity.io/advisories/577" ] } diff --git a/app/scripts/background.js b/app/scripts/background.js index 45d1adcf5..e61d2f6ea 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -381,7 +381,7 @@ function setupController (initState, initLangCode) { } // communication with page or other extension - function connectExternal(remotePort) { + function connectExternal (remotePort) { const originDomain = urlUtil.parse(remotePort.sender.url).hostname const portStream = new PortStream(remotePort) controller.setupUntrustedCommunication(portStream, originDomain) diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index 75e0a95b3..b35a70dd2 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -115,8 +115,8 @@ function logStreamDisconnectWarning (remoteLabel, err) { * @returns {boolean} {@code true} if Web3 should be injected */ function shouldInjectWeb3 () { - return doctypeCheck() && suffixCheck() - && documentElementCheck() && !blacklistedDomainCheck() + return doctypeCheck() && suffixCheck() && + documentElementCheck() && !blacklistedDomainCheck() } /** diff --git a/app/scripts/controllers/blacklist.js b/app/scripts/controllers/blacklist.js index f100c4525..1d2191433 100644 --- a/app/scripts/controllers/blacklist.js +++ b/app/scripts/controllers/blacklist.js @@ -87,7 +87,7 @@ class BlacklistController { * * @private * @param {object} config A config object like that found at {@link https://github.com/MetaMask/eth-phishing-detect/blob/master/src/config.json} - * + * */ _setupPhishingDetector (config) { this._phishingDetector = new PhishingDetector(config) diff --git a/app/scripts/controllers/computed-balances.js b/app/scripts/controllers/computed-balances.js index 1a6802f9a..e04ce2ef7 100644 --- a/app/scripts/controllers/computed-balances.js +++ b/app/scripts/controllers/computed-balances.js @@ -18,7 +18,7 @@ class ComputedbalancesController { /** * Creates a new controller instance * - * @param {ComputedBalancesOptions} [opts] Controller configuration parameters + * @param {ComputedBalancesOptions} [opts] Controller configuration parameters */ constructor (opts = {}) { const { accountTracker, txController, blockTracker } = opts diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 8411e3a28..b314745f5 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -111,9 +111,9 @@ class PreferencesController { * @returns {Promise} selectedAddress the selected address. */ syncAddresses (addresses) { - let { identities, lostIdentities } = this.store.getState() + const { identities, lostIdentities } = this.store.getState() - let newlyLost = {} + const newlyLost = {} Object.keys(identities).forEach((identity) => { if (!addresses.includes(identity)) { newlyLost[identity] = identities[identity] @@ -128,7 +128,7 @@ class PreferencesController { if (this.diagnostics) this.diagnostics.reportOrphans(newlyLost) // store lost accounts - for (let key in newlyLost) { + for (const key in newlyLost) { lostIdentities[key] = newlyLost[key] } } diff --git a/app/scripts/controllers/recent-blocks.js b/app/scripts/controllers/recent-blocks.js index 4009c35ae..d270f6f44 100644 --- a/app/scripts/controllers/recent-blocks.js +++ b/app/scripts/controllers/recent-blocks.js @@ -127,7 +127,7 @@ class RecentBlocksController { * * @returns {Promise} Promises undefined */ - async backfill() { + async backfill () { this.blockTracker.once('latest', async (blockNumberHex) => { const currentBlockNumber = Number.parseInt(blockNumberHex, 16) const blocksToFetch = Math.min(currentBlockNumber, this.historyLength) diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 6884bbc49..5d7d6d6da 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -455,7 +455,7 @@ class TransactionController extends EventEmitter { txStateManager.on('tx:status-update', updateSubscription) updateSubscription() - function updateSubscription() { + function updateSubscription () { const pendingTxs = txStateManager.getPendingTransactions() if (!listenersAreActive && pendingTxs.length > 0) { blockTracker.on('latest', latestBlockHandler) diff --git a/app/scripts/lib/cleanErrorStack.js b/app/scripts/lib/cleanErrorStack.js index fe1bfb0ce..8adf55db7 100644 --- a/app/scripts/lib/cleanErrorStack.js +++ b/app/scripts/lib/cleanErrorStack.js @@ -3,7 +3,7 @@ * @param {Error} err - error * @returns {Error} Error with clean stack trace. */ -function cleanErrorStack(err){ +function cleanErrorStack (err) { var name = err.name name = (name === undefined) ? 'Error' : String(name) diff --git a/app/scripts/lib/createErrorMiddleware.js b/app/scripts/lib/createErrorMiddleware.js index c70beddfd..7f6a4bd73 100644 --- a/app/scripts/lib/createErrorMiddleware.js +++ b/app/scripts/lib/createErrorMiddleware.js @@ -64,4 +64,4 @@ function createErrorMiddleware ({ override = true } = {}) { } } -module.exports = createErrorMiddleware \ No newline at end of file +module.exports = createErrorMiddleware diff --git a/app/scripts/lib/createStreamSink.js b/app/scripts/lib/createStreamSink.js index cf9416fea..b93dbc089 100644 --- a/app/scripts/lib/createStreamSink.js +++ b/app/scripts/lib/createStreamSink.js @@ -4,7 +4,7 @@ const promiseToCallback = require('promise-to-callback') module.exports = createStreamSink -function createStreamSink(asyncWriteFn, _opts) { +function createStreamSink (asyncWriteFn, _opts) { return new AsyncWritableStream(asyncWriteFn, _opts) } diff --git a/app/scripts/lib/diagnostics-reporter.js b/app/scripts/lib/diagnostics-reporter.js index aa4ca6e26..569eb3268 100644 --- a/app/scripts/lib/diagnostics-reporter.js +++ b/app/scripts/lib/diagnostics-reporter.js @@ -5,7 +5,7 @@ class DiagnosticsReporter { this.version = version } - async reportOrphans(orphans) { + async reportOrphans (orphans) { try { return await this.submit({ accounts: Object.keys(orphans), @@ -19,7 +19,7 @@ class DiagnosticsReporter { } } - async reportMultipleKeyrings(rawKeyrings) { + async reportMultipleKeyrings (rawKeyrings) { try { const keyrings = await Promise.all(rawKeyrings.map(async (keyring, index) => { return { @@ -55,7 +55,7 @@ class DiagnosticsReporter { } -function postData(data) { +function postData (data) { const uri = 'https://diagnostics.metamask.io/v1/orphanedAccounts' return fetch(uri, { body: JSON.stringify(data), // must match 'Content-Type' header diff --git a/app/scripts/lib/extractEthjsErrorMessage.js b/app/scripts/lib/extractEthjsErrorMessage.js index 0f100756f..4891075c3 100644 --- a/app/scripts/lib/extractEthjsErrorMessage.js +++ b/app/scripts/lib/extractEthjsErrorMessage.js @@ -10,13 +10,13 @@ module.exports = extractEthjsErrorMessage * * @param {string} errorMessage The error message to parse * @returns {string} Returns an error message, either the same as was passed, or the ending message portion of an isEthjsRpcError - * + * * @example * // returns 'Transaction Failed: replacement transaction underpriced' * extractEthjsErrorMessage(`Error: [ethjs-rpc] rpc error with payload {"id":3947817945380,"jsonrpc":"2.0","params":["0xf8eb8208708477359400830398539406012c8cf97bead5deae237070f9587f8e7a266d80b8843d7d3f5a0000000000000000000000000000000000000000000000000000000000081d1a000000000000000000000000000000000000000000000000001ff973cafa800000000000000000000000000000000000000000000000000000038d7ea4c68000000000000000000000000000000000000000000000000000000000000003f48025a04c32a9b630e0d9e7ff361562d850c86b7a884908135956a7e4a336fa0300d19ca06830776423f25218e8d19b267161db526e66895567147015b1f3fc47aef9a3c7"],"method":"eth_sendRawTransaction"} Error: replacement transaction underpriced`) * */ -function extractEthjsErrorMessage(errorMessage) { +function extractEthjsErrorMessage (errorMessage) { const isEthjsRpcError = errorMessage.includes(ethJsRpcSlug) if (isEthjsRpcError) { const payloadAndError = errorMessage.slice(ethJsRpcSlug.length) diff --git a/app/scripts/lib/get-first-preferred-lang-code.js b/app/scripts/lib/get-first-preferred-lang-code.js index 41a886d74..170d508c1 100644 --- a/app/scripts/lib/get-first-preferred-lang-code.js +++ b/app/scripts/lib/get-first-preferred-lang-code.js @@ -28,7 +28,7 @@ async function getFirstPreferredLangCode () { // safeguard for Brave Browser until they implement chrome.i18n.getAcceptLanguages // https://github.com/MetaMask/metamask-extension/issues/4270 - if (!userPreferredLocaleCodes){ + if (!userPreferredLocaleCodes) { userPreferredLocaleCodes = [] } diff --git a/app/scripts/lib/getObjStructure.js b/app/scripts/lib/getObjStructure.js index 52250d3fb..9c92879fb 100644 --- a/app/scripts/lib/getObjStructure.js +++ b/app/scripts/lib/getObjStructure.js @@ -18,12 +18,12 @@ module.exports = getObjStructure * Creates an object that represents the structure of the given object. It replaces all values with the result of their * type. * - * @param {object} obj The object for which a 'structure' will be returned. Usually a plain object and not a class. + * @param {object} obj The object for which a 'structure' will be returned. Usually a plain object and not a class. * @returns {object} The "mapped" version of a deep clone of the passed object, with each non-object property value * replaced with the javascript type of that value. * */ -function getObjStructure(obj) { +function getObjStructure (obj) { const structure = clone(obj) return deepMap(structure, (value) => { return value === null ? 'null' : typeof value @@ -38,7 +38,7 @@ function getObjStructure(obj) { * @param {Function} visit The modifier to apply to each non-object property value * @returns {object} The modified object */ -function deepMap(target = {}, visit) { +function deepMap (target = {}, visit) { Object.entries(target).forEach(([key, value]) => { if (typeof value === 'object' && value !== null) { target[key] = deepMap(value, visit) diff --git a/app/scripts/lib/local-store.js b/app/scripts/lib/local-store.js index 139ff86bd..fbcba09cd 100644 --- a/app/scripts/lib/local-store.js +++ b/app/scripts/lib/local-store.js @@ -8,7 +8,7 @@ module.exports = class ExtensionStore { /** * @constructor */ - constructor() { + constructor () { this.isSupported = !!(extension.storage.local) if (!this.isSupported) { log.error('Storage local API not available.') @@ -19,7 +19,7 @@ module.exports = class ExtensionStore { * Returns all of the keys currently saved * @return {Promise<*>} */ - async get() { + async get () { if (!this.isSupported) return undefined const result = await this._get() // extension.storage.local always returns an obj @@ -36,7 +36,7 @@ module.exports = class ExtensionStore { * @param {object} state - The state to set * @return {Promise} */ - async set(state) { + async set (state) { return this._set(state) } @@ -45,7 +45,7 @@ module.exports = class ExtensionStore { * @private * @return {object} the key-value map from local storage */ - _get() { + _get () { const local = extension.storage.local return new Promise((resolve, reject) => { local.get(null, (/** @type {any} */ result) => { @@ -65,7 +65,7 @@ module.exports = class ExtensionStore { * @return {Promise} * @private */ - _set(obj) { + _set (obj) { const local = extension.storage.local return new Promise((resolve, reject) => { local.set(obj, () => { @@ -85,6 +85,6 @@ module.exports = class ExtensionStore { * @param {object} obj - The object to check * @returns {boolean} */ -function isEmpty(obj) { +function isEmpty (obj) { return Object.keys(obj).length === 0 } diff --git a/app/scripts/lib/notification-manager.js b/app/scripts/lib/notification-manager.js index 6b88a7a99..969a9459a 100644 --- a/app/scripts/lib/notification-manager.js +++ b/app/scripts/lib/notification-manager.js @@ -26,15 +26,15 @@ class NotificationManager { // bring focus to existing chrome popup extension.windows.update(popup.id, { focused: true }) } else { + const cb = (currentPopup) => { this._popupId = currentPopup.id } // create new notification popup - extension.windows.create({ + const creation = extension.windows.create({ url: 'notification.html', type: 'popup', width, height, - }).then((currentPopup) => { - this._popupId = currentPopup.id - }) + }, cb) + creation && creation.then && creation.then(cb) } }) } diff --git a/app/scripts/lib/port-stream.js b/app/scripts/lib/port-stream.js index 5c4224fd9..fd65d94f3 100644 --- a/app/scripts/lib/port-stream.js +++ b/app/scripts/lib/port-stream.js @@ -58,7 +58,7 @@ PortDuplexStream.prototype._read = noop /** * Called internally when data should be written to * this writable stream. - * + * * @private * @param {*} msg Arbitrary object to write * @param {string} encoding Encoding to use when writing payload diff --git a/app/scripts/lib/reportFailedTxToSentry.js b/app/scripts/lib/reportFailedTxToSentry.js index e09f4f1f8..df5661e59 100644 --- a/app/scripts/lib/reportFailedTxToSentry.js +++ b/app/scripts/lib/reportFailedTxToSentry.js @@ -7,7 +7,7 @@ module.exports = reportFailedTxToSentry // for sending to sentry // -function reportFailedTxToSentry({ raven, txMeta }) { +function reportFailedTxToSentry ({ raven, txMeta }) { const errorMessage = 'Transaction Failed: ' + extractEthjsErrorMessage(txMeta.err.message) raven.captureMessage(errorMessage, { // "extra" key is required by Sentry diff --git a/app/scripts/lib/setupMetamaskMeshMetrics.js b/app/scripts/lib/setupMetamaskMeshMetrics.js index 02690a948..fd3b93fc4 100644 --- a/app/scripts/lib/setupMetamaskMeshMetrics.js +++ b/app/scripts/lib/setupMetamaskMeshMetrics.js @@ -4,7 +4,7 @@ module.exports = setupMetamaskMeshMetrics /** * Injects an iframe into the current document for testing */ -function setupMetamaskMeshMetrics() { +function setupMetamaskMeshMetrics () { const testingContainer = document.createElement('iframe') testingContainer.src = 'https://metamask.github.io/mesh-testing/' console.log('Injecting MetaMask Mesh testing client') diff --git a/app/scripts/lib/setupRaven.js b/app/scripts/lib/setupRaven.js index 30d0a3680..85a078bf3 100644 --- a/app/scripts/lib/setupRaven.js +++ b/app/scripts/lib/setupRaven.js @@ -7,7 +7,7 @@ const DEV = 'https://f59f3dd640d2429d9d0e2445a87ea8e1@sentry.io/273496' module.exports = setupRaven // Setup raven / sentry remote error reporting -function setupRaven(opts) { +function setupRaven (opts) { const { release } = opts let ravenTarget @@ -21,7 +21,7 @@ function setupRaven(opts) { const client = Raven.config(ravenTarget, { release, - transport: function(opts) { + transport: function (opts) { const report = opts.data try { // handle error-like non-error exceptions @@ -42,7 +42,7 @@ function setupRaven(opts) { return Raven } -function rewriteErrorLikeExceptions(report) { +function rewriteErrorLikeExceptions (report) { // handle errors that lost their error-ness in serialization (e.g. dnode) rewriteErrorMessages(report, (errorMessage) => { if (!errorMessage.includes('Non-Error exception captured with keys:')) return errorMessage @@ -51,7 +51,7 @@ function rewriteErrorLikeExceptions(report) { }) } -function simplifyErrorMessages(report) { +function simplifyErrorMessages (report) { rewriteErrorMessages(report, (errorMessage) => { // simplify ethjs error messages errorMessage = extractEthjsErrorMessage(errorMessage) @@ -64,7 +64,7 @@ function simplifyErrorMessages(report) { }) } -function rewriteErrorMessages(report, rewriteFn) { +function rewriteErrorMessages (report, rewriteFn) { // rewrite top level message if (typeof report.message === 'string') report.message = rewriteFn(report.message) // rewrite each exception message @@ -75,7 +75,7 @@ function rewriteErrorMessages(report, rewriteFn) { } } -function rewriteReportUrls(report) { +function rewriteReportUrls (report) { // update request url report.request.url = toMetamaskUrl(report.request.url) // update exception stack trace @@ -88,7 +88,7 @@ function rewriteReportUrls(report) { } } -function toMetamaskUrl(origUrl) { +function toMetamaskUrl (origUrl) { const filePath = origUrl.split(location.origin)[1] if (!filePath) return origUrl const metamaskUrl = `metamask${filePath}` diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 9abb64900..3d7268395 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -399,7 +399,6 @@ module.exports = class MetamaskController extends EventEmitter { } - //============================================================================= // VAULT / KEYRING RELATED METHODS //============================================================================= @@ -645,7 +644,7 @@ module.exports = class MetamaskController extends EventEmitter { * @param {Object} msgParams - The params passed to eth_sign. * @param {Object} req - (optional) the original request, containing the origin */ - async newUnapprovedTransaction(txParams, req) { + async newUnapprovedTransaction (txParams, req) { return await this.txController.newUnapprovedTransaction(txParams, req) } @@ -931,7 +930,7 @@ module.exports = class MetamaskController extends EventEmitter { * Allows a user to begin the seed phrase recovery process. * @param {Function} cb - A callback function called when complete. */ - markPasswordForgotten(cb) { + markPasswordForgotten (cb) { this.configManager.setPasswordForgotten(true) this.sendUpdate() cb() @@ -941,7 +940,7 @@ module.exports = class MetamaskController extends EventEmitter { * Allows a user to end the seed phrase recovery process. * @param {Function} cb - A callback function called when complete. */ - unMarkPasswordForgotten(cb) { + unMarkPasswordForgotten (cb) { this.configManager.setPasswordForgotten(false) this.sendUpdate() cb() diff --git a/app/scripts/migrations/013.js b/app/scripts/migrations/013.js index 15a9b28d4..fb7131f8e 100644 --- a/app/scripts/migrations/013.js +++ b/app/scripts/migrations/013.js @@ -28,7 +28,7 @@ module.exports = { function transformState (state) { const newState = state const { config } = newState - if ( config && config.provider ) { + if (config && config.provider) { if (config.provider.type === 'testnet') { newState.config.provider.type = 'ropsten' } diff --git a/app/scripts/migrations/023.js b/app/scripts/migrations/023.js index 151496b06..18493a789 100644 --- a/app/scripts/migrations/023.js +++ b/app/scripts/migrations/023.js @@ -35,10 +35,10 @@ function transformState (state) { if (transactions.length <= 40) return newState - let reverseTxList = transactions.reverse() + const reverseTxList = transactions.reverse() let stripping = true while (reverseTxList.length > 40 && stripping) { - let txIndex = reverseTxList.findIndex((txMeta) => { + const txIndex = reverseTxList.findIndex((txMeta) => { return (txMeta.status === 'failed' || txMeta.status === 'rejected' || txMeta.status === 'confirmed' || diff --git a/app/scripts/popup-core.js b/app/scripts/popup-core.js index 6325b8a8d..db885ec93 100644 --- a/app/scripts/popup-core.js +++ b/app/scripts/popup-core.js @@ -12,7 +12,7 @@ module.exports = initializePopup /** * Asynchronously initializes the MetaMask popup UI * - * @param {{ container: Element, connectionStream: * }} config Popup configuration object + * @param {{ container: Element, connectionStream: * }} config Popup configuration object * @param {Function} cb Called when initialization is complete */ function initializePopup ({ container, connectionStream }, cb) { diff --git a/app/scripts/ui.js b/app/scripts/ui.js index bdab29c1e..9bf97be87 100644 --- a/app/scripts/ui.js +++ b/app/scripts/ui.js @@ -14,7 +14,7 @@ const log = require('loglevel') start().catch(log.error) -async function start() { +async function start () { // create platform global global.platform = new ExtensionPlatform() diff --git a/development/announcer.js b/development/announcer.js index e97ea65b6..ea1bfdd36 100644 --- a/development/announcer.js +++ b/development/announcer.js @@ -7,6 +7,6 @@ var changelog = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md')).toSt var log = changelog.split(version)[1].split('##')[0].trim() -let msg = `*MetaMask ${version}* now published! It should auto-update soon!\n${log}` +const msg = `*MetaMask ${version}* now published! It should auto-update soon!\n${log}` console.log(msg) diff --git a/development/backGroundConnectionModifiers.js b/development/backGroundConnectionModifiers.js index ffbe49d4d..665f72898 100644 --- a/development/backGroundConnectionModifiers.js +++ b/development/backGroundConnectionModifiers.js @@ -1,5 +1,5 @@ module.exports = { - "confirm sig requests": { + 'confirm sig requests': { signMessage: (msgData, cb) => { const stateUpdate = { unapprovedMsgs: {}, diff --git a/development/beefy.js b/development/beefy.js index 9eff94320..c1c436cb6 100644 --- a/development/beefy.js +++ b/development/beefy.js @@ -1,17 +1,14 @@ const beefy = require('beefy') const http = require('http') -const fs = require('fs') -const path = require('path') - const port = 8124 const handler = beefy({ - entries: {'mocker.js': 'bundle.js'} - , cwd: __dirname - , live: true - , open: true - , quiet: false - , bundlerFlags: ['-t', 'brfs'] + entries: {'mocker.js': 'bundle.js'}, + cwd: __dirname, + live: true, + open: true, + quiet: false, + bundlerFlags: ['-t', 'brfs'], }) diff --git a/development/metamaskbot-build-announce.js b/development/metamaskbot-build-announce.js index 88614ca5c..96b5572fe 100755 --- a/development/metamaskbot-build-announce.js +++ b/development/metamaskbot-build-announce.js @@ -4,7 +4,7 @@ const VERSION = require('../dist/chrome/manifest.json').version start().catch(console.error) -async function start() { +async function start () { const GITHUB_COMMENT_TOKEN = process.env.GITHUB_COMMENT_TOKEN const CIRCLE_PULL_REQUEST = process.env.CIRCLE_PULL_REQUEST @@ -20,7 +20,7 @@ async function start() { } const CIRCLE_PR_NUMBER = CIRCLE_PULL_REQUEST.split('/').pop() - const SHORT_SHA1 = CIRCLE_SHA1.slice(0,7) + const SHORT_SHA1 = CIRCLE_SHA1.slice(0, 7) const BUILD_LINK_BASE = `https://${CIRCLE_BUILD_NUM}-42009758-gh.circle-artifacts.com/0` const MASCARA = `${BUILD_LINK_BASE}/builds/mascara/home.html` diff --git a/development/mock-dev.js b/development/mock-dev.js index f332633d5..15f6ad4bf 100644 --- a/development/mock-dev.js +++ b/development/mock-dev.js @@ -12,7 +12,6 @@ * To use, run `npm run mock`. */ -const extend = require('xtend') const render = require('react-dom').render const h = require('react-hyperscript') const Root = require('../ui/app/root') @@ -24,7 +23,6 @@ const Selector = require('./selector') const MetamaskController = require('../app/scripts/metamask-controller') const firstTimeState = require('../app/scripts/first-time-state') const ExtensionPlatform = require('../app/scripts/platforms/extension') -const extension = require('./mockExtension') const noop = function () {} const log = require('loglevel') @@ -81,14 +79,14 @@ const controller = new MetamaskController({ initState: firstTimeState, }) global.metamaskController = controller -global.platform = new ExtensionPlatform +global.platform = new ExtensionPlatform() // // User Interface // actions._setBackgroundConnection(controller.getApi()) -actions.update = function(stateName) { +actions.update = function (stateName) { selectedView = stateName updateQueryParams(stateName) const newState = states[selectedView] @@ -98,7 +96,7 @@ actions.update = function(stateName) { } } -function modifyBackgroundConnection(backgroundConnectionModifier) { +function modifyBackgroundConnection (backgroundConnectionModifier) { const modifiedBackgroundConnection = Object.assign({}, controller.getApi(), backgroundConnectionModifier) actions._setBackgroundConnection(modifiedBackgroundConnection) } @@ -112,7 +110,7 @@ var store = configureStore(firstState) // start app startApp() -function startApp(){ +function startApp () { const body = document.body const container = document.createElement('div') container.id = 'test-container' diff --git a/development/mockExtension.js b/development/mockExtension.js index ac03d965c..634d4263a 100644 --- a/development/mockExtension.js +++ b/development/mockExtension.js @@ -39,6 +39,6 @@ extension.runtime.reload = noop extension.tabs.create = noop extension.runtime.getManifest = function () { return { - version: 'development' + version: 'development', } -} \ No newline at end of file +} diff --git a/development/run-version-bump.js b/development/run-version-bump.js index 98757f58e..32fed1865 100644 --- a/development/run-version-bump.js +++ b/development/run-version-bump.js @@ -11,7 +11,7 @@ const bumpType = normalizeType(process.argv[2]) start().catch(console.error) -async function start() { +async function start () { const changeBuffer = await readFile(changelogPath) const changelog = changeBuffer.toString() diff --git a/development/selector.js b/development/selector.js index fd387df15..2673d0fe3 100644 --- a/development/selector.js +++ b/development/selector.js @@ -11,7 +11,7 @@ function NewComponent () { NewComponent.prototype.render = function () { const props = this.props - let { + const { states, selectedKey, actions, @@ -28,7 +28,7 @@ NewComponent.prototype.render = function () { margin: '20px 20px 0px', }, value: selected, - onChange:(event) => { + onChange: (event) => { const selectedKey = event.target.value const backgroundConnectionModifier = backGroundConnectionModifiers[selectedKey] modifyBackgroundConnection(backgroundConnectionModifier || {}) diff --git a/development/sentry-publish.js b/development/sentry-publish.js index ab3acabbd..7a6d55115 100644 --- a/development/sentry-publish.js +++ b/development/sentry-publish.js @@ -5,7 +5,7 @@ const VERSION = require('../dist/chrome/manifest.json').version start().catch(console.error) -async function start(){ +async function start () { const authWorked = await checkIfAuthWorks() if (!authWorked) { console.log(`Sentry auth failed...`) @@ -31,21 +31,21 @@ async function start(){ console.log('all done!') } -async function checkIfAuthWorks() { +async function checkIfAuthWorks () { const itWorked = await doesNotFail(async () => { await exec(`sentry-cli releases --org 'metamask' --project 'metamask' list`) }) return itWorked } -async function checkIfVersionExists() { +async function checkIfVersionExists () { const versionAlreadyExists = await doesNotFail(async () => { await exec(`sentry-cli releases --org 'metamask' --project 'metamask' info ${VERSION}`) }) return versionAlreadyExists } -async function doesNotFail(asyncFn) { +async function doesNotFail (asyncFn) { try { await asyncFn() return true diff --git a/development/sourcemap-validator.js b/development/sourcemap-validator.js index edc97667a..143888128 100644 --- a/development/sourcemap-validator.js +++ b/development/sourcemap-validator.js @@ -1,6 +1,6 @@ const fs = require('fs') const { SourceMapConsumer } = require('source-map') - +const path = require('path') // // Utility to help check if sourcemaps are working // @@ -11,9 +11,11 @@ const { SourceMapConsumer } = require('source-map') start() -async function start() { - const rawBuild = fs.readFileSync(__dirname + '/../dist/chrome/inpage.js', 'utf8') - const rawSourceMap = fs.readFileSync(__dirname + '/../dist/sourcemaps/inpage.js.map', 'utf8') + +async function start () { + const rawBuild = fs.readFileSync(path.join(__dirname, '/../dist/chrome/', 'inpage.js') + , 'utf8') + const rawSourceMap = fs.readFileSync(path.join(__dirname, '/../dist/sourcemaps/', 'inpage.js.map'), 'utf8') const consumer = await new SourceMapConsumer(rawSourceMap) console.log('hasContentsOfAllSources:', consumer.hasContentsOfAllSources(), '\n') @@ -34,7 +36,7 @@ async function start() { if (result.source === 'node_modules/web3/dist/web3.min.js') return // minified mess const sourceContent = consumer.sourceContentFor(result.source) const sourceLines = sourceContent.split('\n') - const line = sourceLines[result.line-1] + const line = sourceLines[result.line - 1] console.log(`\n========================== ${result.source} ====================================\n`) console.log(line) console.log(`\n==============================================================================\n`) @@ -42,8 +44,9 @@ async function start() { }) } -function indicesOf(substring, string) { - var a=[],i=-1; - while((i=string.indexOf(substring,i+1)) >= 0) a.push(i); - return a; +function indicesOf (substring, string) { + var a = [] + var i = -1 + while ((i = string.indexOf(substring, i + 1)) >= 0) a.push(i) + return a } diff --git a/development/ui-dev.js b/development/ui-dev.js index cac433909..bae0ce50e 100644 --- a/development/ui-dev.js +++ b/development/ui-dev.js @@ -29,9 +29,8 @@ log.setDefaultLevel(1) // Query String const qs = require('qs') -let queryString = qs.parse(window.location.href.split('#')[1]) +const queryString = qs.parse(window.location.href.split('#')[1]) let selectedView = queryString.view || 'first time' -const firstState = states[selectedView] updateQueryParams(selectedView) // CSS @@ -39,15 +38,15 @@ const MetaMaskUiCss = require('../ui/css') const injectCss = require('inject-css') -function updateQueryParams(newView) { +function updateQueryParams (newView) { queryString.view = newView const params = qs.stringify(queryString) window.location.href = window.location.href.split('#')[0] + `#${params}` } const actions = { - _setBackgroundConnection(){}, - update: function(stateName) { + _setBackgroundConnection () {}, + update: function (stateName) { selectedView = stateName updateQueryParams(stateName) const newState = states[selectedView] @@ -67,7 +66,7 @@ var store = configureStore(states[selectedView]) // start app startApp() -function startApp(){ +function startApp () { const body = document.body const container = document.createElement('div') container.id = 'test-container' diff --git a/development/verify-locale-strings.js b/development/verify-locale-strings.js index 8dc0a30f1..0eef2b35d 100644 --- a/development/verify-locale-strings.js +++ b/development/verify-locale-strings.js @@ -1,4 +1,4 @@ -//////////////////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////////////////// // // Locale verification script // @@ -8,7 +8,7 @@ // // will check the given locale against the strings in english // -//////////////////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////////////////// const fs = require('fs') const path = require('path') @@ -20,7 +20,7 @@ const specifiedLocale = process.argv[2] if (specifiedLocale) { console.log(`Verifying selected locale "${specifiedLocale}":\n\n`) const locale = localeIndex.find(localeMeta => localeMeta.code === specifiedLocale) - verifyLocale({ localeMeta }) + verifyLocale({ locale }) } else { console.log('Verifying all locales:\n\n') localeIndex.forEach(localeMeta => { @@ -30,16 +30,16 @@ if (specifiedLocale) { } - -function verifyLocale({ localeMeta }) { +function verifyLocale ({ localeMeta }) { const localeCode = localeMeta.code const localeName = localeMeta.name + let targetLocale, englishLocale try { const localeFilePath = path.join(process.cwd(), 'app', '_locales', localeCode, 'messages.json') - targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8')); + targetLocale = JSON.parse(fs.readFileSync(localeFilePath, 'utf8')) } catch (e) { - if (e.code == 'ENOENT') { + if (e.code === 'ENOENT') { console.log('Locale file not found') } else { console.log(`Error opening your locale ("${localeCode}") file: `, e) @@ -49,9 +49,9 @@ function verifyLocale({ localeMeta }) { try { const englishFilePath = path.join(process.cwd(), 'app', '_locales', 'en', 'messages.json') - englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8')); + englishLocale = JSON.parse(fs.readFileSync(englishFilePath, 'utf8')) } catch (e) { - if(e.code == 'ENOENT') { + if (e.code === 'ENOENT') { console.log('English File not found') } else { console.log('Error opening english locale file: ', e) @@ -71,7 +71,7 @@ function verifyLocale({ localeMeta }) { if (extraItems.length) { console.log('\nMissing from english locale:') - extraItems.forEach(function(key) { + extraItems.forEach(function (key) { console.log(` - [ ] ${key}`) }) } else { @@ -80,7 +80,7 @@ function verifyLocale({ localeMeta }) { if (missingItems.length) { console.log(`\nMissing:`) - missingItems.forEach(function(key) { + missingItems.forEach(function (key) { console.log(` - [ ] ${key}`) }) } else { @@ -92,6 +92,6 @@ function verifyLocale({ localeMeta }) { } } -function compareLocalesForMissingItems({ base, subject }) { +function compareLocalesForMissingItems ({ base, subject }) { return Object.keys(base).filter((key) => !subject[key]) } diff --git a/development/version-bump.js b/development/version-bump.js index bedf87c01..fa20e9f75 100644 --- a/development/version-bump.js +++ b/development/version-bump.js @@ -1,6 +1,6 @@ const clone = require('clone') -async function versionBump(bumpType, changelog, oldManifest) { +async function versionBump (bumpType, changelog, oldManifest) { const manifest = clone(oldManifest) const newVersion = newVersionFrom(manifest, bumpType) @@ -19,13 +19,13 @@ async function versionBump(bumpType, changelog, oldManifest) { return { version: newVersion, manifest: manifest, - changelog: logLines.join('\n') + changelog: logLines.join('\n'), } } function newVersionFrom (manifest, bumpType) { const string = manifest.version - let segments = string.split('.').map((str) => parseInt(str)) + const segments = string.split('.').map((str) => parseInt(str)) switch (bumpType) { case 'major': @@ -45,8 +45,4 @@ function newVersionFrom (manifest, bumpType) { return segments.map(String).join('.') } -function bumpManifest (manifest, bumpType) { - -} - module.exports = versionBump diff --git a/gentests.js b/gentests.js index 08232e10f..9c591e98c 100644 --- a/gentests.js +++ b/gentests.js @@ -1,6 +1,6 @@ const fs = require('fs') -const async = require('async') const path = require('path') +const async = require('async') const promisify = require('pify') // start(/\.selectors.js/, generateSelectorTest).catch(console.error) @@ -8,7 +8,6 @@ const promisify = require('pify') startContainer(/\.container.js/, generateContainerTest).catch(console.error) async function getAllFileNames (dirName) { - const rootPath = path.join(__dirname, dirName) const allNames = (await promisify(fs.readdir)(dirName)) const fileNames = allNames.filter(name => name.match(/^.+\./)) const dirNames = allNames.filter(name => name.match(/^[^.]+$/)) @@ -16,7 +15,7 @@ async function getAllFileNames (dirName) { const fullPathDirNames = dirNames.map(d => `${dirName}/${d}`) const subNameArrays = await promisify(async.map)(fullPathDirNames, getAllFileNames) let subNames = [] - subNameArrays.forEach(subNameArray => subNames = [...subNames, ...subNameArray]) + subNameArrays.forEach(subNameArray => { subNames = [...subNames, ...subNameArray] }) return [ ...fileNames.map(name => dirName + '/' + name), @@ -24,14 +23,15 @@ async function getAllFileNames (dirName) { ] } +/* async function start (fileRegEx, testGenerator) { const fileNames = await getAllFileNames('./ui/app') const sFiles = fileNames.filter(name => name.match(fileRegEx)) - + let sFileMethodNames let testFilePath async.each(sFiles, async (sFile, cb) => { - let [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/) + const [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/) sFileMethodNames = Object.keys(require(__dirname + '/' + sFile)) testFilePath = sPath.replace('.', '-').replace('.', '.test.') @@ -44,92 +44,96 @@ async function start (fileRegEx, testGenerator) { }, (err) => { console.log(err) }) - + } +*/ async function startContainer (fileRegEx, testGenerator) { const fileNames = await getAllFileNames('./ui/app') const sFiles = fileNames.filter(name => name.match(fileRegEx)) - - let sFileMethodNames + async.each(sFiles, async (sFile, cb) => { - console.log(`sFile`, sFile); - let [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/) - - let testFilePath = sPath.replace('.', '-').replace('.', '.test.') + console.log(`sFile`, sFile) + const [, sRootPath, sPath] = sFile.match(/^(.+\/)([^/]+)$/) + + const testFilePath = sPath.replace('.', '-').replace('.', '.test.') await promisify(fs.readFile)( - __dirname + '/' + sFile, + path.join(__dirname, sFile), 'utf8', async (err, result) => { - console.log(`result`, result.length); - const returnObjectStrings = result - .match(/return\s(\{[\s\S]+?})\n}/g) - .map(str => { - return str - .slice(0, str.length - 1) - .slice(7) - .replace(/\n/g, '') - .replace(/\s\s+/g, ' ') - + if (err) { + console.log('Error: ', err) + } else { + console.log(`result`, result.length) + const returnObjectStrings = result + .match(/return\s(\{[\s\S]+?})\n}/g) + .map(str => { + return str + .slice(0, str.length - 1) + .slice(7) + .replace(/\n/g, '') + .replace(/\s\s+/g, ' ') + + }) + const mapStateToPropsAssertionObject = returnObjectStrings[0] + .replace(/\w+:\s\w+\([\w,\s]+\),/g, str => { + const strKey = str.match(/^\w+/)[0] + return strKey + ': \'mock' + str.match(/^\w+/)[0].replace(/^./, c => c.toUpperCase()) + ':mockState\',\n' + }) + .replace(/{\s\w.+/, firstLinePair => `{\n ${firstLinePair.slice(2)}`) + .replace(/\w+:.+,/g, s => ` ${s}`) + .replace(/}/g, s => ` ${s}`) + let mapDispatchToPropsMethodNames + if (returnObjectStrings[1]) { + mapDispatchToPropsMethodNames = returnObjectStrings[1].match(/\s\w+:\s/g).map(str => str.match(/\w+/)[0]) + } + const proxyquireObject = ('{\n ' + result + .match(/import\s{[\s\S]+?}\sfrom\s.+/g) + .map(s => s.replace(/\n/g, '')) + .map((s, i) => { + const proxyKeys = s.match(/{.+}/)[0].match(/\w+/g) + return '\'' + s.match(/'(.+)'/)[1] + '\': { ' + (proxyKeys.length > 1 + ? '\n ' + proxyKeys.join(': () => {},\n ') + ': () => {},\n ' + : proxyKeys[0] + ': () => {},') + ' }' + }) + .join(',\n ') + '\n}') + .replace('{ connect: () => {}, },', `{ + connect: (ms, md) => { + mapStateToProps = ms + mapDispatchToProps = md + return () => ({}) + }, + },`) + // console.log(`proxyquireObject`, proxyquireObject); + // console.log(`mapStateToPropsAssertionObject`, mapStateToPropsAssertionObject); + // console.log(`mapDispatchToPropsMethodNames`, mapDispatchToPropsMethodNames); + + const containerTest = generateContainerTest(sPath, { + mapStateToPropsAssertionObject, + mapDispatchToPropsMethodNames, + proxyquireObject, }) - const mapStateToPropsAssertionObject = returnObjectStrings[0] - .replace(/\w+:\s\w+\([\w,\s]+\),/g, str => { - const strKey = str.match(/^\w+/)[0] - return strKey + ': \'mock' + str.match(/^\w+/)[0].replace(/^./, c => c.toUpperCase()) + ':mockState\',\n' - }) - .replace(/{\s\w.+/, firstLinePair => `{\n ${firstLinePair.slice(2)}`) - .replace(/\w+:.+,/g, s => ` ${s}`) - .replace(/}/g, s => ` ${s}`) - let mapDispatchToPropsMethodNames - if (returnObjectStrings[1]) { - mapDispatchToPropsMethodNames = returnObjectStrings[1].match(/\s\w+:\s/g).map(str => str.match(/\w+/)[0]) + // console.log(`containerTest`, `${__dirname}/${sRootPath}tests/${testFilePath}`, containerTest); + console.log('----') + console.log(`sRootPath`, sRootPath) + console.log(`testFilePath`, testFilePath) + await promisify(fs.writeFile)( + `${__dirname}/${sRootPath}tests/${testFilePath}`, + containerTest, + 'utf8' + ) } - const proxyquireObject = ('{\n ' + result - .match(/import\s{[\s\S]+?}\sfrom\s.+/g) - .map(s => s.replace(/\n/g, '')) - .map((s, i) => { - const proxyKeys = s.match(/{.+}/)[0].match(/\w+/g) - return '\'' + s.match(/'(.+)'/)[1] + '\': { ' + (proxyKeys.length > 1 - ? '\n ' + proxyKeys.join(': () => {},\n ') + ': () => {},\n ' - : proxyKeys[0] + ': () => {},') + ' }' - }) - .join(',\n ') + '\n}') - .replace('{ connect: () => {}, },', `{ - connect: (ms, md) => { - mapStateToProps = ms - mapDispatchToProps = md - return () => ({}) - }, - },`) - // console.log(`proxyquireObject`, proxyquireObject); - // console.log(`mapStateToPropsAssertionObject`, mapStateToPropsAssertionObject); - // console.log(`mapDispatchToPropsMethodNames`, mapDispatchToPropsMethodNames); - - const containerTest = generateContainerTest(sPath, { - mapStateToPropsAssertionObject, - mapDispatchToPropsMethodNames, - proxyquireObject, - }) - // console.log(`containerTest`, `${__dirname}/${sRootPath}tests/${testFilePath}`, containerTest); - console.log('----') - console.log(`sRootPath`, sRootPath); - console.log(`testFilePath`, testFilePath); - await promisify(fs.writeFile)( - `${__dirname}/${sRootPath}tests/${testFilePath}`, - containerTest, - 'utf8' - ) } ) }, (err) => { console.log('123', err) }) - -} +} +/* function generateMethodList (methodArray) { - return methodArray.map(n => ' ' + n).join(',\n') + ',' + return methodArray.map(n => ' ' + n).join(',\n') + ',' } function generateMethodDescribeBlock (methodName, index) { @@ -143,7 +147,7 @@ function generateMethodDescribeBlock (methodName, index) { })` return describeBlock } - +*/ function generateDispatchMethodDescribeBlock (methodName, index) { const describeBlock = `${index ? ' ' : ''}describe('${methodName}()', () => { @@ -154,12 +158,13 @@ function generateDispatchMethodDescribeBlock (methodName, index) { })` return describeBlock } - +/* function generateMethodDescribeBlocks (methodArray) { return methodArray .map((methodName, index) => generateMethodDescribeBlock(methodName, index)) .join('\n\n') } +*/ function generateDispatchMethodDescribeBlocks (methodArray) { return methodArray @@ -167,6 +172,7 @@ function generateDispatchMethodDescribeBlocks (methodArray) { .join('\n\n') } +/* function generateSelectorTest (name, methodArray) { return `import assert from 'assert' import { @@ -192,6 +198,7 @@ describe('${name.match(/^[^.]+/)} utils', () => { })` } +*/ function generateContainerTest (sPath, { mapStateToPropsAssertionObject, @@ -231,4 +238,4 @@ describe('${sPath.match(/^[^.]+/)} container', () => { }) })` -} \ No newline at end of file +} diff --git a/gulpfile.js b/gulpfile.js index 4dca7089f..480f544d8 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -13,27 +13,21 @@ const zip = require('gulp-zip') const assign = require('lodash.assign') const livereload = require('gulp-livereload') const del = require('del') -const eslint = require('gulp-eslint') const fs = require('fs') const path = require('path') const manifest = require('./app/manifest.json') -const replace = require('gulp-replace') const mkdirp = require('mkdirp') -const asyncEach = require('async/each') -const exec = require('child_process').exec const sass = require('gulp-sass') const autoprefixer = require('gulp-autoprefixer') const gulpStylelint = require('gulp-stylelint') const stylefmt = require('gulp-stylefmt') const uglify = require('gulp-uglify-es').default -const babel = require('gulp-babel') -const debug = require('gulp-debug') const pify = require('pify') const gulpMultiProcess = require('gulp-multi-process') const endOfStream = pify(require('end-of-stream')) function gulpParallel (...args) { - return function spawnGulpChildProcess(cb) { + return function spawnGulpChildProcess (cb) { return gulpMultiProcess(args, cb, true) } } @@ -48,12 +42,12 @@ const commonPlatforms = [ // browser webapp 'mascara', // browser extensions - ...browserPlatforms + ...browserPlatforms, ] // browser reload -gulp.task('dev:reload', function() { +gulp.task('dev:reload', function () { livereload.listen({ port: 35729, }) @@ -108,7 +102,7 @@ createCopyTasks('html:mascara', { destinations: [`./dist/mascara/`], }) -function createCopyTasks(label, opts) { +function createCopyTasks (label, opts) { if (!opts.devOnly) { const copyTaskName = `copy:${label}` copyTask(copyTaskName, opts) @@ -119,7 +113,7 @@ function createCopyTasks(label, opts) { copyDevTaskNames.push(copyDevTaskName) } -function copyTask(taskName, opts){ +function copyTask (taskName, opts) { const source = opts.source const destination = opts.destination const destinations = opts.destinations || [destination] @@ -137,12 +131,12 @@ function copyTask(taskName, opts){ return performCopy() }) - function performCopy() { + function performCopy () { // stream from source let stream = gulp.src(source + pattern, { base: source }) // copy to destinations - destinations.forEach(function(destination) { + destinations.forEach(function (destination) { stream = stream.pipe(gulp.dest(destination)) }) @@ -152,40 +146,40 @@ function copyTask(taskName, opts){ // manifest tinkering -gulp.task('manifest:chrome', function() { +gulp.task('manifest:chrome', function () { return gulp.src('./dist/chrome/manifest.json') - .pipe(jsoneditor(function(json) { + .pipe(jsoneditor(function (json) { delete json.applications return json })) .pipe(gulp.dest('./dist/chrome', { overwrite: true })) }) -gulp.task('manifest:opera', function() { +gulp.task('manifest:opera', function () { return gulp.src('./dist/opera/manifest.json') - .pipe(jsoneditor(function(json) { + .pipe(jsoneditor(function (json) { json.permissions = [ - "storage", - "tabs", - "clipboardWrite", - "clipboardRead", - "http://localhost:8545/" + 'storage', + 'tabs', + 'clipboardWrite', + 'clipboardRead', + 'http://localhost:8545/', ] return json })) .pipe(gulp.dest('./dist/opera', { overwrite: true })) }) -gulp.task('manifest:production', function() { +gulp.task('manifest:production', function () { return gulp.src([ './dist/firefox/manifest.json', './dist/chrome/manifest.json', './dist/edge/manifest.json', './dist/opera/manifest.json', - ],{base: './dist/'}) + ], {base: './dist/'}) // Exclude chromereload script in production: - .pipe(jsoneditor(function(json) { + .pipe(jsoneditor(function (json) { json.background.scripts = json.background.scripts.filter((script) => { return !script.includes('chromereload') }) @@ -212,29 +206,6 @@ gulp.task('dev:copy', ) ) -// lint js - -const lintTargets = ['app/**/*.json', 'app/**/*.js', '!app/scripts/vendor/**/*.js', 'ui/**/*.js', 'old-ui/**/*.js', 'mascara/src/*.js', 'mascara/server/*.js', '!node_modules/**', '!dist/firefox/**', '!docs/**', '!app/scripts/chromereload.js', '!mascara/test/jquery-3.1.0.min.js'] - -gulp.task('lint', function () { - // Ignoring node_modules, dist/firefox, and docs folders: - return gulp.src(lintTargets) - .pipe(eslint(fs.readFileSync(path.join(__dirname, '.eslintrc')))) - // eslint.format() outputs the lint results to the console. - // Alternatively use eslint.formatEach() (see Docs). - .pipe(eslint.format()) - // To have the process exit with an error code (1) on - // lint error, return the stream and pipe to failAfterError last. - .pipe(eslint.failAfterError()) -}); - -gulp.task('lint:fix', function () { - return gulp.src(lintTargets) - .pipe(eslint(Object.assign(fs.readFileSync(path.join(__dirname, '.eslintrc')), {fix: true}))) - .pipe(eslint.format()) - .pipe(eslint.failAfterError()) -}); - // scss compilation and autoprefixing tasks gulp.task('build:scss', createScssBuildTask({ @@ -250,7 +221,7 @@ gulp.task('dev:scss', createScssBuildTask({ pattern: 'ui/app/**/*.scss', })) -function createScssBuildTask({ src, dest, devMode, pattern }) { +function createScssBuildTask ({ src, dest, devMode, pattern }) { return function () { if (devMode) { watch(pattern, async (event) => { @@ -262,7 +233,7 @@ function createScssBuildTask({ src, dest, devMode, pattern }) { return buildScss() } - function buildScss() { + function buildScss () { return gulp.src(src) .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) @@ -272,22 +243,22 @@ function createScssBuildTask({ src, dest, devMode, pattern }) { } } -gulp.task('lint-scss', function() { +gulp.task('lint-scss', function () { return gulp .src('ui/app/css/itcss/**/*.scss') .pipe(gulpStylelint({ reporters: [ - { formatter: 'string', console: true } + { formatter: 'string', console: true }, ], fix: true, - })); -}); + })) +}) gulp.task('fmt-scss', function () { return gulp.src('ui/app/css/itcss/**/*.scss') .pipe(stylefmt()) - .pipe(gulp.dest('ui/app/css/itcss')); -}); + .pipe(gulp.dest('ui/app/css/itcss')) +}) // build js @@ -300,11 +271,11 @@ const buildJsFiles = [ // bundle tasks createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'dev:extension:js', devMode: true }) -createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'build:extension:js' }) +createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'build:extension:js' }) createTasksForBuildJsMascara({ taskPrefix: 'build:mascara:js' }) createTasksForBuildJsMascara({ taskPrefix: 'dev:mascara:js', devMode: true }) -function createTasksForBuildJsExtension({ buildJsFiles, taskPrefix, devMode, bundleTaskOpts = {} }) { +function createTasksForBuildJsExtension ({ buildJsFiles, taskPrefix, devMode, bundleTaskOpts = {} }) { // inpage must be built before all other scripts: const rootDir = './app/scripts' const nonInpageFiles = buildJsFiles.filter(file => file !== 'inpage') @@ -322,7 +293,7 @@ function createTasksForBuildJsExtension({ buildJsFiles, taskPrefix, devMode, bun createTasksForBuildJs({ rootDir, taskPrefix, bundleTaskOpts, destinations, buildPhase1, buildPhase2 }) } -function createTasksForBuildJsMascara({ taskPrefix, devMode, bundleTaskOpts = {} }) { +function createTasksForBuildJsMascara ({ taskPrefix, devMode, bundleTaskOpts = {} }) { // inpage must be built before all other scripts: const rootDir = './mascara/src/' const buildPhase1 = ['ui', 'proxy', 'background', 'metamascara'] @@ -338,7 +309,7 @@ function createTasksForBuildJsMascara({ taskPrefix, devMode, bundleTaskOpts = {} createTasksForBuildJs({ rootDir, taskPrefix, bundleTaskOpts, destinations, buildPhase1 }) } -function createTasksForBuildJs({ rootDir, taskPrefix, bundleTaskOpts, destinations, buildPhase1 = [], buildPhase2 = [] }) { +function createTasksForBuildJs ({ rootDir, taskPrefix, bundleTaskOpts, destinations, buildPhase1 = [], buildPhase2 = [] }) { // bundle task for each file const jsFiles = [].concat(buildPhase1, buildPhase2) jsFiles.forEach((jsFile) => { @@ -367,7 +338,7 @@ gulp.task('disc', gulp.parallel(buildJsFiles.map(jsFile => `disc:${jsFile}`))) // clean dist -gulp.task('clean', function clean() { +gulp.task('clean', function clean () { return del(['./dist/*']) }) @@ -460,7 +431,7 @@ gulp.task('dist', // task generators -function zipTask(target) { +function zipTask (target) { return () => { return gulp.src(`dist/${target}/**`) .pipe(zip(`metamask-${target}-${manifest.version}.zip`)) @@ -468,7 +439,7 @@ function zipTask(target) { } } -function generateBundler(opts, performBundle) { +function generateBundler (opts, performBundle) { const browserifyOpts = assign({}, watchify.args, { entries: [opts.filepath], plugin: 'browserify-derequire', @@ -497,7 +468,7 @@ function generateBundler(opts, performBundle) { return bundler } -function discTask(opts) { +function discTask (opts) { opts = Object.assign({ buildWithFullPaths: true, }, opts) @@ -508,7 +479,7 @@ function discTask(opts) { return performBundle - function performBundle(){ + function performBundle () { // start "disc" build const discDir = path.join(__dirname, 'disc') mkdirp.sync(discDir) @@ -523,14 +494,14 @@ function discTask(opts) { } -function bundleTask(opts) { +function bundleTask (opts) { const bundler = generateBundler(opts, performBundle) // output build logs to terminal bundler.on('log', gutil.log) return performBundle - function performBundle(){ + function performBundle () { let buildStream = bundler.bundle() // handle errors @@ -562,7 +533,7 @@ function bundleTask(opts) { buildStream = buildStream .pipe(uglify({ mangle: { - reserved: [ 'MetamaskInpageProvider' ] + reserved: [ 'MetamaskInpageProvider' ], }, })) } diff --git a/mascara/example/app.js b/mascara/example/app.js index 598e2c84c..7b6421fdc 100644 --- a/mascara/example/app.js +++ b/mascara/example/app.js @@ -3,7 +3,7 @@ const EthQuery = require('ethjs-query') window.addEventListener('load', loadProvider) window.addEventListener('message', console.warn) -async function loadProvider() { +async function loadProvider () { const ethereumProvider = window.metamask.createDefaultProvider({ host: 'http://localhost:9001' }) const ethQuery = new EthQuery(ethereumProvider) const accounts = await ethQuery.accounts() @@ -13,7 +13,7 @@ async function loadProvider() { } -function logToDom(message, context){ +function logToDom (message, context) { document.getElementById(context).innerText = message console.log(message) } @@ -35,4 +35,4 @@ function setupButtons (ethQuery) { }) logToDom(txHash, 'cb-value') }) -} \ No newline at end of file +} diff --git a/mascara/example/server.js b/mascara/example/server.js index d39c19600..bdb1efa16 100644 --- a/mascara/example/server.js +++ b/mascara/example/server.js @@ -1,8 +1,8 @@ const express = require('express') +const path = require('path') const createMetamascaraServer = require('../server/') const createBundle = require('../server/util').createBundle const serveBundle = require('../server/util').serveBundle - // // Iframe Server // @@ -23,7 +23,7 @@ const dappServer = express() // serve dapp bundle serveBundle(dappServer, '/app.js', createBundle(require.resolve('./app.js'))) -dappServer.use(express.static(__dirname + '/app/')) +dappServer.use(express.static(path.join(__dirname, '/app/'))) // start the server const dappPort = '9002' diff --git a/mascara/src/app/first-time/breadcrumbs.js b/mascara/src/app/first-time/breadcrumbs.js index b81a9fb9b..d86e10d48 100644 --- a/mascara/src/app/first-time/breadcrumbs.js +++ b/mascara/src/app/first-time/breadcrumbs.js @@ -8,7 +8,7 @@ export default class Breadcrumbs extends Component { currentIndex: PropTypes.number, }; - render() { + render () { const {total, currentIndex} = this.props return (
@@ -20,7 +20,7 @@ export default class Breadcrumbs extends Component { /> ))}
- ); + ) } } diff --git a/mascara/src/app/first-time/buy-ether-screen.js b/mascara/src/app/first-time/buy-ether-screen.js index c5a560638..e270392e1 100644 --- a/mascara/src/app/first-time/buy-ether-screen.js +++ b/mascara/src/app/first-time/buy-ether-screen.js @@ -54,7 +54,7 @@ class BuyEtherScreen extends Component { return (
showAccountDetail(address)} > Do it later @@ -64,17 +64,17 @@ class BuyEtherScreen extends Component { renderCoinbaseLogo () { return ( - - - - - - - - - - - + + + + + + + + + + + @@ -85,13 +85,13 @@ class BuyEtherScreen extends Component { const {goToCoinbase, address} = this.props return ( -
+
{this.renderCoinbaseLogo()}
-
Coinbase is the world’s most popular way to buy and sell bitcoin, ethereum, and litecoin.
- What is Ethereum? -
+
Coinbase is the world’s most popular way to buy and sell bitcoin, ethereum, and litecoin.
+ What is Ethereum? +