Extension may declare client lib to add alias into requireJs

@author Lionel Lecaque, lionel@taotesting.com
964126
public function registerClientLib()
    {
        $jsPath = trim(Template::js('', $this->extension->getId()), '/');
        ClientLibRegistry::getRegistry()->register($this->extension->getId(), $jsPath);

        $cssPath = trim(Template::css('', $this->extension->getId()), '/');
        ClientLibRegistry::getRegistry()->register($this->extension->getId().'Css', $cssPath);
    }
40636
function (options, callback) {
        options = extend({}, DEPENDENCY_WRITE_DEFAULTS, options)
        var json = require(options.jsonUri)

        // the JSON DSL has the option to have "/foo" in <moduleNameLeft>
        after.reduce(json, createFoldersIntoFilesIterator(options.uri), 
            {}, runDependencyMapper)

        function runDependencyMapper(err, data) {
            if (err) {
                return callback(err)
            }
            after.map(data, mapToDependencies, callback)
        }

        function mapToDependencies(dependencies, moduleName, callback) {
            if (isFile.test(moduleName)) {
                // the JSON DSL has the option to have "/foo" or ["/foo"]
                // in <moduleNameRight>.
                after.map(dependencies, createConvertToProxyNameIterator({
                    moduleName: moduleName,
                    uri: options.uri
                }), callback)
            }
        }
    }
44179
function _require(dependency) {
        let result;
        try {
            result = require(path.join('ng-apimock', 'node_modules', dependency));
        } catch (ex) {
            result = require(dependency)
        }
        return result;
    }
150537
function require_override(p){
  
  function createXMLHttp() {
    if (typeof XMLHttpRequest != 'undefined') {
      return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
      for (var i = avers.length -1; i >= 0; i--) {
        try {
          httpObj = new ActiveXObject(avers[i]);
          return httpObj;
        } catch(e) {}
      }
    }
    throw new Error('XMLHttp (AJAX) not supported');
  }

  var ajaxObj = createXMLHttp();
  
  var path = require.resolve(p)
    , mod = require.modules[path];
  if (!mod) {
    var exports;
    
    var ajaxObj = createXMLHttp();
    ajaxObj.open('GET', path + '.js', false);
    ajaxObj.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        exports = {};
        (new Function('exports', this.responseText))(exports);
        require.modules[path + '.js'] = { exports: exports };
      }
    };
    ajaxObj.send();

    if (exports != null) {
      return exports;
    }
    throw new Error('failed to require "' + p + '"');
  }
  if (!mod.exports) {
    mod.exports = {};
    mod.call(mod.exports, mod, mod.exports, require.relative(path));
  }
  return mod.exports;
}
357452
function rewrite_extension(source, ext) {
  var source_ext = path.extname(source);
  return (source_ext === ext) ? source : (source + ext);
}
429764
function (dependencies, extension) {
            if (dependencies) {
                for (var i = dependencies.length - 1; i >= 0; i--) {
                    this.addDependency(dependencies[i], extension);
                }
            }
        }
399418
function makeRequire(id, path) {
  var expr = callExpression(identifier('require'), [literal(path)]);
  return makeDeclaration(id, expr);
}
62616
function requirePackage(pkg, mainjs) {
			var processed = {};
			var pkgName = path.basename(pkg);
			var code = grunt.file.read(mainjs);
			while (true) {
				var requires = detective(code);
				if (!requires.length) break;
				for (var requireIdx in requires) {
					var name = requires[requireIdx];
					var requiredCode = '';
					if (!processed[name]) {
						var filepath = path.join(pkg, 'lib', name.replace(pkgName + '/', '') + '.js');
						requiredCode = grunt.file.read(filepath);
						processed[name] = true;
					}
					code = code.replace(new RegExp('require\\([\\\'\"]' + name + '[\\\'\"]\\);?'), requiredCode);
				}
			}
			return code;
		}
