An AngularJS source code loader and analyser middleware.

@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack.
194764
function AnalyzeSourceCodeMiddleware (context)
{
  var grunt = context.grunt;

  //--------------------------------------------------------------------------------------------------------------------
  // PUBLIC API
  //--------------------------------------------------------------------------------------------------------------------

  this.analyze = function (filesArray)
  {
    var src = util.sortFilesBeforeSubfolders (filesArray.src);

    // Load the script files and scan them for module definitions.
    src.forEach (function (path)
    {

      if (!grunt.file.exists (path)) {
        warn ('Source file "' + path + '" not found.');
        return;
      }
      // Read the script and scan it for module declarations.
      var script = grunt.file.read (path);
      /** @type {ModuleHeaderInfo[]} */
      var moduleHeaders;
      try {
        moduleHeaders = sourceExtract.extractModuleHeaders (script);
      }
      catch (e) {
        if (typeof e === 'string')
          return warn (e + NL + reportErrorLocation (path));
        throw e;
      }

      // Ignore irrelevant files.
      if (!moduleHeaders.length) {
        if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) {
          info ('Ignored file: %', path.cyan);
          return;
        }
        context.standaloneScripts.push ({
          path:    path,
          content: script
        });
      }
      else moduleHeaders.forEach (function (header)
      {
        setupModuleInfo (header, script, path);
      });
    });

  };

  this.trace = function (module)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  this.build = function (targetScript)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  //--------------------------------------------------------------------------------------------------------------------
  // PRIVATE
  //--------------------------------------------------------------------------------------------------------------------

  /**
   * Store information about the specified module retrieved from the given source code on the specified file.
   *
   * @param {ModuleHeaderInfo} moduleHeader
   * @param {string} fileContent
   * @param {string} filePath
   */
  function setupModuleInfo (moduleHeader, fileContent, filePath)
  {
    // Get information about the specified module.
    var module = context.modules[moduleHeader.name];
    // If this is the first time a specific module is mentioned, create the respective information record.
    if (!module)
      module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name);
    // Skip the file if it defines an external module.
    else if (module.external)
      return;
    // Reject additional attempts to redeclare a module (only appending is allowed).
    else if (module.head && !moduleHeader.append)
      fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name);
    // The file is appending definitions to a module declared elsewhere.
    if (moduleHeader.append) {
      // Append the file path to the paths list.
      if (!~module.bodyPaths.indexOf (filePath)) {
        module.bodies.push (fileContent);
        module.bodyPaths.push (filePath);
      }
    }
    // Otherwise, the file contains a module declaration.
    else {
      if (module.head)
        fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name);
      module.head = fileContent;
      module.headPath = filePath;
      module.requires = moduleHeader.requires;
    }
    module.configFn = moduleHeader.configFn;
  }

}
423331
function(context, args, stack) {
		var ctx = new Context(args[0], args[1] || context);
		stack.push(ctx);
		return ctx;
	}
1220063
function(context, pkg){
		var deps = crawl.getDependencyMap(context.loader, pkg, true);

		var pluginsPromise = crawl.loadPlugins(context, pkg, true, deps, true);
		var stealPromise = crawl.loadSteal(context, pkg, true, deps);

		return Promise.all([pluginsPromise, stealPromise]);
	}
1344159
function resolveContext (emitter, context, storageKey) {
  // TODO: clean up - try to use internal context resolve more on no
  // use the one from on (resolve)
  // figure out why we cant use resolveContextSet since thats what it is
  if (context) {
    // this is lame stuff! should be in observable in some way...
    let base = emitter.parent.parent
    let type = emitter.key
    let setObj = { on: {} }
    setObj.on[type] = {}
    // base = base.set(setObj) // .on[type]
    emitter = (base.set(setObj) || base)._on[type]
  }
  if (!emitter.hasOwnProperty(storageKey)) {
    emitter.setKey(storageKey, {}, false)
  }
  return emitter
}
956602
function create(context) {
    return {
        CallExpression(node) {
            if (isRequireCall(node) && ancestor(isConditional, node)) {
                context.report(node, message);
            }
        }
    };
}
1323560
function BuildAssetsMiddleware (context)
{
  var grunt = context.grunt
    , options = context.options.assets;

  /**
   * Records which files have been already exported.
   * Prevents duplicate asset exports.
   * It's a map of absolute file names to boolean `true`.
   * @type {Object.<string,boolean>}
   */
  var exportedAssets = {};

  //--------------------------------------------------------------------------------------------------------------------
  // PUBLIC API
  //--------------------------------------------------------------------------------------------------------------------

  this.analyze = function (filesArray)
  {
    /* jshint unused: vars */
    // Do nothing
  };

  this.trace = function (module)
  {
    /* jshint unused: vars */
    // Do nothing.
  };

  this.build = function (targetScript)
  {
    if (!options.enabled) return;
    // Import file paths.
    var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty);
    if (!stylehseets) return; // No stylesheet sources are configured.
    var targetPath = path.dirname (targetScript);
    stylehseets.forEach (function (filePath)
    {
      var src = grunt.file.read (filePath);
      scan (path.dirname (filePath), targetPath, src);
    });

  };

  //--------------------------------------------------------------------------------------------------------------------
  // PRIVATE
  //--------------------------------------------------------------------------------------------------------------------

  /**
   * Scans a stylesheet for asset URL references and copies the assets to the build folder.
   * @private
   * @param {string} basePath
   * @param {string} targetPath
   * @param {string} sourceCode
   */
  function scan (basePath, targetPath, sourceCode)
  {
    var match;
    while ((match = MATCH_URLS.exec (sourceCode))) {
      var url = match[2];
      if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs
        var absSrcPath = path.resolve (basePath, url)
          , absDestPath = path.resolve (targetPath, options.targetDir, url)
          , relDestPath = path.relative (targetPath, absDestPath);
        if (relDestPath[0] === '.')
          return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL);
        if (exportedAssets[absDestPath]) // skip already exported asset
          continue;
        else exportedAssets[absDestPath] = true;
        var absTargetFolder = path.dirname (absDestPath);
        grunt.file.mkdir (absTargetFolder);
        if (options.symlink)
          fs.symlinkSync (absSrcPath, absDestPath);
        else grunt.file.copy (absSrcPath, absDestPath);
      }
    }
  }

}
442414
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030):
    
    try:
        from watchdog.observers import Observer
    except ImportError:
        context.pip_command('install', 'watchdog>0.8,<0.9')
        from watchdog.observers import Observer

    from watchdog.events import PatternMatchingEventHandler

    class RebuildHandler(PatternMatchingEventHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self._patterns = ['*.js', '*.scss', '*.html']
            self._ignore_directories = True
            self.builder = None
            self.rebuild_javascript = threading.Event()
            self.rebuild_stylesheets = threading.Event()

        def on_any_event(self, event):
            if self.builder:
                self.builder.cancel()
            extension = event.src_path.rsplit('.', 1)[-1].lower()
            if extension == 'js':
                self.rebuild_javascript.set()
            elif extension == 'scss':
                self.rebuild_stylesheets.set()
            self.builder = threading.Timer(3, self.rebuild)
            self.builder.start()

        def rebuild(self):
            if self.rebuild_javascript.is_set():
                self.rebuild_javascript.clear()
                context.debug('Triggering javascript build')
                bundle_javascript(context)
            if self.rebuild_stylesheets.is_set():
                self.rebuild_stylesheets.clear()
                context.debug('Triggering stylesheet build')
                bundle_stylesheets(context)
            context.debug('Reloading browsers')
            context.node_tool('browser-sync', 'reload', '--port=%s' % browsersync_port)

    context.info('Watching sources')
    observer = Observer()
    paths = [
        context.app.common_asset_source_path,
        context.app.asset_source_path,
        context.app.common_templates_path,
        context.app.templates_path,
    ]
    handler = RebuildHandler()
    for path in paths:
        observer.schedule(handler, path, recursive=True)
    observer.setDaemon(True)
    observer.start()

    context.info('Starting browser sync')
    browsersync_args = ['start', '--host=localhost', '--no-open',
                        '--logLevel', {0: 'silent', 1: 'info', 2: 'debug'}[context.verbosity],
                        '--port=%s' % browsersync_port, '--proxy=localhost:%s' % port,
                        '--ui-port=%s' % browsersync_ui_port]
    browsersync = functools.partial(context.node_tool, 'browser-sync', *browsersync_args)
    threading.Thread(target=browsersync, daemon=True).start()

    context.info('Starting web server')
    return start(context, port=port)
986994
function (context) {
		var file = context.file;

		try {
			var ast = parser.parse(file.data);

			ast = uglify.ast_mangle(ast, {
				except: [ 'require' ]
			});
			ast = uglify.ast_squeeze(ast);

			file.data = uglify.gen_code(ast) + ';';
		} catch (err) {
			context.error('JS syntax error: "%s" (line %s, col %s)',
				file.pathname, err.line, err.col);
			file.data += ';'
		}
	}
1079149
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
    }
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? web3VM : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else if (id === '237') name = 'DEXON'
        else if (id === '238') name = 'DEXON Testnet'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    if (name && this.customNetWorks[name]) {
      delete this.customNetWorks[name]
      self.event.trigger('removeProvider', [name])
    }
  }

  this.addProvider = function (network) {
    if (network && network.name && network.url) {
      this.customNetWorks[network.name] = network
      self.event.trigger('addProvider', [network])
    }
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vm.stateManager.revert(function () {
        vm.stateManager.checkpoint()
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/dexon-foundation/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}
1369782
function runScriptViaModuleLoader(script, context) {
    if(!fs.existsSync(script.fullPath)) {
        events.emit('warn', 'Script file does\'t exist and will be skipped: ' + script.fullPath);
        return Q();
    }
    var scriptFn = require(script.fullPath);
    context.scriptLocation = script.fullPath;
    context.opts.plugin = script.plugin;

    // We can't run script if it is a plain Node script - it will run its commands when we require it.
    // This is not a desired case as we want to pass context, but added for compatibility.
    if (scriptFn instanceof Function) {
        // If hook is async it can return promise instance and we will handle it.
        return Q(scriptFn(context));
    } else {
        return Q();
    }
}
815806
function _createContext(context) {
  let newContext = context || _defaultContext
  if (_isString(newContext) || _isArray(newContext)) {
    newContext = {
      any: _arrayify(newContext),
    }
  } else {
    newContext = _arrayizeContext(context)
  }
  return newContext
}
252416
function create(context) {
    return {
        ReturnStatement(node) {
            if (isCommonJsWrapper(nearestFunction(node).parent)) {
                context.report(node, message);
            }
        }
    };
}
983757
function (subtype, context, done) {
    var types = this.types
      , loaded = {};
    this.allExtensions(function (type, id, plugin, next) {
      if (!plugin[subtype]) return next();
      if ('string' === typeof plugin[subtype]) {
        try {
          plugin[subtype] = require(path.resolve(path.join(plugin.dir, plugin[subtype])));
        } catch (e) {
          // eslint-disable-next-line no-console
          console.log('failed to load plugin', id, e.message, e.stack);
          e.message += '; error loading plugin ' + id;
          return next(e);
        }
      }

      if (!loaded[type]) loaded[type] = {};
      if (!types[type][subtype]) {
        loaded[type][id] = plugin[subtype];
        return next();
      }
      types[type][subtype](id, plugin[subtype], plugin, context, function (err, initialized) {
        loaded[type][id] = initialized;
        next(err);
      });
    }, function (err) {
      done(err, loaded);
    });
  }
340207
function create(context) {
    return {
        AssignmentExpression(node) {
            if (assignsToExportsProperty(node) && ancestor(isCommonJsWrapper, node)) {
                context.report(node, messages);
            }
        }
    };
}
41903
function processResult(loaderContext, resultPromise) {
  const { callback } = loaderContext;

  resultPromise
    .then(
      ({ css, map, imports }) => {
        imports.forEach(loaderContext.addDependency, loaderContext);
        return {
          // Removing the sourceMappingURL comment.
          // See removeSourceMappingUrl.js for the reasoning behind this.
          css: removeSourceMappingUrl(css),
          map: typeof map === 'string' ? JSON.parse(map) : map,
        };
      },
      (lessError) => {
        if (lessError.filename) {
          loaderContext.addDependency(lessError.filename);
        }
        throw formatLessError(lessError);
      }
    )
    .then(({ css, map }) => {
      callback(null, css, map);
    }, callback);
}
581307
function create(context) {
    return {
        CallExpression(node) {
            if (isRequireCall(node) && !isValidRequire(node)) {
                context.report(node, message);
            }
        }
    };
}
1143787
function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}