884074
function patchRequire(require) {
        if (require.patched) {
            return require;
        }
        function fromPackageJson(module, dir) {
            var pkgPath, pkgContents, pkg;
            pkgPath = fs.pathJoin(dir, module, 'package.json');
            if (!fs.exists(pkgPath)) {
                return;
            }
            pkgContents = fs.read(pkgPath);
            if (!pkgContents) {
                return;
            }
            try {
                pkg = JSON.parse(pkgContents);
            } catch (e) {
                return;
            }
            if (typeof pkg === "object" && pkg.main) {
                return fs.absolute(fs.pathJoin(dir, module, pkg.main));
            }
        }
        function resolveFile(path, dir) {
            var extensions = ['js', 'coffee', 'json'];
            var basenames = [path, path + '/index'];
            var paths = [];
            var nodejsScript = fromPackageJson(path, dir);
            if (nodejsScript) {
                return nodejsScript;
            }
            basenames.forEach(function(basename) {
                paths.push(fs.absolute(fs.pathJoin(dir, basename)));
                extensions.forEach(function(extension) {
                    paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
                });
            });
            for (var i = 0; i < paths.length; i++) {
                if (fs.isFile(paths[i])) {
                    return paths[i];
                }
            }
            return null;
        }
        function getCurrentScriptRoot() {
            if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                return phantom.casperScriptBaseDir;
            }
            return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
        }
        function casperBuiltinPath(path) {
            return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
        }
        function nodeModulePath(path) {
            var resolved, prevBaseDir;
            var baseDir = getCurrentScriptRoot();
            do {
                resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
                prevBaseDir = baseDir;
                baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
            } while (!resolved && baseDir !== '/' && prevBaseDir !== '/' && baseDir !== prevBaseDir);
            return resolved;
        }
        function localModulePath(path) {
            return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
        }
        var patchedRequire = function patchedRequire(path) {
            try {
                return require(casperBuiltinPath(path) ||
                               nodeModulePath(path)    ||
                               localModulePath(path)   ||
                               path);
            } catch (e) {
                throw new CasperError("Can't find module " + path);
            }
        };
        patchedRequire.cache = require.cache;
        patchedRequire.extensions = require.extensions;
        patchedRequire.stubs = require.stubs;
        patchedRequire.patched = true;
        return patchedRequire;
    }
772631
function (beyond, name) {
        "use strict";
    
        Object.defineProperty(this, 'name', {
            'get': function () {
                return name;
            }
        });
    
        Object.defineProperty(this, 'version', {
            'get': function () {
                return beyond.hosts.libraries[name].version;
            }
        });
    
        Object.defineProperty(this, 'path', {
            'get': function () {
                return 'libraries/' + name;
            }
        });
    
        var host = beyond.hosts.libraries[name].ws;
        if (host) {
            exportSocket(this, beyond, host);
        }
    
    }
698823
function moduleSize(id, paths) {
    var path = id;
    var extension = '.js';
    // Use `paths:` to resolve an alias.
    if (paths[id]) {
        path = paths[id];
    }
    // Does the dependency reference a plugin?
    if (path.indexOf('!') !== -1) {
        // Split into plugin and path.
        var pathParts = path.split('!');
        // Often, the plugin maps to the extension it handles.
        extension = '.' + pathParts[0];
        path = pathParts[1];
    }
    // Try to get the file at the path.
    var stats;
    try {
        stats = fs.statSync(path);
        return stats['size'];
    }
    catch(e) {}

    // Didn't find it? Let's try again with the extension added.
    if (path.slice(-extension.length) !== extension) {
        path = path + extension;
    }
    try {
        stats = fs.statSync(path);
        return stats['size'];
    }
    catch(e) {}

    // Still didn't find the file.
    return null;
}
779254
function () {
    var start = Date.now();
    bundler.bundle()
      .on('error', gutil.log)
      .pipe(source(options.name))
      .pipe(gulpif(options.uglify, streamify(uglify())))
      .pipe(gulp.dest(options.dest))
      .pipe(notify(function () {

        // Fix for requirejs
        var fs = require('fs');
        var file = fs.readFileSync(options.dest + '/' + options.name).toString();
        file = file.replace('define([],e)', 'define(["react"],e)');
        fs.writeFileSync(options.dest + '/' + options.name, file);

        console.log('Built in ' + (Date.now() - start) + 'ms');

      }));

  }
1346965
function (subTplName, callback) {
            var tpl = S.require(subTplName);
            if (tpl) {
                callback(undefined, tpl);
            } else {
                var warning = 'template "' + subTplName + '" does not exist, ' + 'better required or used first for performance!';
                S.log(warning, 'error');
                callback(warning, undefined);
            }
        }
330485
function compileJs(srcDir, srcFilename, destDir, options) {
  options = options || {};

  if (options.minify) {
    const startTime = Date.now();
    return closureCompile(
        srcDir + srcFilename + '.js', destDir, options.minifiedName, options)
        .then(function() {
          fs.writeFileSync(destDir + '/version.txt', internalRuntimeVersion);
          if (options.latestName) {
            fs.copySync(
                destDir + '/' + options.minifiedName,
                destDir + '/' + options.latestName);
          }
        })
        .then(() => {
          endBuildStep('Minified', srcFilename + '.js', startTime);
        });
  }

  var bundler = browserify(srcDir + srcFilename + '-babel.js', {debug: true})
      .transform(babel, {loose: 'all'});
  if (options.watch) {
    bundler = watchify(bundler);
  }

  var wrapper = options.wrapper || '<%= contents %>';

  var lazybuild = lazypipe()
      .pipe(source, srcFilename + '-babel.js')
      .pipe(buffer)
      .pipe($$.replace, /\$internalRuntimeVersion\$/g, internalRuntimeVersion)
      .pipe($$.wrap, wrapper)
      .pipe($$.sourcemaps.init.bind($$.sourcemaps), {loadMaps: true});

  var lazywrite = lazypipe()
      .pipe($$.sourcemaps.write.bind($$.sourcemaps), './')
      .pipe(gulp.dest.bind(gulp), destDir);

  var destFilename = options.toName || srcFilename + '.js';
  function rebundle() {
    const startTime = Date.now();
    return toPromise(bundler.bundle()
      .on('error', function(err) {
        if (err instanceof SyntaxError) {
          console.error($$.util.colors.red('Syntax error:', err.message));
        } else {
          console.error($$.util.colors.red(err.message));
        }
      })
      .pipe(lazybuild())
      .pipe($$.rename(destFilename))
      .pipe(lazywrite())
      .on('end', function() {
      })).then(() => {
        endBuildStep('Compiled', srcFilename, startTime);
      });
  }

  if (options.watch) {
    bundler.on('update', function() {
      rebundle();
      // Touch file in unit test set. This triggers rebundling of tests because
      // karma only considers changes to tests files themselves re-bundle
      // worthy.
      touch('test/_init_tests.js');
    });
  }

  if (options.watch === false) {
    // Due to the two step build process, compileJs() is called twice, once with
    // options.watch set to true and, once with it set to false. However, we do
    // not need to call rebundle() twice. This avoids the duplicate compile seen
    // when you run `gulp watch` and touch a file.
    return Promise.resolve();
  } else {
    // This is the default options.watch === true case, and also covers the
    // `gulp build` / `gulp dist` cases where options.watch is undefined.
    return rebundle();
  }
}
1019916
function loadAliases(opts) {
        opts.preload = opts.preload || [];
        var preloadDirs = _.isArray(opts.preload) ? opts.preload : [opts.preload];
        preloadDirs.push(this.servicesDir);
        var aliases = _.extend({}, this.loadMappings(this.rootDir, preloadDirs), opts.serverAliases);

        // we also want to point the shorter adapter names to the same objects
        _.each(this.adapterMap, function (impl, type) {
            var fullName = utils.getCamelCase(impl + '.' + type + '.adapter');
            var shortName = utils.getPascalCase(type + '.adapter');
            if (aliases[fullName]) {
                aliases[shortName] = aliases[fullName];
            }
        });

        return aliases;
    }
23388
function hookExtensions(_exts) {
  _lodashCollectionEach2["default"](oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  _lodashCollectionEach2["default"](_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
}
354991
async function onEveryExtensionLoad() {
  new StudyLifeCycleHandler();

  const studySetup = await getStudySetup();
  await browser.study.logger.log(["Study setup: ", studySetup]);
  await browser.study.setup(studySetup);
}