[
  {
    "path": ".editorconfig",
    "content": "; top-most EditorConfig file\nroot = true\n\n; Unix-style newlines\n[*]\nend_of_line = LF\n\n[*.php]\nindent_style = space\nindent_size = 4\n"
  },
  {
    "path": ".gitignore",
    "content": "vendor\n.idea\nnbproject\n.project\ncomposer.phar\ncomposer.lock"
  },
  {
    "path": ".travis.yml",
    "content": "language: php\n\nphp:\n  - 5.6\n  - 7.0\n  - hhvm\n\nbefore_script: composer install\nscript: composer test\n\nnotifications:\n    email: false\n"
  },
  {
    "path": "LICENSE.md",
    "content": "# License\n\nComponent Installer is released under the MIT License:\n\n> Copyright (C) 2015 [Rob Loach](http://robloach.net)\n>\n> Permission is hereby granted, free of charge, to any person obtaining\n> a copy of this software and associated documentation files (the\n> \"Software\"), to deal in the Software without restriction, including\n> without limitation the rights to use, copy, modify, merge, publish,\n> distribute, sublicense, and/or sell copies of the Software, and to\n> permit persons to whom the Software is furnished to do so, subject to\n> the following conditions:\n>\n> The above copyright notice and this permission notice shall be\n> included in all copies or substantial portions of the Software.\n>\n> THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# DEPRECATED\n\nComponent Installer has been deprecated. Use one of the following projects instead:\n- [Composer Installers Extender](https://github.com/oomphinc/composer-installers-extender)\n- [Asset Packagist](https://asset-packagist.org)\n- [Composer Asset Plugin](https://github.com/fxpio/composer-asset-plugin)\n- [Laravel Mix](https://laravel.com/docs/5.8/mix) (Example: [eventum/eventum#801](https://github.com/eventum/eventum/pull/801) and  [eventum/eventum#812](https://github.com/eventum/eventum/pull/812))\n\n## Example\n\n```\ncomposer require oomphinc/composer-installers-extender\n```\n\n```\n  \"extra\": {\n    \"installer-types\": [\"component\"],\n    \"installer-paths\": {\n      \"components/{$name}/\": [\"type:component\"]\n    }\n  }\n```\n\n# Component Installer for [Composer](http://getcomposer.org) [![Build Status](https://secure.travis-ci.org/RobLoach/component-installer.png?branch=master)](http://travis-ci.org/RobLoach/component-installer)\n\nAllows installation of Components via [Composer](http://getcomposer.org).\n\n## Install\n\n```\ncomposer require robloach/component-installer\n```\n\n``` json\n{\n    \"require\": {\n        \"robloach/component-installer\": \"*\"\n    }\n}\n```\n\n## Usage\n\nTo install a Component with Composer, add the Component to your *composer.json*\n`require` key. The following will install [jQuery](http://jquery.com) and\n[normalize.css](https://github.com/necolas/normalize.css):\n\n```\ncomposer require components/jquery\ncomposer require components/normalize.css\n```\n\n``` json\n{\n    \"require\": {\n        \"components/jquery\": \"2.*\",\n        \"components/normalize.css\": \"3.*\",\n        \"robloach/component-installer\": \"*\"\n    }\n}\n```\n\n### Using the Component\n\nThe easiest approach is to use the Component statically. Just reference the\nComponents manually using a `script` or `link` tag:\n\n``` html\n<script src=\"components/jquery/jquery.js\"></script>\n<link href=\"components/normalize/normalize.css\" rel=\"stylesheet\">\n```\n\nFor complex projects, a [RequireJS](http://requirejs.org) configuration is\navailable, which allows autoloading scripts only when needed. A *require.css*\nfile is also compiled, including all Component stylesheets:\n\n``` html\n<!DOCTYPE html>\n<html>\n    <head>\n        <link href=\"components/require.css\" rel=\"stylesheet\" type=\"text/css\">\n        <script src=\"components/require.js\"></script>\n    </head>\n    <body>\n        <h1>jQuery+RequireJS Component Installer Sample Page</h1>\n        <script>\n          require(['jquery'], function($) {\n            $('body').css('background-color', 'green');\n          });\n        </script>\n    </body>\n</html>\n```\n\n## Configuration\n\nThere are a number of ways to alter how Components are installed and used.\n\n### Installation Directory\n\nIt is possible to switch where Components are installed by changing the\n`component-dir` option in your root *composer.json*'s `config`. The following\nwill install jQuery to *public/jquery* rather than *components/jquery*:\n\n``` json\n{\n    \"require\": {\n        \"components/jquery\": \"*\"\n    },\n    \"config\": {\n        \"component-dir\": \"public\"\n    }\n}\n```\n\nDefaults to `components`.\n\n### Base URL\n\nWhile `component-dir` depicts where the Components will be installed,\n`component-baseurl` tells RequireJS the base path that will use when attempting\nto load the scripts in the web browser. It is important to make sure the\n`component-baseurl` points to the `component-dir` when loaded externally. See\nmore about [`baseUrl`](http://requirejs.org/docs/api.html#config-baseUrl) in the\nRequireJS documentation.\n\n``` json\n{\n    \"require\": {\n        \"components/jquery\": \"*\"\n    },\n    \"config\": {\n        \"component-dir\": \"public/assets\",\n        \"component-baseurl\": \"/assets\"\n    }\n}\n```\n\nDefaults to `components`.\n\n### Assetic filters\n\n``` json\n{\n    \"require\": {\n        \"components/jquery\": \"*\"\n    },\n    \"config\": {\n        \"component-dir\": \"public/assets\",\n        \"component-baseurl\": \"/assets\",\n        \"component-scriptFilters\": {\n            \"\\\\Assetic\\\\Filter\\\\GoogleClosure\\\\CompilerApiFilter\": []\n        },\n        \"component-styleFilters\": {\n            \"\\\\Assetic\\\\Filter\\\\CssImportFilter\": []\n        }\n    }\n}\n```\n\n## Creating a Component\n\nTo set up a Component to be installed with Component Installer, have it\n`require` the package *robloach/component-installer* and set the `type` to\n*component*, but it is not necessary:\n\n``` json\n{\n    \"name\": \"components/bootstrap\",\n    \"type\": \"component\",\n    \"require\": {\n        \"robloach/component-installer\": \"*\"\n    },\n    \"extra\": {\n        \"component\": {\n            \"scripts\": [\n                \"js/bootstrap.js\"\n            ],\n            \"styles\": [\n                \"css/bootstrap.css\"\n            ],\n            \"files\": [\n                \"img/*.png\",\n                \"js/bootstrap.min.js\",\n                \"css/bootstrap.min.css\"\n            ]\n        }\n    }\n}\n```\n\n* `scripts` - List of all the JavaScript files that will be concatenated\ntogether and processed when loading the Component.\n* `styles` - List of all the CSS files that should be concatenated together\ninto the final *require.css* file.\n* `files` - Any additional file assets that should be copied into the Component\ndirectory.\n\n### Component Name\n\nComponents can provide their own Component name. The following will install\njQuery to *components/myownjquery* rather than *components/jquery*:\n\n``` json\n{\n    \"name\": \"components/jquery\",\n    \"type\": \"component\",\n    \"extra\": {\n        \"component\": {\n            \"name\": \"myownjquery\"\n        }\n    }\n}\n```\n\nDefaults to the package name, without the vendor.\n\n### RequireJS Configuration\n\nComponents can alter how [RequireJS](http://requirejs.org) registers and\ninteracts with them by changing some of the [configuration\noptions](http://www.requirejs.org/docs/api.html#config):\n\n``` json\n{\n    \"name\": \"components/backbone\",\n    \"type\": \"component\",\n    \"require\": {\n        \"components/underscore\": \"*\"\n    },\n    \"extra\": {\n        \"component\": {\n            \"shim\": {\n                \"deps\": [\"underscore\", \"jquery\"],\n                \"exports\": \"Backbone\"\n            },\n            \"config\": {\n                \"color\": \"blue\"\n            }\n        }\n    },\n    \"config\": {\n        \"component\": {\n            \"waitSeconds\": 5\n        }\n    }\n}\n```\n\nCurrent available RequireJS options for individual packages include:\n* [`shim`](http://www.requirejs.org/docs/api.html#config-shim)\n* [`config`](http://www.requirejs.org/docs/api.html#config-moduleconfig)\n* Anything that's passed through `config.component` is sent to Require.js\n\n### Packages Without Composer Support\n\nUsing [`repositories`](http://getcomposer.org/doc/05-repositories.md#repositories)\nin *composer.json* allows use of Component Installer in packages that don't\nexplicitly provide their own *composer.json*. In the following example, we\ndefine use of [html5shiv](https://github.com/aFarkas/html5shiv):\n\n``` json\n{\n    \"require\": {\n        \"afarkas/html5shiv\": \"3.6.*\"\n    },\n    \"repositories\": [\n        {\n            \"type\": \"package\",\n            \"package\": {\n                \"name\": \"afarkas/html5shiv\",\n                \"type\": \"component\",\n                \"version\": \"3.6.2\",\n                \"dist\": {\n                    \"url\": \"https://github.com/aFarkas/html5shiv/archive/3.6.2.zip\",\n                    \"type\": \"zip\"\n                },\n                \"source\": {\n                    \"url\": \"https://github.com/aFarkas/html5shiv.git\",\n                    \"type\": \"git\",\n                    \"reference\": \"3.6.2\"\n                },\n                \"extra\": {\n                    \"component\": {\n                        \"scripts\": [\n                            \"dist/html5shiv.js\"\n                        ]\n                    }\n                },\n                \"require\": {\n                    \"robloach/component-installer\": \"*\"\n                }\n            }\n        }\n    ]\n}\n```\n\n### Packages Without Component Support In *composer.json*\n\nUsing [`extra`](https://getcomposer.org/doc/04-schema.md#extra)\nin *composer.json* allows use of Component Installer in packages that don't\nexplicitly provide support for component, but do ship with their own *composer.json*. \nUsing `extra` with packages that ship with Component Installer, will override component's settings for that package.\n\n``` json\n{\n    \"require\": {\n        \"datatables/datatables\": \"~1.10\"\n    },\n    \"extra\": {\n        \"component\": {\n            \"datatables/datatables\": {\n                \"scripts\": [\n                    \"media/js/jquery.dataTables.js\"\n                ],\n                \"styles\": [\n                    \"media/css/jquery.dataTables.css\"\n                ],\n                \"files\": [\n                    \"media/js/jquery.dataTables.min.js\",\n                    \"media/css/jquery.dataTables.min.css\",\n                    \"media/images/*.png\"\n                ]\n            }\n        }\n    }\n}\n```\n\n## Not Invented Here\n\nThere are many other amazing projects from which Component Installer was\ninspired. It is encouraged to take a look at some of the [other great package\nmanagement systems](http://github.com/wilmoore/frontend-packagers):\n* [npm](http://npmjs.org)\n* [bower](http://bower.io/)\n* [component](http://github.com/component/component)\n* [Jam](http://jamjs.org)\n* [volo](http://volojs.org)\n* [Ender](http://ender.jit.su)\n* etc\n\n## License\n\nComponent Installer is licensed under the MIT License - see LICENSE.md for\ndetails.\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"robloach/component-installer\",\n    \"description\": \"Allows installation of Components via Composer.\",\n    \"type\": \"composer-plugin\",\n    \"license\": \"MIT\",\n    \"authors\": [\n        {\n            \"name\": \"Rob Loach\",\n            \"homepage\": \"http://robloach.net\"\n        }\n    ],\n    \"autoload\": {\n        \"psr-0\": {\n            \"ComponentInstaller\": \"src/\"\n        }\n    },\n    \"extra\": {\n        \"branch-alias\": {\n            \"dev-master\": \"1.0.x-dev\"\n        },\n        \"class\": \"ComponentInstaller\\\\ComponentInstallerPlugin\"\n    },\n    \"require\": {\n        \"php\": \">=5.3.2\",\n        \"kriswallsmith/assetic\": \"1.*\",\n        \"composer-plugin-api\": \"^1.0\"\n    },\n    \"require-dev\": {\n        \"composer/composer\": \"~1.1.2\",\n        \"phpunit/phpunit\": \"~5.4.6\"\n    },\n    \"scripts\": {\n        \"test\": \"phpunit\"\n    },\n    \"archive\": {\n        \"exclude\": [\n            \"tests\",\n            \"phpunit.xml.dist\",\n            \".travis.yml\",\n            \".gitignore\",\n            \".editorconfig\"\n        ]\n    },\n    \"abandoned\": \"oomphinc/composer-installers-extender\"\n}\n"
  },
  {
    "path": "phpunit.xml.dist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<phpunit backupGlobals=\"false\"\n         backupStaticAttributes=\"false\"\n         colors=\"true\"\n         convertErrorsToExceptions=\"true\"\n         convertNoticesToExceptions=\"true\"\n         convertWarningsToExceptions=\"true\"\n         processIsolation=\"false\"\n         stopOnFailure=\"false\"\n         syntaxCheck=\"true\"\n         bootstrap=\"tests/bootstrap.php\"\n>\n    <testsuites>\n        <testsuite name=\"Component Installer Test Suite\">\n            <directory>tests/ComponentInstaller</directory>\n        </testsuite>\n    </testsuites>\n\n    <filter>\n        <whitelist>\n            <directory>src/ComponentInstaller</directory>\n        </whitelist>\n    </filter>\n</phpunit>\n"
  },
  {
    "path": "src/ComponentInstaller/ComponentInstallerPlugin.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller;\n\nuse Composer\\Composer;\nuse Composer\\IO\\IOInterface;\nuse Composer\\Plugin\\PluginInterface;\n\n/**\n * Composer Plugin to install Components.\n *\n * Adds the ComponentInstaller Plugin to the Composer instance.\n *\n * @see ComponentInstaller\\Installer\n */\nclass ComponentInstallerPlugin implements PluginInterface\n{\n    /**\n     * Called when the plugin is activated.\n     */\n    public function activate(Composer $composer, IOInterface $io)\n    {\n        $installer = new Installer($io, $composer);\n        $composer->getInstallationManager()->addInstaller($installer);\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Installer.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller;\n\nuse Composer\\Installer\\LibraryInstaller;\nuse Composer\\Script\\Event;\nuse Composer\\Package\\PackageInterface;\nuse Composer\\Package\\AliasPackage;\n\n/**\n * Component Installer for Composer.\n */\nclass Installer extends LibraryInstaller\n{\n    private static $defaultProcesses = array(\n        // Copy the assets to the Components directory.\n        \"ComponentInstaller\\\\Process\\\\CopyProcess\",\n        // Build the require.js file.\n        \"ComponentInstaller\\\\Process\\\\RequireJsProcess\",\n        // Build the require.css file.\n        \"ComponentInstaller\\\\Process\\\\RequireCssProcess\",\n        // Compile the require-built.js file.\n        \"ComponentInstaller\\\\Process\\\\BuildJsProcess\",\n    );\n\n    /**\n     * The location where Components are to be installed.\n     */\n    protected $componentDir;\n\n    /**\n     * {@inheritDoc}\n     *\n     * Components are supported by all packages. This checks wheteher or not the\n     * entire package is a \"component\", as well as injects the script to act\n     * on components embedded in packages that are not just \"component\" types.\n     */\n    public function supports($packageType)\n    {\n        // Components are supported by all package types. We will just act on\n        // the root package's scripts if available.\n        $rootPackage = isset($this->composer) ? $this->composer->getPackage() : null;\n        if (isset($rootPackage)) {\n            // Ensure we get the root package rather than its alias.\n            while ($rootPackage instanceof AliasPackage) {\n                $rootPackage = $rootPackage->getAliasOf();\n            }\n\n            // Make sure the root package can override the available scripts.\n            if (method_exists($rootPackage, 'setScripts')) {\n                $scripts = $rootPackage->getScripts();\n                // Act on the \"post-autoload-dump\" command so that we can act on all\n                // the installed packages.\n                $scripts['post-autoload-dump']['component-installer'] = 'ComponentInstaller\\\\Installer::postAutoloadDump';\n                $rootPackage->setScripts($scripts);\n            }\n        }\n\n        // State support for \"component\" package types.\n        return $packageType == 'component';\n    }\n\n    /**\n     * Gets the destination Component directory.\n     *\n     * @param PackageInterface $package\n     * @return string\n     *   The path to where the final Component should be installed.\n     */\n    public function getComponentPath(PackageInterface $package)\n    {\n        // Parse the pretty name for the vendor and package name.\n        $name = $prettyName = $package->getPrettyName();\n        if (strpos($prettyName, '/') !== false) {\n            list($vendor, $name) = explode('/', $prettyName);\n            unset($vendor);\n        }\n\n        // First look for an override in root package's extra, then try the package's extra\n        $rootPackage = $this->composer->getPackage();\n        $rootExtras = $rootPackage ? $rootPackage->getExtra() : array();\n        $customComponents = isset($rootExtras['component']) ? $rootExtras['component'] : array();\n\n        if (isset($customComponents[$prettyName]) && is_array($customComponents[$prettyName])) {\n            $component = $customComponents[$prettyName];\n        }\n        else {\n            $extra = $package->getExtra();\n            $component = isset($extra['component']) ? $extra['component'] : array();\n        }\n\n        // Allow the component to define its own name.\n        if (isset($component['name'])) {\n            $name = $component['name'];\n        }\n\n        // Find where the package should be located.\n        return $this->getComponentDir() . DIRECTORY_SEPARATOR . $name;\n    }\n\n    /**\n     * Initialize the Component directory, as well as the vendor directory.\n     */\n    protected function initializeVendorDir()\n    {\n        $this->componentDir = $this->getComponentDir();\n        $this->filesystem->ensureDirectoryExists($this->componentDir);\n        parent::initializeVendorDir();\n    }\n\n    /**\n     * Retrieves the Installer's provided component directory.\n     */\n    public function getComponentDir()\n    {\n        $config = $this->composer->getConfig();\n        return $config->has('component-dir') ? $config->get('component-dir') : 'components';\n    }\n\n    /**\n     * Remove both the installed code and files from the Component directory.\n     *\n     * @param PackageInterface $package\n     */\n    public function removeCode(PackageInterface $package)\n    {\n        $this->removeComponent($package);\n        parent::removeCode($package);\n    }\n\n    /**\n     * Remove a Component's files from the Component directory.\n     *\n     * @param PackageInterface $package\n     * @return bool\n     */\n    public function removeComponent(PackageInterface $package)\n    {\n        $path = $this->getComponentPath($package);\n        return $this->filesystem->remove($path);\n    }\n\n    /**\n     * Before installing the Component, be sure its destination is clear first.\n     *\n     * @param PackageInterface $package\n     */\n    public function installCode(PackageInterface $package)\n    {\n        $this->removeComponent($package);\n        parent::installCode($package);\n    }\n\n    /**\n     * Script callback; Acted on after the autoloader is dumped.\n     *\n     * @param Event $event\n     */\n    public static function postAutoloadDump(Event $event)\n    {\n        // Retrieve basic information about the environment and present a\n        // message to the user.\n        $composer = $event->getComposer();\n        $config = $composer->getConfig();\n        $io = $event->getIO();\n        $io->write('<info>Compiling component files</info>');\n\n        // Set up all the processes.\n        $processes = $config->has('component-processes') ? \n                $config->get('component-processes') :\n                static::$defaultProcesses;\n\n        // Initialize and execute each process in sequence.\n        foreach ($processes as $process) {\n            $options = array();\n\n            if (is_array($process)) {\n                $options = isset($process['options']) ? $process['options'] : array();\n                $class = $process['class'];\n            }\n            else {\n                $class = $process;\n            }\n\n            if(!class_exists($class)){\n                $io->write(\"<warning>Process class '$class' not found, skipping this process</warning>\");\n                continue;\n            }\n            \n            /** @var \\ComponentInstaller\\Process\\Process $process */\n            $process = new $class($composer, $io, $options);\n            // When an error occurs during initialization, end the process.\n            if (!$process->init()) {\n                $io->write(\"<warning>An error occurred while initializing the '$class' process.</warning>\");\n                break;\n            }\n            $process->process();\n        }\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/BuildJsProcess.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\n/**\n * Builds all JavaScript Components into one require-built.js.\n */\nclass BuildJsProcess extends Process\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function process()\n    {\n        return $this->compile($this->packages);\n    }\n\n    /**\n     * Copy file assets from the given packages to the component directory.\n     *\n     * @param array $packages\n     *   An array of packages.\n     * @return bool\n     */\n    public function compile($packages)\n    {\n        // Set up the initial require-build.js file.\n        $destination = $this->componentDir.DIRECTORY_SEPARATOR.'require-built.js';\n        $require = $this->componentDir.DIRECTORY_SEPARATOR.'require.js';\n        copy($require, $destination);\n\n        // Cycle through each package and add it to the built require.js file.\n        foreach ($packages as $package) {\n            // Retrieve some information about the package\n            $name = isset($package['name']) ? $package['name'] : '__component__';\n            $extra = isset($package['extra']) ? $package['extra'] : array();\n            $componentName = $this->getComponentName($name, $extra);\n\n            // Find where the source file is located.\n            $packageDir = $this->componentDir.DIRECTORY_SEPARATOR.$componentName;\n            $source = $packageDir.DIRECTORY_SEPARATOR.$componentName.'-built.js';\n\n            // Make sure the source script is available.\n            if (file_exists($source)) {\n                // Build the compiled script.\n                $content = file_get_contents($source);\n                $output = $this->definePrefix($componentName) . $content . $this->definePostfix();\n\n                // Append the module definition to the destination file.\n                file_put_contents($destination, $output, FILE_APPEND);\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Provide the initial definition prefix.\n     *\n     * @param string $componentName\n     * @return string Begin the module definition.\n     */\n    protected function definePrefix($componentName)\n    {\n        // Define the module using the simplified CommonJS wrapper.\n        return \"\\ndefine('$componentName', function (require, exports, module) {\\n\";\n    }\n\n    /**\n     * Finish the module definition.\n     *\n     * @return string Close brackets to finish the module.\n     */\n    protected function definePostfix()\n    {\n        return \"\\n});\\n\";\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/CopyProcess.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\n/**\n * Process which copies components from their source to the components folder.\n */\nclass CopyProcess extends Process\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function process()\n    {\n        return $this->copy($this->packages);\n    }\n\n    /**\n     * Copy file assets from the given packages to the component directory.\n     *\n     * @param array $packages\n     *   An array of packages.\n     * @return bool\n     */\n    public function copy($packages)\n    {\n        // Iterate over each package that should be processed.\n        foreach ($packages as $package) {\n            // Retrieve some information about the package.\n            $packageDir = $this->getVendorDir($package);\n            $name = isset($package['name']) ? $package['name'] : '__component__';\n            $extra = isset($package['extra']) ? $package['extra'] : array();\n            $componentName = $this->getComponentName($name, $extra);\n\n            // Cycle through each asset type.\n            $fileType = array('scripts', 'styles', 'files');\n            foreach ($fileType as $type) {\n                // Only act on the files if they're available.\n                if (isset($extra['component'][$type]) && is_array($extra['component'][$type])) {\n                    foreach ($extra['component'][$type] as $file) {\n                        // Make sure the file itself is available.\n                        $source = $packageDir.DIRECTORY_SEPARATOR.$file;\n\n                        // Perform a recursive glob file search on the pattern.\n                        foreach ($this->fs->recursiveGlobFiles($source) as $filesource) {\n                            // Find the final destination without the package directory.\n                            $withoutPackageDir = str_replace($packageDir.DIRECTORY_SEPARATOR, '', $filesource);\n\n                            // Construct the final file destination.\n                            $destination = $this->componentDir.DIRECTORY_SEPARATOR.$componentName.DIRECTORY_SEPARATOR.$withoutPackageDir;\n\n                            // Ensure the directory is available.\n                            $this->fs->ensureDirectoryExists(dirname($destination));\n\n                            // Copy the file to its destination.\n                            copy($filesource, $destination);\n                        }\n                    }\n                }\n            }\n        }\n\n        return true;\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/Process.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\nuse Composer\\IO\\IOInterface;\nuse Composer\\Composer;\nuse Composer\\IO\\NullIO;\nuse Composer\\Package\\Dumper\\ArrayDumper;\nuse ComponentInstaller\\Util\\Filesystem;\nuse Composer\\Package\\Loader\\ArrayLoader;\n\n/**\n * The base Process type.\n *\n * Processes are initialized, and then run during installation.\n */\nclass Process implements ProcessInterface\n{\n    /**\n     * @var Composer\n     */\n    protected $composer;\n\n    /**\n     * @var IOInterface|NullIO\n     */\n    protected $io;\n\n    /**\n     * @var \\Composer\\Config\n     */\n    protected $config;\n\n    /**\n     * @var array\n     */\n    protected $packages = array();\n\n    /**\n     * @var string\n     */\n    protected $componentDir = 'components';\n\n    /**\n     * @var Filesystem\n     */\n    protected $fs;\n\n    /**\n     * The Composer installation manager to find Component vendor directories.\n     * @var \\Composer\\Installer\\InstallationManager\n     */\n    protected $installationManager;\n\n    /**\n     * Any user provided options to configure this process.\n     * @var array\n     */\n    protected $options;\n\n    /**\n     * {@inheritdoc}\n     */\n    public function __construct(Composer $composer = null, IOInterface $io = null)\n    {\n        $this->composer = isset($composer) ? $composer : new Composer();\n        $this->io = isset($io) ? $io : new NullIO();\n        $this->fs = new Filesystem();\n        $this->installationManager = $this->composer->getInstallationManager();\n        \n        // TODO: Break compatibility and expect in interface\n        $args = func_get_args();\n        $this->options = count($args) > 2 && is_array($args[2]) ? $args[2]: array();\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function init()\n    {\n        // Retrieve the configuration variables.\n        $this->config = $this->composer->getConfig();\n        if (isset($this->config)) {\n            if ($this->config->has('component-dir')) {\n                $this->componentDir = $this->config->get('component-dir');\n            }\n        }\n\n        // Get the available packages.\n        $allPackages = array();\n        /** @var \\Composer\\Package\\Locker $locker */\n        $locker = $this->composer->getLocker();\n        if ($locker !== null && $locker->isLocked()) {\n            $lockData = $locker->getLockData();\n            $allPackages = $lockData['packages'];\n\n            // Also merge in any of the development packages.\n            $dev = isset($lockData['packages-dev']) ? $lockData['packages-dev'] : array();\n            foreach ($dev as $package) {\n                $allPackages[] = $package;\n            }\n        }\n\n        // Only add those packages that we can reasonably\n        // assume are components into our packages list\n        /** @var \\Composer\\Package\\RootPackageInterface $rootPackage */\n        $rootPackage = $this->composer->getPackage();\n        $rootExtras = $rootPackage ? $rootPackage->getExtra() : array();\n        $customComponents = isset($rootExtras['component']) ? $rootExtras['component'] : array();\n        foreach ($allPackages as $package) {\n            $name = $package['name'];\n            if (isset($customComponents[$name]) && is_array($customComponents[$name])) {\n                $package['extra'] = array('component' => $customComponents[$name]);\n                $this->packages[] = $package;\n            }\n            else {\n                $extra = isset($package['extra']) ? $package['extra'] : array();\n                if (isset($extra['component']) && is_array($extra['component'])) {\n                    $this->packages[] = $package;\n                }\n            }\n        }\n\n        // Add the root package to the packages list.\n        $root = $this->composer->getPackage();\n        if ($root) {\n            $dumper = new ArrayDumper();\n            $package = $dumper->dump($root);\n            $package['is-root'] = true;\n            $this->packages[] = $package;\n        }\n\n        return true;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function process()\n    {\n        return false;\n    }\n\n    /**\n     * Retrieves the component name for the component.\n     *\n     * @param string $prettyName\n     *   The Composer package name.\n     * @param array $extra\n     *   The extra config options sent from Composer.\n     *\n     * @return string\n     *   The name of the component, without its vendor name.\n     */\n    public function getComponentName($prettyName, array $extra = array())\n    {\n        // Parse the pretty name for the vendor and name.\n        if (strpos($prettyName, '/') !== false) {\n            list($vendor, $name) = explode('/', $prettyName);\n            unset($vendor);\n        } else {\n            // Vendor wasn't found, so default to the pretty name instead.\n            $name = $prettyName;\n        }\n\n        // Allow the component to define its own name.\n        $component = isset($extra['component']) ? $extra['component'] : array();\n        if (isset($component['name'])) {\n            $name = $component['name'];\n        }\n\n        return $name;\n    }\n\n    /**\n     * Retrieves the component directory.\n     */\n    public function getComponentDir()\n    {\n        return $this->componentDir;\n    }\n\n    /**\n     * Sets the component directory.\n     * @param string $dir\n     * @return string\n     */\n    public function setComponentDir($dir)\n    {\n        return $this->componentDir = $dir;\n    }\n\n    /**\n     * Retrieves the given package's vendor directory, where it's installed.\n     *\n     * @param array $package\n     *   The package to retrieve the vendor directory for.\n     * @return string\n     */\n    public function getVendorDir(array $package)\n    {\n        // The root package vendor directory is not handled by getInstallPath().\n        if (isset($package['is-root']) && $package['is-root'] === true) {\n            $path = getcwd();\n\n            if (!file_exists($path.DIRECTORY_SEPARATOR.'composer.json')) {\n                for ($temp = __DIR__; strlen($temp) > 3; $temp = dirname($temp)) {\n                    if (file_exists($temp.DIRECTORY_SEPARATOR.'composer.json')) {\n                        $path = $temp;\n                    }\n                }\n            }\n\n            return $path;\n        }\n\n        if (!isset($package['version'])) {\n            $package['version'] = '1.0.0';\n        }\n        $loader = new ArrayLoader();\n        $completePackage = $loader->load($package);\n\n        return $this->installationManager->getInstallPath($completePackage);\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/ProcessInterface.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\nuse Composer\\IO\\IOInterface;\nuse Composer\\Composer;\n\ninterface ProcessInterface\n{\n    /**\n     * Create a new Process.\n     *\n     * @param Composer $composer\n     *   The Composer object to act on.\n     * @param IOInterface $io\n     *   Input/Output object to act on.\n     */\n    public function __construct(Composer $composer, IOInterface $io);\n\n    /**\n     * Initialize the process before its run.\n     *\n     * @return boolean\n     *   Whether or not the process should continue after initialization.\n     */\n    public function init();\n\n    /**\n     * Called when running through the process.\n     *\n     * @return boolean\n     *   True or false depending on whether the process was successful.\n     */\n    public function process();\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/RequireCssProcess.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\nuse Composer\\Config;\nuse Assetic\\Asset\\AssetCollection;\nuse Assetic\\Filter\\CssRewriteFilter;\nuse Assetic\\Asset\\FileAsset;\nuse Assetic\\Filter\\FilterCollection;\n\n/**\n * Builds the require.css file from all Component stylesheets.\n */\nclass RequireCssProcess extends Process\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function process()\n    {\n        $filters = array(new CssRewriteFilter());\n        if ($this->config->has('component-styleFilters')) {\n            $customFilters = $this->config->get('component-styleFilters');\n            if (isset($customFilters) && is_array($customFilters)) {\n                foreach ($customFilters as $filter => $filterParams) {\n                    $reflection = new \\ReflectionClass($filter);\n                    $filters[] = $reflection->newInstanceArgs($filterParams);\n                }\n            }\n        }\n\n        $filterCollection = new FilterCollection($filters);\n\n        $assets = new AssetCollection();\n        $styles = $this->packageStyles($this->packages);\n        foreach ($styles as $package => $packageStyles) {\n            $packageAssets = new AssetCollection();\n            $packagePath = $this->componentDir.'/'.$package;\n\n            foreach ($packageStyles as $style => $paths) {\n                foreach ($paths as $path) {\n                    // The full path to the CSS file.\n                    $assetPath = realpath($path);\n                    // The root of the CSS file.\n                    $sourceRoot = dirname($path);\n                    // The style path to the CSS file when external.\n                    $sourcePath = $package . '/' . $style;\n                    //Replace glob patterns with filenames.\n                    $filename = basename($style);\n                    if(preg_match('~^\\*(\\.[^\\.]+)$~', $filename, $matches)){\n                        $sourcePath = str_replace($filename, basename($assetPath), $sourcePath);\n                    }\n                    // Where the final CSS will be generated.\n                    $targetPath = $this->componentDir;\n                    // Build the asset and add it to the collection.\n                    $asset = new FileAsset($assetPath, $filterCollection, $sourceRoot, $sourcePath);\n                    $asset->setTargetPath($targetPath);\n                    $assets->add($asset);\n                    // Add asset to package collection.\n                    $sourcePath = preg_replace('{^.*'.preg_quote($package).'/}', '', $sourcePath);\n                    $asset = new FileAsset($assetPath, $filterCollection, $sourceRoot, $sourcePath);\n                    $asset->setTargetPath($packagePath);\n                    $packageAssets->add($asset);\n                }\n            }\n\n            if (file_put_contents($packagePath.'/'.$package.'-built.css', $packageAssets->dump()) === FALSE) {\n                $this->io->write(\"<error>Error writing $package-built.css to destination</error>\");\n            }\n        }\n\n        if (file_put_contents($this->componentDir . '/require.css', $assets->dump()) === FALSE) {\n            $this->io->write('<error>Error writing require.css to destination</error>');\n            return false;\n        }\n\n        return null;\n    }\n\n    /**\n     * Retrieves an array of styles from a collection of packages.\n     *\n     * @param array $packages\n     *   An array of packages from the composer.lock file.\n     *\n     * @return array\n     *   A set of package styles.\n     */\n    public function packageStyles(array $packages)\n    {\n        $output = array();\n\n        // Construct the packages configuration.\n        foreach ($packages as $package) {\n            // Retrieve information from the extra options.\n            $extra = isset($package['extra']) ? $package['extra'] : array();\n            $name = $this->getComponentName($package['name'], $extra);\n            $component = isset($extra['component']) ? $extra['component'] : array();\n            $styles = isset($component['styles']) ? $component['styles'] : array();\n            $vendorDir = $this->getVendorDir($package);\n\n            // Loop through each style.\n            foreach ($styles as $style) {\n                // Find the style path from the vendor directory.\n                $path = strtr($vendorDir.'/'.$style, '/', DIRECTORY_SEPARATOR);\n\n                // Search for the candidate with a glob recursive file search.\n                $files = $this->fs->recursiveGlobFiles($path);\n                foreach ($files as $file) {\n                    // Provide the package name, style and full path.\n                    $output[$name][$style][] = $file;\n                }\n            }\n        }\n\n        return $output;\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Process/RequireJsProcess.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Process;\n\nuse Assetic\\Asset\\StringAsset;\nuse Composer\\Config;\nuse Composer\\Json\\JsonFile;\nuse Assetic\\Asset\\AssetCollection;\nuse Assetic\\Asset\\FileAsset;\n\n/**\n * Builds the require.js configuration.\n */\nclass RequireJsProcess extends Process\n{\n    /**\n     * The base URL for the require.js configuration.\n     */\n    protected $baseUrl = 'components';\n\n    /**\n     * {@inheritdoc}\n     */\n    public function init()\n    {\n        $output = parent::init();\n        if ($this->config->has('component-baseurl')) {\n            $this->baseUrl = $this->config->get('component-baseurl');\n        }\n\n        return $output;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function process()\n    {\n        // Construct the require.js and stick it in the destination.\n        $json = $this->requireJson($this->packages, $this->config);\n        $requireConfig = $this->requireJs($json);\n\n        // Attempt to write the require.config.js file.\n        $destination = $this->componentDir . '/require.config.js';\n        $this->fs->ensureDirectoryExists(dirname($destination));\n        if (file_put_contents($destination, $requireConfig) === FALSE) {\n            $this->io->write('<error>Error writing require.config.js</error>');\n\n            return false;\n        }\n\n        // Read in require.js to prepare the final require.js.\n        if (!file_exists(dirname(__DIR__) . '/Resources/require.js')) {\n            $this->io->write('<error>Error reading in require.js</error>');\n\n            return false;\n        }\n\n        $assets = $this->newAssetCollection();\n        $assets->add(new StringAsset($requireConfig));\n        $assets->add(new FileAsset(dirname(__DIR__) . '/Resources/require.js'));\n\n        // Append the config to the require.js and write it.\n        if (file_put_contents($this->componentDir . '/require.js', $assets->dump()) === FALSE) {\n            $this->io->write('<error>Error writing require.js to the components directory</error>');\n\n            return false;\n        }\n\n        return null;\n    }\n\n    /**\n     * Creates a require.js configuration from an array of packages.\n     *\n     * @param $packages\n     *   An array of packages from the composer.lock file.\n     *\n     * @return array\n     *   The built JSON array.\n     */\n    public function requireJson(array $packages)\n    {\n        $json = array();\n\n        // Construct the packages configuration.\n        foreach ($packages as $package) {\n            // Retrieve information from the extra options.\n            $extra = isset($package['extra']) ? $package['extra'] : array();\n            $options = isset($extra['component']) ? $extra['component'] : array();\n\n            // Construct the base details.\n            $name = $this->getComponentName($package['name'], $extra);\n            $component = array(\n                'name' => $name,\n            );\n\n            // Build the \"main\" directive.\n            $scripts = isset($options['scripts']) ? $options['scripts'] : array();\n            if (!empty($scripts)) {\n                // Put all scripts into a build.js file.\n                $result = $this->aggregateScripts($package, $scripts, $name.DIRECTORY_SEPARATOR.$name.'-built.js');\n                if ($result) {\n                    // If the aggregation was successful, add the script to the\n                    // packages array.\n                    $component['main'] = $name.'-built.js';\n\n                    // Add the component to the packages array.\n                    $json['packages'][] = $component;\n                }\n            }\n\n            // Add the shim definition for the package.\n            $shim = isset($options['shim']) ? $options['shim'] : array();\n            if (!empty($shim)) {\n                $json['shim'][$name] = $shim;\n            }\n\n            // Add the config definition for the package.\n            $packageConfig = isset($options['config']) ? $options['config'] : array();\n            if (!empty($packageConfig)) {\n                $json['config'][$name] = $packageConfig;\n            }\n        }\n\n        // Provide the baseUrl.\n        $json['baseUrl'] = $this->baseUrl;\n\n        // Merge in configuration options from the root.\n        if ($this->config->has('component')) {\n            $config = $this->config->get('component');\n            if (isset($config) && is_array($config)) {\n                // Use a recursive, distict array merge.\n                $json = $this->arrayMergeRecursiveDistinct($json, $config);\n            }\n        }\n\n        return $json;\n    }\n\n    /**\n     * Concatenate all scripts together into one destination file.\n     *\n     * @param array $package\n     * @param array $scripts\n     * @param string $file\n     * @return bool\n     */\n    public function aggregateScripts($package, array $scripts, $file)\n    {\n        $assets = $this->newAssetCollection();\n\n        foreach ($scripts as $script) {\n            // Collect each candidate from a glob file search.\n            $path = $this->getVendorDir($package).DIRECTORY_SEPARATOR.$script;\n            $matches = $this->fs->recursiveGlobFiles($path);\n            foreach ($matches as $match) {\n                $assets->add(new FileAsset($match));\n            }\n        }\n        $js = $assets->dump();\n\n        // Write the file if there are any JavaScript assets.\n        if (!empty($js)) {\n            $destination = $this->componentDir.DIRECTORY_SEPARATOR.$file;\n            $this->fs->ensureDirectoryExists(dirname($destination));\n\n            return file_put_contents($destination, $js);\n        }\n\n        return false;\n    }\n\n    /**\n     * Constructs the require.js file from the provided require.js JSON array.\n     *\n     * @param $json\n     *   The require.js JSON configuration.\n     *\n     * @return string\n     *   The RequireJS JavaScript configuration.\n     */\n    public function requireJs(array $json = array())\n    {\n        // Encode the array to a JSON array.\n        $js = JsonFile::encode($json);\n\n        // Construct the JavaScript output.\n        $output = <<<EOT\nvar components = $js;\nif (typeof require !== \"undefined\" && require.config) {\n    require.config(components);\n} else {\n    var require = components;\n}\nif (typeof exports !== \"undefined\" && typeof module !== \"undefined\") {\n    module.exports = components;\n}\nEOT;\n\n        return $output;\n    }\n\n    /**\n     * Merges two arrays without changing string array keys. Appends to array if keys are numeric.\n     *\n     * @see array_merge()\n     * @see array_merge_recursive()\n     *\n     * @param array $array1\n     * @param array $array2\n     * @return array\n     */\n    protected function arrayMergeRecursiveDistinct(array &$array1, array &$array2)\n    {\n        $merged = $array1;\n\n        foreach ($array2 as $key => &$value) {\n            if(is_numeric($key)){\n                $merged[] = $value;\n            } else {\n                if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {\n                    $merged[$key] = $this->arrayMergeRecursiveDistinct($merged[$key], $value);\n                }\n                else {\n                    $merged[$key] = $value;\n                }\n            }\n        }\n\n        return $merged;\n    }\n\n    /**\n     * @return AssetCollection\n     */\n    protected function newAssetCollection()\n    {\n        // Aggregate all the assets into one file.\n        $assets = new AssetCollection();\n        if ($this->config->has('component-scriptFilters')) {\n            $filters = $this->config->get('component-scriptFilters');\n            if (isset($filters) && is_array($filters)) {\n                foreach ($filters as $filter => $filterParams) {\n                    $reflection = new \\ReflectionClass($filter);\n                    /** @var \\Assetic\\Filter\\FilterInterface $filter */\n                    $filter = $reflection->newInstanceArgs($filterParams);\n                    $assets->ensureFilter($filter);\n                }\n            }\n        }\n\n        return $assets;\n    }\n}\n"
  },
  {
    "path": "src/ComponentInstaller/Resources/require.js",
    "content": "/** vim: et:ts=4:sw=4:sts=4\n * @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.\n * Available via the MIT or new BSD license.\n * see: http://github.com/jrburke/requirejs for details\n */\n//Not using strict: uneven strict support in browsers, #392, and causes\n//problems with requirejs.exec()/transpiler plugins that may not be strict.\n/*jslint regexp: true, nomen: true, sloppy: true */\n/*global window, navigator, document, importScripts, setTimeout, opera */\n\nvar requirejs, require, define;\n(function (global) {\n    var req, s, head, baseElement, dataMain, src,\n        interactiveScript, currentlyAddingScript, mainScript, subPath,\n        version = '2.1.5',\n        commentRegExp = /(\\/\\*([\\s\\S]*?)\\*\\/|([^:]|^)\\/\\/(.*)$)/mg,\n        cjsRequireRegExp = /[^.]\\s*require\\s*\\(\\s*[\"']([^'\"\\s]+)[\"']\\s*\\)/g,\n        jsSuffixRegExp = /\\.js$/,\n        currDirRegExp = /^\\.\\//,\n        op = Object.prototype,\n        ostring = op.toString,\n        hasOwn = op.hasOwnProperty,\n        ap = Array.prototype,\n        apsp = ap.splice,\n        isBrowser = !!(typeof window !== 'undefined' && navigator && document),\n        isWebWorker = !isBrowser && typeof importScripts !== 'undefined',\n        //PS3 indicates loaded and complete, but need to wait for complete\n        //specifically. Sequence is 'loading', 'loaded', execution,\n        // then 'complete'. The UA check is unfortunate, but not sure how\n        //to feature test w/o causing perf issues.\n        readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?\n                      /^complete$/ : /^(complete|loaded)$/,\n        defContextName = '_',\n        //Oh the tragedy, detecting opera. See the usage of isOpera for reason.\n        isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',\n        contexts = {},\n        cfg = {},\n        globalDefQueue = [],\n        useInteractive = false;\n\n    function isFunction(it) {\n        return ostring.call(it) === '[object Function]';\n    }\n\n    function isArray(it) {\n        return ostring.call(it) === '[object Array]';\n    }\n\n    /**\n     * Helper function for iterating over an array. If the func returns\n     * a true value, it will break out of the loop.\n     */\n    function each(ary, func) {\n        if (ary) {\n            var i;\n            for (i = 0; i < ary.length; i += 1) {\n                if (ary[i] && func(ary[i], i, ary)) {\n                    break;\n                }\n            }\n        }\n    }\n\n    /**\n     * Helper function for iterating over an array backwards. If the func\n     * returns a true value, it will break out of the loop.\n     */\n    function eachReverse(ary, func) {\n        if (ary) {\n            var i;\n            for (i = ary.length - 1; i > -1; i -= 1) {\n                if (ary[i] && func(ary[i], i, ary)) {\n                    break;\n                }\n            }\n        }\n    }\n\n    function hasProp(obj, prop) {\n        return hasOwn.call(obj, prop);\n    }\n\n    function getOwn(obj, prop) {\n        return hasProp(obj, prop) && obj[prop];\n    }\n\n    /**\n     * Cycles over properties in an object and calls a function for each\n     * property value. If the function returns a truthy value, then the\n     * iteration is stopped.\n     */\n    function eachProp(obj, func) {\n        var prop;\n        for (prop in obj) {\n            if (hasProp(obj, prop)) {\n                if (func(obj[prop], prop)) {\n                    break;\n                }\n            }\n        }\n    }\n\n    /**\n     * Simple function to mix in properties from source into target,\n     * but only if target does not already have a property of the same name.\n     */\n    function mixin(target, source, force, deepStringMixin) {\n        if (source) {\n            eachProp(source, function (value, prop) {\n                if (force || !hasProp(target, prop)) {\n                    if (deepStringMixin && typeof value !== 'string') {\n                        if (!target[prop]) {\n                            target[prop] = {};\n                        }\n                        mixin(target[prop], value, force, deepStringMixin);\n                    } else {\n                        target[prop] = value;\n                    }\n                }\n            });\n        }\n        return target;\n    }\n\n    //Similar to Function.prototype.bind, but the 'this' object is specified\n    //first, since it is easier to read/figure out what 'this' will be.\n    function bind(obj, fn) {\n        return function () {\n            return fn.apply(obj, arguments);\n        };\n    }\n\n    function scripts() {\n        return document.getElementsByTagName('script');\n    }\n\n    //Allow getting a global that expressed in\n    //dot notation, like 'a.b.c'.\n    function getGlobal(value) {\n        if (!value) {\n            return value;\n        }\n        var g = global;\n        each(value.split('.'), function (part) {\n            g = g[part];\n        });\n        return g;\n    }\n\n    /**\n     * Constructs an error with a pointer to an URL with more information.\n     * @param {String} id the error ID that maps to an ID on a web page.\n     * @param {String} message human readable error.\n     * @param {Error} [err] the original error, if there is one.\n     *\n     * @returns {Error}\n     */\n    function makeError(id, msg, err, requireModules) {\n        var e = new Error(msg + '\\nhttp://requirejs.org/docs/errors.html#' + id);\n        e.requireType = id;\n        e.requireModules = requireModules;\n        if (err) {\n            e.originalError = err;\n        }\n        return e;\n    }\n\n    if (typeof define !== 'undefined') {\n        //If a define is already in play via another AMD loader,\n        //do not overwrite.\n        return;\n    }\n\n    if (typeof requirejs !== 'undefined') {\n        if (isFunction(requirejs)) {\n            //Do not overwrite and existing requirejs instance.\n            return;\n        }\n        cfg = requirejs;\n        requirejs = undefined;\n    }\n\n    //Allow for a require config object\n    if (typeof require !== 'undefined' && !isFunction(require)) {\n        //assume it is a config object.\n        cfg = require;\n        require = undefined;\n    }\n\n    function newContext(contextName) {\n        var inCheckLoaded, Module, context, handlers,\n            checkLoadedTimeoutId,\n            config = {\n                //Defaults. Do not set a default for map\n                //config to speed up normalize(), which\n                //will run faster if there is no default.\n                waitSeconds: 7,\n                baseUrl: './',\n                paths: {},\n                pkgs: {},\n                shim: {},\n                config: {}\n            },\n            registry = {},\n            //registry of just enabled modules, to speed\n            //cycle breaking code when lots of modules\n            //are registered, but not activated.\n            enabledRegistry = {},\n            undefEvents = {},\n            defQueue = [],\n            defined = {},\n            urlFetched = {},\n            requireCounter = 1,\n            unnormalizedCounter = 1;\n\n        /**\n         * Trims the . and .. from an array of path segments.\n         * It will keep a leading path segment if a .. will become\n         * the first path segment, to help with module name lookups,\n         * which act like paths, but can be remapped. But the end result,\n         * all paths that use this function should look normalized.\n         * NOTE: this method MODIFIES the input array.\n         * @param {Array} ary the array of path segments.\n         */\n        function trimDots(ary) {\n            var i, part;\n            for (i = 0; ary[i]; i += 1) {\n                part = ary[i];\n                if (part === '.') {\n                    ary.splice(i, 1);\n                    i -= 1;\n                } else if (part === '..') {\n                    if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {\n                        //End of the line. Keep at least one non-dot\n                        //path segment at the front so it can be mapped\n                        //correctly to disk. Otherwise, there is likely\n                        //no path mapping for a path starting with '..'.\n                        //This can still fail, but catches the most reasonable\n                        //uses of ..\n                        break;\n                    } else if (i > 0) {\n                        ary.splice(i - 1, 2);\n                        i -= 2;\n                    }\n                }\n            }\n        }\n\n        /**\n         * Given a relative module name, like ./something, normalize it to\n         * a real name that can be mapped to a path.\n         * @param {String} name the relative name\n         * @param {String} baseName a real name that the name arg is relative\n         * to.\n         * @param {Boolean} applyMap apply the map config to the value. Should\n         * only be done if this normalization is for a dependency ID.\n         * @returns {String} normalized name\n         */\n        function normalize(name, baseName, applyMap) {\n            var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,\n                foundMap, foundI, foundStarMap, starI,\n                baseParts = baseName && baseName.split('/'),\n                normalizedBaseParts = baseParts,\n                map = config.map,\n                starMap = map && map['*'];\n\n            //Adjust any relative paths.\n            if (name && name.charAt(0) === '.') {\n                //If have a base name, try to normalize against it,\n                //otherwise, assume it is a top-level require that will\n                //be relative to baseUrl in the end.\n                if (baseName) {\n                    if (getOwn(config.pkgs, baseName)) {\n                        //If the baseName is a package name, then just treat it as one\n                        //name to concat the name with.\n                        normalizedBaseParts = baseParts = [baseName];\n                    } else {\n                        //Convert baseName to array, and lop off the last part,\n                        //so that . matches that 'directory' and not name of the baseName's\n                        //module. For instance, baseName of 'one/two/three', maps to\n                        //'one/two/three.js', but we want the directory, 'one/two' for\n                        //this normalization.\n                        normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);\n                    }\n\n                    name = normalizedBaseParts.concat(name.split('/'));\n                    trimDots(name);\n\n                    //Some use of packages may use a . path to reference the\n                    //'main' module name, so normalize for that.\n                    pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));\n                    name = name.join('/');\n                    if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {\n                        name = pkgName;\n                    }\n                } else if (name.indexOf('./') === 0) {\n                    // No baseName, so this is ID is resolved relative\n                    // to baseUrl, pull off the leading dot.\n                    name = name.substring(2);\n                }\n            }\n\n            //Apply map config if available.\n            if (applyMap && map && (baseParts || starMap)) {\n                nameParts = name.split('/');\n\n                for (i = nameParts.length; i > 0; i -= 1) {\n                    nameSegment = nameParts.slice(0, i).join('/');\n\n                    if (baseParts) {\n                        //Find the longest baseName segment match in the config.\n                        //So, do joins on the biggest to smallest lengths of baseParts.\n                        for (j = baseParts.length; j > 0; j -= 1) {\n                            mapValue = getOwn(map, baseParts.slice(0, j).join('/'));\n\n                            //baseName segment has config, find if it has one for\n                            //this name.\n                            if (mapValue) {\n                                mapValue = getOwn(mapValue, nameSegment);\n                                if (mapValue) {\n                                    //Match, update name to the new value.\n                                    foundMap = mapValue;\n                                    foundI = i;\n                                    break;\n                                }\n                            }\n                        }\n                    }\n\n                    if (foundMap) {\n                        break;\n                    }\n\n                    //Check for a star map match, but just hold on to it,\n                    //if there is a shorter segment match later in a matching\n                    //config, then favor over this star map.\n                    if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {\n                        foundStarMap = getOwn(starMap, nameSegment);\n                        starI = i;\n                    }\n                }\n\n                if (!foundMap && foundStarMap) {\n                    foundMap = foundStarMap;\n                    foundI = starI;\n                }\n\n                if (foundMap) {\n                    nameParts.splice(0, foundI, foundMap);\n                    name = nameParts.join('/');\n                }\n            }\n\n            return name;\n        }\n\n        function removeScript(name) {\n            if (isBrowser) {\n                each(scripts(), function (scriptNode) {\n                    if (scriptNode.getAttribute('data-requiremodule') === name &&\n                            scriptNode.getAttribute('data-requirecontext') === context.contextName) {\n                        scriptNode.parentNode.removeChild(scriptNode);\n                        return true;\n                    }\n                });\n            }\n        }\n\n        function hasPathFallback(id) {\n            var pathConfig = getOwn(config.paths, id);\n            if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {\n                removeScript(id);\n                //Pop off the first array value, since it failed, and\n                //retry\n                pathConfig.shift();\n                context.require.undef(id);\n                context.require([id]);\n                return true;\n            }\n        }\n\n        //Turns a plugin!resource to [plugin, resource]\n        //with the plugin being undefined if the name\n        //did not have a plugin prefix.\n        function splitPrefix(name) {\n            var prefix,\n                index = name ? name.indexOf('!') : -1;\n            if (index > -1) {\n                prefix = name.substring(0, index);\n                name = name.substring(index + 1, name.length);\n            }\n            return [prefix, name];\n        }\n\n        /**\n         * Creates a module mapping that includes plugin prefix, module\n         * name, and path. If parentModuleMap is provided it will\n         * also normalize the name via require.normalize()\n         *\n         * @param {String} name the module name\n         * @param {String} [parentModuleMap] parent module map\n         * for the module name, used to resolve relative names.\n         * @param {Boolean} isNormalized: is the ID already normalized.\n         * This is true if this call is done for a define() module ID.\n         * @param {Boolean} applyMap: apply the map config to the ID.\n         * Should only be true if this map is for a dependency.\n         *\n         * @returns {Object}\n         */\n        function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {\n            var url, pluginModule, suffix, nameParts,\n                prefix = null,\n                parentName = parentModuleMap ? parentModuleMap.name : null,\n                originalName = name,\n                isDefine = true,\n                normalizedName = '';\n\n            //If no name, then it means it is a require call, generate an\n            //internal name.\n            if (!name) {\n                isDefine = false;\n                name = '_@r' + (requireCounter += 1);\n            }\n\n            nameParts = splitPrefix(name);\n            prefix = nameParts[0];\n            name = nameParts[1];\n\n            if (prefix) {\n                prefix = normalize(prefix, parentName, applyMap);\n                pluginModule = getOwn(defined, prefix);\n            }\n\n            //Account for relative paths if there is a base name.\n            if (name) {\n                if (prefix) {\n                    if (pluginModule && pluginModule.normalize) {\n                        //Plugin is loaded, use its normalize method.\n                        normalizedName = pluginModule.normalize(name, function (name) {\n                            return normalize(name, parentName, applyMap);\n                        });\n                    } else {\n                        normalizedName = normalize(name, parentName, applyMap);\n                    }\n                } else {\n                    //A regular module.\n                    normalizedName = normalize(name, parentName, applyMap);\n\n                    //Normalized name may be a plugin ID due to map config\n                    //application in normalize. The map config values must\n                    //already be normalized, so do not need to redo that part.\n                    nameParts = splitPrefix(normalizedName);\n                    prefix = nameParts[0];\n                    normalizedName = nameParts[1];\n                    isNormalized = true;\n\n                    url = context.nameToUrl(normalizedName);\n                }\n            }\n\n            //If the id is a plugin id that cannot be determined if it needs\n            //normalization, stamp it with a unique ID so two matching relative\n            //ids that may conflict can be separate.\n            suffix = prefix && !pluginModule && !isNormalized ?\n                     '_unnormalized' + (unnormalizedCounter += 1) :\n                     '';\n\n            return {\n                prefix: prefix,\n                name: normalizedName,\n                parentMap: parentModuleMap,\n                unnormalized: !!suffix,\n                url: url,\n                originalName: originalName,\n                isDefine: isDefine,\n                id: (prefix ?\n                        prefix + '!' + normalizedName :\n                        normalizedName) + suffix\n            };\n        }\n\n        function getModule(depMap) {\n            var id = depMap.id,\n                mod = getOwn(registry, id);\n\n            if (!mod) {\n                mod = registry[id] = new context.Module(depMap);\n            }\n\n            return mod;\n        }\n\n        function on(depMap, name, fn) {\n            var id = depMap.id,\n                mod = getOwn(registry, id);\n\n            if (hasProp(defined, id) &&\n                    (!mod || mod.defineEmitComplete)) {\n                if (name === 'defined') {\n                    fn(defined[id]);\n                }\n            } else {\n                getModule(depMap).on(name, fn);\n            }\n        }\n\n        function onError(err, errback) {\n            var ids = err.requireModules,\n                notified = false;\n\n            if (errback) {\n                errback(err);\n            } else {\n                each(ids, function (id) {\n                    var mod = getOwn(registry, id);\n                    if (mod) {\n                        //Set error on module, so it skips timeout checks.\n                        mod.error = err;\n                        if (mod.events.error) {\n                            notified = true;\n                            mod.emit('error', err);\n                        }\n                    }\n                });\n\n                if (!notified) {\n                    req.onError(err);\n                }\n            }\n        }\n\n        /**\n         * Internal method to transfer globalQueue items to this context's\n         * defQueue.\n         */\n        function takeGlobalQueue() {\n            //Push all the globalDefQueue items into the context's defQueue\n            if (globalDefQueue.length) {\n                //Array splice in the values since the context code has a\n                //local var ref to defQueue, so cannot just reassign the one\n                //on context.\n                apsp.apply(defQueue,\n                           [defQueue.length - 1, 0].concat(globalDefQueue));\n                globalDefQueue = [];\n            }\n        }\n\n        handlers = {\n            'require': function (mod) {\n                if (mod.require) {\n                    return mod.require;\n                } else {\n                    return (mod.require = context.makeRequire(mod.map));\n                }\n            },\n            'exports': function (mod) {\n                mod.usingExports = true;\n                if (mod.map.isDefine) {\n                    if (mod.exports) {\n                        return mod.exports;\n                    } else {\n                        return (mod.exports = defined[mod.map.id] = {});\n                    }\n                }\n            },\n            'module': function (mod) {\n                if (mod.module) {\n                    return mod.module;\n                } else {\n                    return (mod.module = {\n                        id: mod.map.id,\n                        uri: mod.map.url,\n                        config: function () {\n                            return (config.config && getOwn(config.config, mod.map.id)) || {};\n                        },\n                        exports: defined[mod.map.id]\n                    });\n                }\n            }\n        };\n\n        function cleanRegistry(id) {\n            //Clean up machinery used for waiting modules.\n            delete registry[id];\n            delete enabledRegistry[id];\n        }\n\n        function breakCycle(mod, traced, processed) {\n            var id = mod.map.id;\n\n            if (mod.error) {\n                mod.emit('error', mod.error);\n            } else {\n                traced[id] = true;\n                each(mod.depMaps, function (depMap, i) {\n                    var depId = depMap.id,\n                        dep = getOwn(registry, depId);\n\n                    //Only force things that have not completed\n                    //being defined, so still in the registry,\n                    //and only if it has not been matched up\n                    //in the module already.\n                    if (dep && !mod.depMatched[i] && !processed[depId]) {\n                        if (getOwn(traced, depId)) {\n                            mod.defineDep(i, defined[depId]);\n                            mod.check(); //pass false?\n                        } else {\n                            breakCycle(dep, traced, processed);\n                        }\n                    }\n                });\n                processed[id] = true;\n            }\n        }\n\n        function checkLoaded() {\n            var map, modId, err, usingPathFallback,\n                waitInterval = config.waitSeconds * 1000,\n                //It is possible to disable the wait interval by using waitSeconds of 0.\n                expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),\n                noLoads = [],\n                reqCalls = [],\n                stillLoading = false,\n                needCycleCheck = true;\n\n            //Do not bother if this call was a result of a cycle break.\n            if (inCheckLoaded) {\n                return;\n            }\n\n            inCheckLoaded = true;\n\n            //Figure out the state of all the modules.\n            eachProp(enabledRegistry, function (mod) {\n                map = mod.map;\n                modId = map.id;\n\n                //Skip things that are not enabled or in error state.\n                if (!mod.enabled) {\n                    return;\n                }\n\n                if (!map.isDefine) {\n                    reqCalls.push(mod);\n                }\n\n                if (!mod.error) {\n                    //If the module should be executed, and it has not\n                    //been inited and time is up, remember it.\n                    if (!mod.inited && expired) {\n                        if (hasPathFallback(modId)) {\n                            usingPathFallback = true;\n                            stillLoading = true;\n                        } else {\n                            noLoads.push(modId);\n                            removeScript(modId);\n                        }\n                    } else if (!mod.inited && mod.fetched && map.isDefine) {\n                        stillLoading = true;\n                        if (!map.prefix) {\n                            //No reason to keep looking for unfinished\n                            //loading. If the only stillLoading is a\n                            //plugin resource though, keep going,\n                            //because it may be that a plugin resource\n                            //is waiting on a non-plugin cycle.\n                            return (needCycleCheck = false);\n                        }\n                    }\n                }\n            });\n\n            if (expired && noLoads.length) {\n                //If wait time expired, throw error of unloaded modules.\n                err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);\n                err.contextName = context.contextName;\n                return onError(err);\n            }\n\n            //Not expired, check for a cycle.\n            if (needCycleCheck) {\n                each(reqCalls, function (mod) {\n                    breakCycle(mod, {}, {});\n                });\n            }\n\n            //If still waiting on loads, and the waiting load is something\n            //other than a plugin resource, or there are still outstanding\n            //scripts, then just try back later.\n            if ((!expired || usingPathFallback) && stillLoading) {\n                //Something is still waiting to load. Wait for it, but only\n                //if a timeout is not already in effect.\n                if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {\n                    checkLoadedTimeoutId = setTimeout(function () {\n                        checkLoadedTimeoutId = 0;\n                        checkLoaded();\n                    }, 50);\n                }\n            }\n\n            inCheckLoaded = false;\n        }\n\n        Module = function (map) {\n            this.events = getOwn(undefEvents, map.id) || {};\n            this.map = map;\n            this.shim = getOwn(config.shim, map.id);\n            this.depExports = [];\n            this.depMaps = [];\n            this.depMatched = [];\n            this.pluginMaps = {};\n            this.depCount = 0;\n\n            /* this.exports this.factory\n               this.depMaps = [],\n               this.enabled, this.fetched\n            */\n        };\n\n        Module.prototype = {\n            init: function (depMaps, factory, errback, options) {\n                options = options || {};\n\n                //Do not do more inits if already done. Can happen if there\n                //are multiple define calls for the same module. That is not\n                //a normal, common case, but it is also not unexpected.\n                if (this.inited) {\n                    return;\n                }\n\n                this.factory = factory;\n\n                if (errback) {\n                    //Register for errors on this module.\n                    this.on('error', errback);\n                } else if (this.events.error) {\n                    //If no errback already, but there are error listeners\n                    //on this module, set up an errback to pass to the deps.\n                    errback = bind(this, function (err) {\n                        this.emit('error', err);\n                    });\n                }\n\n                //Do a copy of the dependency array, so that\n                //source inputs are not modified. For example\n                //\"shim\" deps are passed in here directly, and\n                //doing a direct modification of the depMaps array\n                //would affect that config.\n                this.depMaps = depMaps && depMaps.slice(0);\n\n                this.errback = errback;\n\n                //Indicate this module has be initialized\n                this.inited = true;\n\n                this.ignore = options.ignore;\n\n                //Could have option to init this module in enabled mode,\n                //or could have been previously marked as enabled. However,\n                //the dependencies are not known until init is called. So\n                //if enabled previously, now trigger dependencies as enabled.\n                if (options.enabled || this.enabled) {\n                    //Enable this module and dependencies.\n                    //Will call this.check()\n                    this.enable();\n                } else {\n                    this.check();\n                }\n            },\n\n            defineDep: function (i, depExports) {\n                //Because of cycles, defined callback for a given\n                //export can be called more than once.\n                if (!this.depMatched[i]) {\n                    this.depMatched[i] = true;\n                    this.depCount -= 1;\n                    this.depExports[i] = depExports;\n                }\n            },\n\n            fetch: function () {\n                if (this.fetched) {\n                    return;\n                }\n                this.fetched = true;\n\n                context.startTime = (new Date()).getTime();\n\n                var map = this.map;\n\n                //If the manager is for a plugin managed resource,\n                //ask the plugin to load it now.\n                if (this.shim) {\n                    context.makeRequire(this.map, {\n                        enableBuildCallback: true\n                    })(this.shim.deps || [], bind(this, function () {\n                        return map.prefix ? this.callPlugin() : this.load();\n                    }));\n                } else {\n                    //Regular dependency.\n                    return map.prefix ? this.callPlugin() : this.load();\n                }\n            },\n\n            load: function () {\n                var url = this.map.url;\n\n                //Regular dependency.\n                if (!urlFetched[url]) {\n                    urlFetched[url] = true;\n                    context.load(this.map.id, url);\n                }\n            },\n\n            /**\n             * Checks if the module is ready to define itself, and if so,\n             * define it.\n             */\n            check: function () {\n                if (!this.enabled || this.enabling) {\n                    return;\n                }\n\n                var err, cjsModule,\n                    id = this.map.id,\n                    depExports = this.depExports,\n                    exports = this.exports,\n                    factory = this.factory;\n\n                if (!this.inited) {\n                    this.fetch();\n                } else if (this.error) {\n                    this.emit('error', this.error);\n                } else if (!this.defining) {\n                    //The factory could trigger another require call\n                    //that would result in checking this module to\n                    //define itself again. If already in the process\n                    //of doing that, skip this work.\n                    this.defining = true;\n\n                    if (this.depCount < 1 && !this.defined) {\n                        if (isFunction(factory)) {\n                            //If there is an error listener, favor passing\n                            //to that instead of throwing an error.\n                            if (this.events.error) {\n                                try {\n                                    exports = context.execCb(id, factory, depExports, exports);\n                                } catch (e) {\n                                    err = e;\n                                }\n                            } else {\n                                exports = context.execCb(id, factory, depExports, exports);\n                            }\n\n                            if (this.map.isDefine) {\n                                //If setting exports via 'module' is in play,\n                                //favor that over return value and exports. After that,\n                                //favor a non-undefined return value over exports use.\n                                cjsModule = this.module;\n                                if (cjsModule &&\n                                        cjsModule.exports !== undefined &&\n                                        //Make sure it is not already the exports value\n                                        cjsModule.exports !== this.exports) {\n                                    exports = cjsModule.exports;\n                                } else if (exports === undefined && this.usingExports) {\n                                    //exports already set the defined value.\n                                    exports = this.exports;\n                                }\n                            }\n\n                            if (err) {\n                                err.requireMap = this.map;\n                                err.requireModules = [this.map.id];\n                                err.requireType = 'define';\n                                return onError((this.error = err));\n                            }\n\n                        } else {\n                            //Just a literal value\n                            exports = factory;\n                        }\n\n                        this.exports = exports;\n\n                        if (this.map.isDefine && !this.ignore) {\n                            defined[id] = exports;\n\n                            if (req.onResourceLoad) {\n                                req.onResourceLoad(context, this.map, this.depMaps);\n                            }\n                        }\n\n                        //Clean up\n                        cleanRegistry(id);\n\n                        this.defined = true;\n                    }\n\n                    //Finished the define stage. Allow calling check again\n                    //to allow define notifications below in the case of a\n                    //cycle.\n                    this.defining = false;\n\n                    if (this.defined && !this.defineEmitted) {\n                        this.defineEmitted = true;\n                        this.emit('defined', this.exports);\n                        this.defineEmitComplete = true;\n                    }\n\n                }\n            },\n\n            callPlugin: function () {\n                var map = this.map,\n                    id = map.id,\n                    //Map already normalized the prefix.\n                    pluginMap = makeModuleMap(map.prefix);\n\n                //Mark this as a dependency for this plugin, so it\n                //can be traced for cycles.\n                this.depMaps.push(pluginMap);\n\n                on(pluginMap, 'defined', bind(this, function (plugin) {\n                    var load, normalizedMap, normalizedMod,\n                        name = this.map.name,\n                        parentName = this.map.parentMap ? this.map.parentMap.name : null,\n                        localRequire = context.makeRequire(map.parentMap, {\n                            enableBuildCallback: true\n                        });\n\n                    //If current map is not normalized, wait for that\n                    //normalized name to load instead of continuing.\n                    if (this.map.unnormalized) {\n                        //Normalize the ID if the plugin allows it.\n                        if (plugin.normalize) {\n                            name = plugin.normalize(name, function (name) {\n                                return normalize(name, parentName, true);\n                            }) || '';\n                        }\n\n                        //prefix and name should already be normalized, no need\n                        //for applying map config again either.\n                        normalizedMap = makeModuleMap(map.prefix + '!' + name,\n                                                      this.map.parentMap);\n                        on(normalizedMap,\n                            'defined', bind(this, function (value) {\n                                this.init([], function () { return value; }, null, {\n                                    enabled: true,\n                                    ignore: true\n                                });\n                            }));\n\n                        normalizedMod = getOwn(registry, normalizedMap.id);\n                        if (normalizedMod) {\n                            //Mark this as a dependency for this plugin, so it\n                            //can be traced for cycles.\n                            this.depMaps.push(normalizedMap);\n\n                            if (this.events.error) {\n                                normalizedMod.on('error', bind(this, function (err) {\n                                    this.emit('error', err);\n                                }));\n                            }\n                            normalizedMod.enable();\n                        }\n\n                        return;\n                    }\n\n                    load = bind(this, function (value) {\n                        this.init([], function () { return value; }, null, {\n                            enabled: true\n                        });\n                    });\n\n                    load.error = bind(this, function (err) {\n                        this.inited = true;\n                        this.error = err;\n                        err.requireModules = [id];\n\n                        //Remove temp unnormalized modules for this module,\n                        //since they will never be resolved otherwise now.\n                        eachProp(registry, function (mod) {\n                            if (mod.map.id.indexOf(id + '_unnormalized') === 0) {\n                                cleanRegistry(mod.map.id);\n                            }\n                        });\n\n                        onError(err);\n                    });\n\n                    //Allow plugins to load other code without having to know the\n                    //context or how to 'complete' the load.\n                    load.fromText = bind(this, function (text, textAlt) {\n                        /*jslint evil: true */\n                        var moduleName = map.name,\n                            moduleMap = makeModuleMap(moduleName),\n                            hasInteractive = useInteractive;\n\n                        //As of 2.1.0, support just passing the text, to reinforce\n                        //fromText only being called once per resource. Still\n                        //support old style of passing moduleName but discard\n                        //that moduleName in favor of the internal ref.\n                        if (textAlt) {\n                            text = textAlt;\n                        }\n\n                        //Turn off interactive script matching for IE for any define\n                        //calls in the text, then turn it back on at the end.\n                        if (hasInteractive) {\n                            useInteractive = false;\n                        }\n\n                        //Prime the system by creating a module instance for\n                        //it.\n                        getModule(moduleMap);\n\n                        //Transfer any config to this other module.\n                        if (hasProp(config.config, id)) {\n                            config.config[moduleName] = config.config[id];\n                        }\n\n                        try {\n                            req.exec(text);\n                        } catch (e) {\n                            return onError(makeError('fromtexteval',\n                                             'fromText eval for ' + id +\n                                            ' failed: ' + e,\n                                             e,\n                                             [id]));\n                        }\n\n                        if (hasInteractive) {\n                            useInteractive = true;\n                        }\n\n                        //Mark this as a dependency for the plugin\n                        //resource\n                        this.depMaps.push(moduleMap);\n\n                        //Support anonymous modules.\n                        context.completeLoad(moduleName);\n\n                        //Bind the value of that module to the value for this\n                        //resource ID.\n                        localRequire([moduleName], load);\n                    });\n\n                    //Use parentName here since the plugin's name is not reliable,\n                    //could be some weird string with no path that actually wants to\n                    //reference the parentName's path.\n                    plugin.load(map.name, localRequire, load, config);\n                }));\n\n                context.enable(pluginMap, this);\n                this.pluginMaps[pluginMap.id] = pluginMap;\n            },\n\n            enable: function () {\n                enabledRegistry[this.map.id] = this;\n                this.enabled = true;\n\n                //Set flag mentioning that the module is enabling,\n                //so that immediate calls to the defined callbacks\n                //for dependencies do not trigger inadvertent load\n                //with the depCount still being zero.\n                this.enabling = true;\n\n                //Enable each dependency\n                each(this.depMaps, bind(this, function (depMap, i) {\n                    var id, mod, handler;\n\n                    if (typeof depMap === 'string') {\n                        //Dependency needs to be converted to a depMap\n                        //and wired up to this module.\n                        depMap = makeModuleMap(depMap,\n                                               (this.map.isDefine ? this.map : this.map.parentMap),\n                                               false,\n                                               !this.skipMap);\n                        this.depMaps[i] = depMap;\n\n                        handler = getOwn(handlers, depMap.id);\n\n                        if (handler) {\n                            this.depExports[i] = handler(this);\n                            return;\n                        }\n\n                        this.depCount += 1;\n\n                        on(depMap, 'defined', bind(this, function (depExports) {\n                            this.defineDep(i, depExports);\n                            this.check();\n                        }));\n\n                        if (this.errback) {\n                            on(depMap, 'error', this.errback);\n                        }\n                    }\n\n                    id = depMap.id;\n                    mod = registry[id];\n\n                    //Skip special modules like 'require', 'exports', 'module'\n                    //Also, don't call enable if it is already enabled,\n                    //important in circular dependency cases.\n                    if (!hasProp(handlers, id) && mod && !mod.enabled) {\n                        context.enable(depMap, this);\n                    }\n                }));\n\n                //Enable each plugin that is used in\n                //a dependency\n                eachProp(this.pluginMaps, bind(this, function (pluginMap) {\n                    var mod = getOwn(registry, pluginMap.id);\n                    if (mod && !mod.enabled) {\n                        context.enable(pluginMap, this);\n                    }\n                }));\n\n                this.enabling = false;\n\n                this.check();\n            },\n\n            on: function (name, cb) {\n                var cbs = this.events[name];\n                if (!cbs) {\n                    cbs = this.events[name] = [];\n                }\n                cbs.push(cb);\n            },\n\n            emit: function (name, evt) {\n                each(this.events[name], function (cb) {\n                    cb(evt);\n                });\n                if (name === 'error') {\n                    //Now that the error handler was triggered, remove\n                    //the listeners, since this broken Module instance\n                    //can stay around for a while in the registry.\n                    delete this.events[name];\n                }\n            }\n        };\n\n        function callGetModule(args) {\n            //Skip modules already defined.\n            if (!hasProp(defined, args[0])) {\n                getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);\n            }\n        }\n\n        function removeListener(node, func, name, ieName) {\n            //Favor detachEvent because of IE9\n            //issue, see attachEvent/addEventListener comment elsewhere\n            //in this file.\n            if (node.detachEvent && !isOpera) {\n                //Probably IE. If not it will throw an error, which will be\n                //useful to know.\n                if (ieName) {\n                    node.detachEvent(ieName, func);\n                }\n            } else {\n                node.removeEventListener(name, func, false);\n            }\n        }\n\n        /**\n         * Given an event from a script node, get the requirejs info from it,\n         * and then removes the event listeners on the node.\n         * @param {Event} evt\n         * @returns {Object}\n         */\n        function getScriptData(evt) {\n            //Using currentTarget instead of target for Firefox 2.0's sake. Not\n            //all old browsers will be supported, but this one was easy enough\n            //to support and still makes sense.\n            var node = evt.currentTarget || evt.srcElement;\n\n            //Remove the listeners once here.\n            removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');\n            removeListener(node, context.onScriptError, 'error');\n\n            return {\n                node: node,\n                id: node && node.getAttribute('data-requiremodule')\n            };\n        }\n\n        function intakeDefines() {\n            var args;\n\n            //Any defined modules in the global queue, intake them now.\n            takeGlobalQueue();\n\n            //Make sure any remaining defQueue items get properly processed.\n            while (defQueue.length) {\n                args = defQueue.shift();\n                if (args[0] === null) {\n                    return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));\n                } else {\n                    //args are id, deps, factory. Should be normalized by the\n                    //define() function.\n                    callGetModule(args);\n                }\n            }\n        }\n\n        context = {\n            config: config,\n            contextName: contextName,\n            registry: registry,\n            defined: defined,\n            urlFetched: urlFetched,\n            defQueue: defQueue,\n            Module: Module,\n            makeModuleMap: makeModuleMap,\n            nextTick: req.nextTick,\n            onError: onError,\n\n            /**\n             * Set a configuration for the context.\n             * @param {Object} cfg config object to integrate.\n             */\n            configure: function (cfg) {\n                //Make sure the baseUrl ends in a slash.\n                if (cfg.baseUrl) {\n                    if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {\n                        cfg.baseUrl += '/';\n                    }\n                }\n\n                //Save off the paths and packages since they require special processing,\n                //they are additive.\n                var pkgs = config.pkgs,\n                    shim = config.shim,\n                    objs = {\n                        paths: true,\n                        config: true,\n                        map: true\n                    };\n\n                eachProp(cfg, function (value, prop) {\n                    if (objs[prop]) {\n                        if (prop === 'map') {\n                            if (!config.map) {\n                                config.map = {};\n                            }\n                            mixin(config[prop], value, true, true);\n                        } else {\n                            mixin(config[prop], value, true);\n                        }\n                    } else {\n                        config[prop] = value;\n                    }\n                });\n\n                //Merge shim\n                if (cfg.shim) {\n                    eachProp(cfg.shim, function (value, id) {\n                        //Normalize the structure\n                        if (isArray(value)) {\n                            value = {\n                                deps: value\n                            };\n                        }\n                        if ((value.exports || value.init) && !value.exportsFn) {\n                            value.exportsFn = context.makeShimExports(value);\n                        }\n                        shim[id] = value;\n                    });\n                    config.shim = shim;\n                }\n\n                //Adjust packages if necessary.\n                if (cfg.packages) {\n                    each(cfg.packages, function (pkgObj) {\n                        var location;\n\n                        pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;\n                        location = pkgObj.location;\n\n                        //Create a brand new object on pkgs, since currentPackages can\n                        //be passed in again, and config.pkgs is the internal transformed\n                        //state for all package configs.\n                        pkgs[pkgObj.name] = {\n                            name: pkgObj.name,\n                            location: location || pkgObj.name,\n                            //Remove leading dot in main, so main paths are normalized,\n                            //and remove any trailing .js, since different package\n                            //envs have different conventions: some use a module name,\n                            //some use a file name.\n                            main: (pkgObj.main || 'main')\n                                  .replace(currDirRegExp, '')\n                                  .replace(jsSuffixRegExp, '')\n                        };\n                    });\n\n                    //Done with modifications, assing packages back to context config\n                    config.pkgs = pkgs;\n                }\n\n                //If there are any \"waiting to execute\" modules in the registry,\n                //update the maps for them, since their info, like URLs to load,\n                //may have changed.\n                eachProp(registry, function (mod, id) {\n                    //If module already has init called, since it is too\n                    //late to modify them, and ignore unnormalized ones\n                    //since they are transient.\n                    if (!mod.inited && !mod.map.unnormalized) {\n                        mod.map = makeModuleMap(id);\n                    }\n                });\n\n                //If a deps array or a config callback is specified, then call\n                //require with those args. This is useful when require is defined as a\n                //config object before require.js is loaded.\n                if (cfg.deps || cfg.callback) {\n                    context.require(cfg.deps || [], cfg.callback);\n                }\n            },\n\n            makeShimExports: function (value) {\n                function fn() {\n                    var ret;\n                    if (value.init) {\n                        ret = value.init.apply(global, arguments);\n                    }\n                    return ret || (value.exports && getGlobal(value.exports));\n                }\n                return fn;\n            },\n\n            makeRequire: function (relMap, options) {\n                options = options || {};\n\n                function localRequire(deps, callback, errback) {\n                    var id, map, requireMod;\n\n                    if (options.enableBuildCallback && callback && isFunction(callback)) {\n                        callback.__requireJsBuild = true;\n                    }\n\n                    if (typeof deps === 'string') {\n                        if (isFunction(callback)) {\n                            //Invalid call\n                            return onError(makeError('requireargs', 'Invalid require call'), errback);\n                        }\n\n                        //If require|exports|module are requested, get the\n                        //value for them from the special handlers. Caveat:\n                        //this only works while module is being defined.\n                        if (relMap && hasProp(handlers, deps)) {\n                            return handlers[deps](registry[relMap.id]);\n                        }\n\n                        //Synchronous access to one module. If require.get is\n                        //available (as in the Node adapter), prefer that.\n                        if (req.get) {\n                            return req.get(context, deps, relMap, localRequire);\n                        }\n\n                        //Normalize module name, if it contains . or ..\n                        map = makeModuleMap(deps, relMap, false, true);\n                        id = map.id;\n\n                        if (!hasProp(defined, id)) {\n                            return onError(makeError('notloaded', 'Module name \"' +\n                                        id +\n                                        '\" has not been loaded yet for context: ' +\n                                        contextName +\n                                        (relMap ? '' : '. Use require([])')));\n                        }\n                        return defined[id];\n                    }\n\n                    //Grab defines waiting in the global queue.\n                    intakeDefines();\n\n                    //Mark all the dependencies as needing to be loaded.\n                    context.nextTick(function () {\n                        //Some defines could have been added since the\n                        //require call, collect them.\n                        intakeDefines();\n\n                        requireMod = getModule(makeModuleMap(null, relMap));\n\n                        //Store if map config should be applied to this require\n                        //call for dependencies.\n                        requireMod.skipMap = options.skipMap;\n\n                        requireMod.init(deps, callback, errback, {\n                            enabled: true\n                        });\n\n                        checkLoaded();\n                    });\n\n                    return localRequire;\n                }\n\n                mixin(localRequire, {\n                    isBrowser: isBrowser,\n\n                    /**\n                     * Converts a module name + .extension into an URL path.\n                     * *Requires* the use of a module name. It does not support using\n                     * plain URLs like nameToUrl.\n                     */\n                    toUrl: function (moduleNamePlusExt) {\n                        var ext,\n                            index = moduleNamePlusExt.lastIndexOf('.'),\n                            segment = moduleNamePlusExt.split('/')[0],\n                            isRelative = segment === '.' || segment === '..';\n\n                        //Have a file extension alias, and it is not the\n                        //dots from a relative path.\n                        if (index !== -1 && (!isRelative || index > 1)) {\n                            ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);\n                            moduleNamePlusExt = moduleNamePlusExt.substring(0, index);\n                        }\n\n                        return context.nameToUrl(normalize(moduleNamePlusExt,\n                                                relMap && relMap.id, true), ext,  true);\n                    },\n\n                    defined: function (id) {\n                        return hasProp(defined, makeModuleMap(id, relMap, false, true).id);\n                    },\n\n                    specified: function (id) {\n                        id = makeModuleMap(id, relMap, false, true).id;\n                        return hasProp(defined, id) || hasProp(registry, id);\n                    }\n                });\n\n                //Only allow undef on top level require calls\n                if (!relMap) {\n                    localRequire.undef = function (id) {\n                        //Bind any waiting define() calls to this context,\n                        //fix for #408\n                        takeGlobalQueue();\n\n                        var map = makeModuleMap(id, relMap, true),\n                            mod = getOwn(registry, id);\n\n                        delete defined[id];\n                        delete urlFetched[map.url];\n                        delete undefEvents[id];\n\n                        if (mod) {\n                            //Hold on to listeners in case the\n                            //module will be attempted to be reloaded\n                            //using a different config.\n                            if (mod.events.defined) {\n                                undefEvents[id] = mod.events;\n                            }\n\n                            cleanRegistry(id);\n                        }\n                    };\n                }\n\n                return localRequire;\n            },\n\n            /**\n             * Called to enable a module if it is still in the registry\n             * awaiting enablement. A second arg, parent, the parent module,\n             * is passed in for context, when this method is overriden by\n             * the optimizer. Not shown here to keep code compact.\n             */\n            enable: function (depMap) {\n                var mod = getOwn(registry, depMap.id);\n                if (mod) {\n                    getModule(depMap).enable();\n                }\n            },\n\n            /**\n             * Internal method used by environment adapters to complete a load event.\n             * A load event could be a script load or just a load pass from a synchronous\n             * load call.\n             * @param {String} moduleName the name of the module to potentially complete.\n             */\n            completeLoad: function (moduleName) {\n                var found, args, mod,\n                    shim = getOwn(config.shim, moduleName) || {},\n                    shExports = shim.exports;\n\n                takeGlobalQueue();\n\n                while (defQueue.length) {\n                    args = defQueue.shift();\n                    if (args[0] === null) {\n                        args[0] = moduleName;\n                        //If already found an anonymous module and bound it\n                        //to this name, then this is some other anon module\n                        //waiting for its completeLoad to fire.\n                        if (found) {\n                            break;\n                        }\n                        found = true;\n                    } else if (args[0] === moduleName) {\n                        //Found matching define call for this script!\n                        found = true;\n                    }\n\n                    callGetModule(args);\n                }\n\n                //Do this after the cycle of callGetModule in case the result\n                //of those calls/init calls changes the registry.\n                mod = getOwn(registry, moduleName);\n\n                if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {\n                    if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {\n                        if (hasPathFallback(moduleName)) {\n                            return;\n                        } else {\n                            return onError(makeError('nodefine',\n                                             'No define call for ' + moduleName,\n                                             null,\n                                             [moduleName]));\n                        }\n                    } else {\n                        //A script that does not call define(), so just simulate\n                        //the call for it.\n                        callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);\n                    }\n                }\n\n                checkLoaded();\n            },\n\n            /**\n             * Converts a module name to a file path. Supports cases where\n             * moduleName may actually be just an URL.\n             * Note that it **does not** call normalize on the moduleName,\n             * it is assumed to have already been normalized. This is an\n             * internal API, not a public one. Use toUrl for the public API.\n             */\n            nameToUrl: function (moduleName, ext, skipExt) {\n                var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,\n                    parentPath;\n\n                //If a colon is in the URL, it indicates a protocol is used and it is just\n                //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)\n                //or ends with .js, then assume the user meant to use an url and not a module id.\n                //The slash is important for protocol-less URLs as well as full paths.\n                if (req.jsExtRegExp.test(moduleName)) {\n                    //Just a plain path, not module name lookup, so just return it.\n                    //Add extension if it is included. This is a bit wonky, only non-.js things pass\n                    //an extension, this method probably needs to be reworked.\n                    url = moduleName + (ext || '');\n                } else {\n                    //A module that needs to be converted to a path.\n                    paths = config.paths;\n                    pkgs = config.pkgs;\n\n                    syms = moduleName.split('/');\n                    //For each module name segment, see if there is a path\n                    //registered for it. Start with most specific name\n                    //and work up from it.\n                    for (i = syms.length; i > 0; i -= 1) {\n                        parentModule = syms.slice(0, i).join('/');\n                        pkg = getOwn(pkgs, parentModule);\n                        parentPath = getOwn(paths, parentModule);\n                        if (parentPath) {\n                            //If an array, it means there are a few choices,\n                            //Choose the one that is desired\n                            if (isArray(parentPath)) {\n                                parentPath = parentPath[0];\n                            }\n                            syms.splice(0, i, parentPath);\n                            break;\n                        } else if (pkg) {\n                            //If module name is just the package name, then looking\n                            //for the main module.\n                            if (moduleName === pkg.name) {\n                                pkgPath = pkg.location + '/' + pkg.main;\n                            } else {\n                                pkgPath = pkg.location;\n                            }\n                            syms.splice(0, i, pkgPath);\n                            break;\n                        }\n                    }\n\n                    //Join the path parts together, then figure out if baseUrl is needed.\n                    url = syms.join('/');\n                    url += (ext || (/\\?/.test(url) || skipExt ? '' : '.js'));\n                    url = (url.charAt(0) === '/' || url.match(/^[\\w\\+\\.\\-]+:/) ? '' : config.baseUrl) + url;\n                }\n\n                return config.urlArgs ? url +\n                                        ((url.indexOf('?') === -1 ? '?' : '&') +\n                                         config.urlArgs) : url;\n            },\n\n            //Delegates to req.load. Broken out as a separate function to\n            //allow overriding in the optimizer.\n            load: function (id, url) {\n                req.load(context, id, url);\n            },\n\n            /**\n             * Executes a module callack function. Broken out as a separate function\n             * solely to allow the build system to sequence the files in the built\n             * layer in the right sequence.\n             *\n             * @private\n             */\n            execCb: function (name, callback, args, exports) {\n                return callback.apply(exports, args);\n            },\n\n            /**\n             * callback for script loads, used to check status of loading.\n             *\n             * @param {Event} evt the event from the browser for the script\n             * that was loaded.\n             */\n            onScriptLoad: function (evt) {\n                //Using currentTarget instead of target for Firefox 2.0's sake. Not\n                //all old browsers will be supported, but this one was easy enough\n                //to support and still makes sense.\n                if (evt.type === 'load' ||\n                        (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {\n                    //Reset interactive script so a script node is not held onto for\n                    //to long.\n                    interactiveScript = null;\n\n                    //Pull out the name of the module and the context.\n                    var data = getScriptData(evt);\n                    context.completeLoad(data.id);\n                }\n            },\n\n            /**\n             * Callback for script errors.\n             */\n            onScriptError: function (evt) {\n                var data = getScriptData(evt);\n                if (!hasPathFallback(data.id)) {\n                    return onError(makeError('scripterror', 'Script error', evt, [data.id]));\n                }\n            }\n        };\n\n        context.require = context.makeRequire();\n        return context;\n    }\n\n    /**\n     * Main entry point.\n     *\n     * If the only argument to require is a string, then the module that\n     * is represented by that string is fetched for the appropriate context.\n     *\n     * If the first argument is an array, then it will be treated as an array\n     * of dependency string names to fetch. An optional function callback can\n     * be specified to execute when all of those dependencies are available.\n     *\n     * Make a local req variable to help Caja compliance (it assumes things\n     * on a require that are not standardized), and to give a short\n     * name for minification/local scope use.\n     */\n    req = requirejs = function (deps, callback, errback, optional) {\n\n        //Find the right context, use default\n        var context, config,\n            contextName = defContextName;\n\n        // Determine if have config object in the call.\n        if (!isArray(deps) && typeof deps !== 'string') {\n            // deps is a config object\n            config = deps;\n            if (isArray(callback)) {\n                // Adjust args if there are dependencies\n                deps = callback;\n                callback = errback;\n                errback = optional;\n            } else {\n                deps = [];\n            }\n        }\n\n        if (config && config.context) {\n            contextName = config.context;\n        }\n\n        context = getOwn(contexts, contextName);\n        if (!context) {\n            context = contexts[contextName] = req.s.newContext(contextName);\n        }\n\n        if (config) {\n            context.configure(config);\n        }\n\n        return context.require(deps, callback, errback);\n    };\n\n    /**\n     * Support require.config() to make it easier to cooperate with other\n     * AMD loaders on globally agreed names.\n     */\n    req.config = function (config) {\n        return req(config);\n    };\n\n    /**\n     * Execute something after the current tick\n     * of the event loop. Override for other envs\n     * that have a better solution than setTimeout.\n     * @param  {Function} fn function to execute later.\n     */\n    req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {\n        setTimeout(fn, 4);\n    } : function (fn) { fn(); };\n\n    /**\n     * Export require as a global, but only if it does not already exist.\n     */\n    if (!require) {\n        require = req;\n    }\n\n    req.version = version;\n\n    //Used to filter out dependencies that are already paths.\n    req.jsExtRegExp = /^\\/|:|\\?|\\.js$/;\n    req.isBrowser = isBrowser;\n    s = req.s = {\n        contexts: contexts,\n        newContext: newContext\n    };\n\n    //Create default context.\n    req({});\n\n    //Exports some context-sensitive methods on global require.\n    each([\n        'toUrl',\n        'undef',\n        'defined',\n        'specified'\n    ], function (prop) {\n        //Reference from contexts instead of early binding to default context,\n        //so that during builds, the latest instance of the default context\n        //with its config gets used.\n        req[prop] = function () {\n            var ctx = contexts[defContextName];\n            return ctx.require[prop].apply(ctx, arguments);\n        };\n    });\n\n    if (isBrowser) {\n        head = s.head = document.getElementsByTagName('head')[0];\n        //If BASE tag is in play, using appendChild is a problem for IE6.\n        //When that browser dies, this can be removed. Details in this jQuery bug:\n        //http://dev.jquery.com/ticket/2709\n        baseElement = document.getElementsByTagName('base')[0];\n        if (baseElement) {\n            head = s.head = baseElement.parentNode;\n        }\n    }\n\n    /**\n     * Any errors that require explicitly generates will be passed to this\n     * function. Intercept/override it if you want custom error handling.\n     * @param {Error} err the error object.\n     */\n    req.onError = function (err) {\n        throw err;\n    };\n\n    /**\n     * Does the request to load a module for the browser case.\n     * Make this a separate function to allow other environments\n     * to override it.\n     *\n     * @param {Object} context the require context to find state.\n     * @param {String} moduleName the name of the module.\n     * @param {Object} url the URL to the module.\n     */\n    req.load = function (context, moduleName, url) {\n        var config = (context && context.config) || {},\n            node;\n        if (isBrowser) {\n            //In the browser so use a script tag\n            node = config.xhtml ?\n                    document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :\n                    document.createElement('script');\n            node.type = config.scriptType || 'text/javascript';\n            node.charset = 'utf-8';\n            node.async = true;\n\n            node.setAttribute('data-requirecontext', context.contextName);\n            node.setAttribute('data-requiremodule', moduleName);\n\n            //Set up load listener. Test attachEvent first because IE9 has\n            //a subtle issue in its addEventListener and script onload firings\n            //that do not match the behavior of all other browsers with\n            //addEventListener support, which fire the onload event for a\n            //script right after the script execution. See:\n            //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution\n            //UNFORTUNATELY Opera implements attachEvent but does not follow the script\n            //script execution mode.\n            if (node.attachEvent &&\n                    //Check if node.attachEvent is artificially added by custom script or\n                    //natively supported by browser\n                    //read https://github.com/jrburke/requirejs/issues/187\n                    //if we can NOT find [native code] then it must NOT natively supported.\n                    //in IE8, node.attachEvent does not have toString()\n                    //Note the test for \"[native code\" with no closing brace, see:\n                    //https://github.com/jrburke/requirejs/issues/273\n                    !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&\n                    !isOpera) {\n                //Probably IE. IE (at least 6-8) do not fire\n                //script onload right after executing the script, so\n                //we cannot tie the anonymous define call to a name.\n                //However, IE reports the script as being in 'interactive'\n                //readyState at the time of the define call.\n                useInteractive = true;\n\n                node.attachEvent('onreadystatechange', context.onScriptLoad);\n                //It would be great to add an error handler here to catch\n                //404s in IE9+. However, onreadystatechange will fire before\n                //the error handler, so that does not help. If addEventListener\n                //is used, then IE will fire error before load, but we cannot\n                //use that pathway given the connect.microsoft.com issue\n                //mentioned above about not doing the 'script execute,\n                //then fire the script load event listener before execute\n                //next script' that other browsers do.\n                //Best hope: IE10 fixes the issues,\n                //and then destroys all installs of IE 6-9.\n                //node.attachEvent('onerror', context.onScriptError);\n            } else {\n                node.addEventListener('load', context.onScriptLoad, false);\n                node.addEventListener('error', context.onScriptError, false);\n            }\n            node.src = url;\n\n            //For some cache cases in IE 6-8, the script executes before the end\n            //of the appendChild execution, so to tie an anonymous define\n            //call to the module name (which is stored on the node), hold on\n            //to a reference to this node, but clear after the DOM insertion.\n            currentlyAddingScript = node;\n            if (baseElement) {\n                head.insertBefore(node, baseElement);\n            } else {\n                head.appendChild(node);\n            }\n            currentlyAddingScript = null;\n\n            return node;\n        } else if (isWebWorker) {\n            try {\n                //In a web worker, use importScripts. This is not a very\n                //efficient use of importScripts, importScripts will block until\n                //its script is downloaded and evaluated. However, if web workers\n                //are in play, the expectation that a build has been done so that\n                //only one script needs to be loaded anyway. This may need to be\n                //reevaluated if other use cases become common.\n                importScripts(url);\n\n                //Account for anonymous modules\n                context.completeLoad(moduleName);\n            } catch (e) {\n                context.onError(makeError('importscripts',\n                                'importScripts failed for ' +\n                                    moduleName + ' at ' + url,\n                                e,\n                                [moduleName]));\n            }\n        }\n    };\n\n    function getInteractiveScript() {\n        if (interactiveScript && interactiveScript.readyState === 'interactive') {\n            return interactiveScript;\n        }\n\n        eachReverse(scripts(), function (script) {\n            if (script.readyState === 'interactive') {\n                return (interactiveScript = script);\n            }\n        });\n        return interactiveScript;\n    }\n\n    //Look for a data-main script attribute, which could also adjust the baseUrl.\n    if (isBrowser) {\n        //Figure out baseUrl. Get it from the script tag with require.js in it.\n        eachReverse(scripts(), function (script) {\n            //Set the 'head' where we can append children by\n            //using the script's parent.\n            if (!head) {\n                head = script.parentNode;\n            }\n\n            //Look for a data-main attribute to set main script for the page\n            //to load. If it is there, the path to data main becomes the\n            //baseUrl, if it is not already set.\n            dataMain = script.getAttribute('data-main');\n            if (dataMain) {\n                //Set final baseUrl if there is not already an explicit one.\n                if (!cfg.baseUrl) {\n                    //Pull off the directory of data-main for use as the\n                    //baseUrl.\n                    src = dataMain.split('/');\n                    mainScript = src.pop();\n                    subPath = src.length ? src.join('/')  + '/' : './';\n\n                    cfg.baseUrl = subPath;\n                    dataMain = mainScript;\n                }\n\n                //Strip off any trailing .js since dataMain is now\n                //like a module name.\n                dataMain = dataMain.replace(jsSuffixRegExp, '');\n\n                //Put the data-main script in the files to load.\n                cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];\n\n                return true;\n            }\n        });\n    }\n\n    /**\n     * The function that handles definitions of modules. Differs from\n     * require() in that a string for the module should be the first argument,\n     * and the function to execute after dependencies are loaded should\n     * return a value to define the module corresponding to the first argument's\n     * name.\n     */\n    define = function (name, deps, callback) {\n        var node, context;\n\n        //Allow for anonymous modules\n        if (typeof name !== 'string') {\n            //Adjust args appropriately\n            callback = deps;\n            deps = name;\n            name = null;\n        }\n\n        //This module may not have dependencies\n        if (!isArray(deps)) {\n            callback = deps;\n            deps = [];\n        }\n\n        //If no name, and callback is a function, then figure out if it a\n        //CommonJS thing with dependencies.\n        if (!deps.length && isFunction(callback)) {\n            //Remove comments from the callback string,\n            //look for require calls, and pull them into the dependencies,\n            //but only if there are function args.\n            if (callback.length) {\n                callback\n                    .toString()\n                    .replace(commentRegExp, '')\n                    .replace(cjsRequireRegExp, function (match, dep) {\n                        deps.push(dep);\n                    });\n\n                //May be a CommonJS thing even without require calls, but still\n                //could use exports, and module. Avoid doing exports and module\n                //work though if it just needs require.\n                //REQUIRES the function to expect the CommonJS variables in the\n                //order listed below.\n                deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);\n            }\n        }\n\n        //If in IE 6-8 and hit an anonymous define() call, do the interactive\n        //work.\n        if (useInteractive) {\n            node = currentlyAddingScript || getInteractiveScript();\n            if (node) {\n                if (!name) {\n                    name = node.getAttribute('data-requiremodule');\n                }\n                context = contexts[node.getAttribute('data-requirecontext')];\n            }\n        }\n\n        //Always save off evaluating the def call until the script onload handler.\n        //This allows multiple modules to be in a file without prematurely\n        //tracing dependencies, and allows for anonymous module support,\n        //where the module name is not known until the script onload event\n        //occurs. If no context, use the global queue, and get it processed\n        //in the onscript load callback.\n        (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);\n    };\n\n    define.amd = {\n        jQuery: true\n    };\n\n\n    /**\n     * Executes the text. Normally just uses eval, but can be modified\n     * to use a better, environment-specific call. Only used for transpiling\n     * loader plugins, not for plain JS modules.\n     * @param {String} text the text to execute/evaluate.\n     */\n    req.exec = function (text) {\n        /*jslint evil: true */\n        return eval(text);\n    };\n\n    //Set up with config info.\n    req(cfg);\n}(this));\n"
  },
  {
    "path": "src/ComponentInstaller/Util/Filesystem.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Util;\n\nuse Composer\\Util\\Filesystem as BaseFilesystem;\n\n/**\n * Provides basic file system operations.\n */\nclass Filesystem extends BaseFilesystem\n{\n    /**\n     * Performs a recursive-enabled glob search with the given pattern.\n     *\n     * @param string $pattern\n     *   The pattern passed to glob(). If the pattern contains \"**\", then it\n     *   a recursive search will be used.\n     * @param int $flags\n     *   Flags to pass into glob().\n     *\n     * @return mixed\n     *  An array of files that match the recursive pattern given.\n     */\n    public function recursiveGlob($pattern, $flags = 0)\n    {\n        // Perform the glob search.\n        $files = glob($pattern, $flags);\n\n        // Check if this is to be recursive.\n        if (strpos($pattern, '**') !== FALSE) {\n            $dirs = glob(dirname($pattern).DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR|GLOB_NOSORT);\n            if ($dirs) {\n                foreach ($dirs as $dir) {\n                    $files = array_merge($files, $this->recursiveGlob($dir.DIRECTORY_SEPARATOR.basename($pattern), $flags));\n                }\n            }\n        }\n\n        return $files;\n    }\n\n    /**\n     * Performs a recursive glob search for files with the given pattern.\n     *\n     * @param string $pattern\n     *   The pattern passed to glob().\n     * @param int $flags\n     *   Flags to pass into glob().\n     *\n     * @return mixed\n     *  An array of files that match the recursive pattern given.\n     */\n    public function recursiveGlobFiles($pattern, $flags = 0)\n    {\n        $files = $this->recursiveGlob($pattern, $flags);\n\n        return array_filter($files, 'is_file');\n    }\n}\n"
  },
  {
    "path": "src/bootstrap.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nfunction includeIfExists($file)\n{\n    if (file_exists($file)) {\n        /** @noinspection PhpIncludeInspection */\n        return include $file;\n    }\n\n    return null;\n}\n\nif ((!$loader = includeIfExists(__DIR__ . '/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__ . '/../../../autoload.php'))) {\n    die('You must set up the project dependencies, run the following commands:'.PHP_EOL.\n        'curl -s http://getcomposer.org/installer | php'.PHP_EOL.\n        'php composer.phar install'.PHP_EOL);\n}\n\nreturn $loader;\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/InstallerTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace Composer\\Test;\n\nuse ComponentInstaller\\Util\\Filesystem;\nuse Composer\\Test\\Installer\\LibraryInstallerTest;\nuse ComponentInstaller\\Installer;\nuse Composer\\Package\\Loader\\ArrayLoader;\nuse Composer\\Config;\n\n/**\n * Tests registering Component Installer with Composer.\n */\nclass InstallerTest extends LibraryInstallerTest\n{\n    protected $componentDir = 'components';\n\n\t/**\n\t * @var \\Composer\\Config\n\t */\n\tprotected $config;\n\n\t/**\n\t * @var Filesystem\n\t */\n\tprotected $fs;\n\n    /**\n     * {@inheritdoc}\n     */\n    protected function setUp()\n    {\n        // Run through the Library Installer Test set up.\n        parent::setUp();\n\n        // Also be sure to set up the Component directory.\n        $this->componentDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'composer-test-component';\n        $this->ensureDirectoryExistsAndClear($this->componentDir);\n\n        // Merge the component-dir setting in so that it applies correctly.\n        $this->config->merge(array(\n            'config' => array(\n                'component-dir' => $this->componentDir,\n            ),\n        ));\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    protected function tearDown()\n    {\n        $this->fs->removeDirectory($this->componentDir);\n\n        parent::tearDown();\n    }\n\n    /**\n     * Tests that the Installer doesn't create the Component directory.\n     */\n    public function testInstallerCreationShouldNotCreateComponentDirectory()\n    {\n        $this->fs->removeDirectory($this->componentDir);\n        new Installer($this->io, $this->composer);\n        $this->assertFileNotExists($this->componentDir);\n    }\n\n    /**\n     * Test the Installer's support() function.\n     *\n     * @param $type\n     *   The type of library.\n     * @param $expected\n     *   Whether or not the given type is supported by Component Installer.\n     *\n     * @return void\n     *\n     * @dataProvider providerComponentSupports\n     */\n    public function testComponentSupports($type, $expected)\n    {\n        $installer = new Installer($this->io, $this->composer, 'component');\n        $this->assertSame($expected, $installer->supports($type), sprintf('Failed to show support for %s', $type));\n    }\n\n    /**\n     * Data provider for testComponentSupports().\n     *\n     * @see testComponentSupports()\n     */\n    public function providerComponentSupports()\n    {\n        // All package types support having Components.\n        $tests[] = array('component', true);\n        $tests[] = array('all-supported', false);\n\n        return $tests;\n    }\n\n    /**\n     * Tests the Installer's getComponentPath function.\n     *\n     * @param $expected\n     *   The expected install path for the package.\n     * @param $package\n     *   The package to test upon.\n     *\n     * @dataProvider providerGetComponentPath\n     *\n     * @see \\ComponentInstaller\\Installer::getComponentPath()\n     */\n    public function testGetComponentPath($expected, $package) {\n        // Construct the mock objects.\n        $installer = new Installer($this->io, $this->composer, 'component');\n        $loader = new ArrayLoader();\n\n        // Test the results.\n        $result = $installer->getComponentPath($loader->load($package));\n        $this->assertEquals($this->componentDir . DIRECTORY_SEPARATOR . $expected, $result);\n    }\n\n    /**\n     * Data provider for testGetComponentPath().\n     *\n     * @see testGetComponentPath()\n     */\n    public function providerGetComponentPath()\n    {\n        $package = array(\n            'name' => 'foo/bar',\n            'type' => 'component',\n            'version' => '1.0.0',\n        );\n        $tests[] = array('bar', $package);\n\n        $package = array(\n            'name' => 'foo/bar2',\n            'version' => '1.0.0',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'name' => 'foo',\n                ),\n            ),\n        );\n        $tests[] = array('foo', $package);\n\n        return $tests;\n    }\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Process/CopyProcessTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Test\\Process;\n\nuse ComponentInstaller\\Process\\CopyProcess;\n\n/**\n * Tests CopyProcess.\n */\nclass CopyProcessTest extends ProcessTest\n{\n\t/**\n\t * @var CopyProcess\n\t */\n    protected $process;\n\n    public function setUp()\n    {\n        parent::setUp();\n        $this->process = new CopyProcess($this->composer, $this->io);\n    }\n\n    /**\n     * testCopy\n     *\n     * @dataProvider providerCopyStyles\n\t * @param array $packages\n\t * @param array $files\n     */\n    public function testCopyStyles($packages, $files)\n    {\n        // Initialize the process.\n        $this->process->init();\n        $this->process->copy($packages);\n        foreach ($files as $file) {\n            $this->assertFileExists($this->componentDir.'/' . $file, sprintf('Failed to find the destination file: %s', $file));\n        }\n    }\n\n    public function providerCopyStyles()\n    {\n        // Test collecting one style.\n        $package = array(\n            'name' => 'components/package',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.css',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'package/tests/ComponentInstaller/Test/Resources/test.css',\n        ));\n\n        // Test collecting two styles.\n        $package = array(\n            'name' => 'components/packagewithtwostyles',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.css',\n                        'tests/ComponentInstaller/Test/Resources/test2.css',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'packagewithtwostyles/tests/ComponentInstaller/Test/Resources/test.css',\n            'packagewithtwostyles/tests/ComponentInstaller/Test/Resources/test2.css',\n        ));\n\n        // Test collecting a style that doesn't exist.\n        $package = array(\n            'name' => 'components/stylethatdoesnotexist',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.css',\n                        'tests/ComponentInstaller/Test/Resources/test-not-found.css',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'stylethatdoesnotexist/tests/ComponentInstaller/Test/Resources/test.css',\n        ));\n\n        // Test collecting all styles, files and scripts.\n        $package = array(\n            'name' => 'components/allassets',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.css',\n                    ),\n                    'files' => array(\n                        'tests/ComponentInstaller/Test/Resources/img.jpg',\n                        'tests/ComponentInstaller/Test/Resources/img2.jpg',\n                    ),\n                    'scripts' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.js'\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'allassets/tests/ComponentInstaller/Test/Resources/test.css',\n            'allassets/tests/ComponentInstaller/Test/Resources/img.jpg',\n            'allassets/tests/ComponentInstaller/Test/Resources/img2.jpg',\n            'allassets/tests/ComponentInstaller/Test/Resources/test.js',\n        ));\n\n        // Test copying a different component name.\n        $package = array(\n            'name' => 'components/differentcomponentname',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'name' => 'diffname',\n                    'files' => array(\n                        'tests/ComponentInstaller/Test/Resources/img.jpg',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'diffname/tests/ComponentInstaller/Test/Resources/img.jpg',\n        ));\n\n        // Test two different packages.\n        $package = array(\n            'name' => 'components/twopackages1',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'files' => array(\n                        'tests/ComponentInstaller/Test/Resources/img.jpg',\n                    ),\n                ),\n            ),\n        );\n        $package2 = array(\n            'name' => 'components/twopackages2',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'name' => 'twopackages2-diff',\n                    'files' => array(\n                        'tests/ComponentInstaller/Test/Resources/img2.jpg',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package, $package2);\n        $tests[] = array($packages, array(\n            'twopackages1/tests/ComponentInstaller/Test/Resources/img.jpg',\n            'twopackages2-diff/tests/ComponentInstaller/Test/Resources/img2.jpg',\n        ));\n\n        // Test copying an asset with a glob().\n        $package = array(\n            'name' => 'components/differentcomponentname',\n            'version' => '1.2.3',\n            'is-root' => true, // Set the root so that it knows to use the cwd.\n            'extra' => array(\n                'component' => array(\n                    'name' => 'diffname',\n                    'files' => array(\n                        'tests/ComponentInstaller/Test/Resources/*.jpg',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $tests[] = array($packages, array(\n            'diffname/tests/ComponentInstaller/Test/Resources/img.jpg',\n            'diffname/tests/ComponentInstaller/Test/Resources/img2.jpg',\n        ));\n\n        return $tests;\n    }\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Process/ProcessTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Test\\Process;\n\nuse ComponentInstaller\\Process\\Process;\nuse Composer\\Composer;\nuse Composer\\Config;\nuse Composer\\IO\\NullIO;\nuse Composer\\Util\\Filesystem;\nuse Composer\\Installer\\InstallationManager;\nuse Composer\\Installer\\LibraryInstaller;\nuse ComponentInstaller\\Installer;\n\n/**\n * Tests Process.\n */\nclass ProcessTest extends \\PHPUnit_Framework_TestCase\n{\n\t/**\n\t * @var Composer\n\t */\n    protected $composer;\n\n\t/**\n\t * @var Config\n\t */\n    protected $config;\n\n\t/**\n\t * @var NullIO\n\t */\n    protected $io;\n\n\t/**\n\t * @var Filesystem\n\t */\n    protected $filesystem;\n\n\t/**\n\t * @var string\n\t */\n    protected $componentDir;\n\n\t/**\n\t * @var string\n\t */\n    protected $vendorDir;\n\n\t/**\n\t * @var string\n\t */\n    protected $binDir;\n\n\t/**\n\t * @var InstallationManager\n\t */\n    protected $installationManager;\n\n    public function setUp()\n    {\n        $this->filesystem = new Filesystem();\n        $this->composer = new Composer();\n        $this->config = new Config();\n        $this->io = new NullIO();\n\n        $this->componentDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'component-installer-componentDir';\n        $this->vendorDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'component-installer-vendorDir';\n        $this->binDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'component-installer-binDir';\n\n        foreach (array($this->componentDir, $this->vendorDir, $this->binDir) as $dir) {\n            if (is_dir($dir)) {\n                $this->filesystem->removeDirectory($dir);\n            }\n            $this->filesystem->ensureDirectoryExists($dir);\n        }\n        $this->config->merge(array(\n            'config' => array(\n                'vendor-dir' => $this->vendorDir,\n                'component-dir' => $this->componentDir,\n                'bin-dir' => $this->binDir,\n            )\n        ));\n        $this->composer->setConfig($this->config);\n\n        // Set up the Installation Manager.\n        $this->installationManager = new InstallationManager();\n        $this->installationManager->addInstaller(new LibraryInstaller($this->io, $this->composer));\n        $this->installationManager->addInstaller(new Installer($this->io, $this->composer));\n        $this->composer->setInstallationManager($this->installationManager);\n    }\n\n    protected function tearDown()\n    {\n        foreach (array($this->componentDir, $this->vendorDir, $this->binDir) as $dir) {\n            $this->filesystem->removeDirectory($dir);\n        }\n    }\n\n    /**\n     * testGetComponentName\n     *\n     * @dataProvider providerGetComponentName\n\t * @param string $prettyName\n\t * @param array $extra\n\t * @param string $expected\n     */\n    public function testGetComponentName($prettyName, array $extra, $expected)\n    {\n        $process = new Process($this->composer, $this->io);\n        $result = $process->getComponentName($prettyName, array('component' => $extra));\n        $this->assertEquals($result, $expected, sprintf('Fail to get proper component name for %s', $prettyName));\n    }\n\n    /**\n     * Data provider for testGetComponentName.\n     *\n     * @see testGetComponentName()\n     */\n    public function providerGetComponentName()\n    {\n        return array(\n            array('components/jquery', array(), 'jquery'),\n            array('components/jquery', array('name' => 'myownjquery'), 'myownjquery'),\n            array('jquery', array(), 'jquery'),\n        );\n    }\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Process/RequireCssProcessTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Test\\Process;\n\nuse ComponentInstaller\\Process\\RequireCssProcess;\nuse Composer\\Config;\n\n/**\n * Tests RequireCssProcess.\n */\nclass RequireCssProcessTest extends ProcessTest\n{\n\t/**\n\t * @var RequireCssProcess\n\t */\n    protected $process;\n\n    public function setUp()\n    {\n        parent::setUp();\n        $this->process = new RequireCssProcess($this->composer, $this->io);\n    }\n    /**\n     * testPackageStyles\n     *\n     * @dataProvider providerPackageStyles\n\t * @param array $packages\n\t * @param array $config\n\t * @param array $expected\n     */\n    public function testPackageStyles(array $packages, array $config, $expected = null)\n    {\n        $this->composer->getConfig()->merge(array('config' => $config));\n        $this->process->init();\n        $result = $this->process->packageStyles($packages);\n        $this->assertEquals($expected, $result);\n    }\n\n    public function providerPackageStyles()\n    {\n        // Test collecting one style.\n        $package = array(\n            'name' => 'components/package',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.css',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($package);\n        $expected = array(\n            'package' => array(\n                'tests/ComponentInstaller/Test/Resources/test.css' => array(\n                    realpath('tests/ComponentInstaller/Test/Resources/test.css'),\n                ),\n            ),\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test collecting a style that doesn't exist.\n        $package2 = array(\n            'name' => 'components/package2',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test-not-found.css',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($package, $package2);\n        $expected = array(\n            'package' => array(\n                'tests/ComponentInstaller/Test/Resources/test.css' => array(\n                    realpath('tests/ComponentInstaller/Test/Resources/test.css'),\n                )\n            )\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test collecting a style that doesn't exist.\n        $package3 = array(\n            'name' => 'components/package3',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/test2.css',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($package, $package3);\n        $expected = array(\n            'package' => array(\n                'tests/ComponentInstaller/Test/Resources/test.css' => array(\n                    realpath('tests/ComponentInstaller/Test/Resources/test.css'),\n                ),\n            ),\n            'package3' => array(\n                'tests/ComponentInstaller/Test/Resources/test2.css' => array(\n                    realpath('tests/ComponentInstaller/Test/Resources/test2.css'),\n                ),\n            )\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test collecting a style that uses glob().\n        $package = array(\n            'name' => 'components/package4',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'styles' => array(\n                        'tests/ComponentInstaller/Test/Resources/*.css',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($package);\n        $expected = array(\n            'package4' => array(\n                'tests/ComponentInstaller/Test/Resources/*.css' => array(\n                    realpath('tests/ComponentInstaller/Test/Resources/test.css'),\n                    realpath('tests/ComponentInstaller/Test/Resources/test2.css'),\n                )\n            )\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        return $tests;\n    }\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Process/RequireJsProcessTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Test\\Process;\n\nuse ComponentInstaller\\Process\\RequireJsProcess;\nuse Composer\\Config;\n\n/**\n * Tests RequireJsProcess.\n */\nclass RequireJsProcessTest extends ProcessTest\n{\n\t/**\n\t * @var RequireJsProcess\n\t */\n    protected $process;\n\n    public function setUp()\n    {\n        parent::setUp();\n        $this->process = new RequireJsProcess($this->composer, $this->io);\n    }\n\n    /**\n     * testRequireJs\n     *\n     * @dataProvider providerRequireJs\n\t * @param array $json\n\t * @param string $expected\n     */\n    public function testRequireJs(array $json = array(), $expected = '')\n    {\n        $result = $this->process->requireJs($json);\n        $this->assertEquals($expected, $result);\n    }\n\n    public function providerRequireJs()\n    {\n        // Start with a base RequireJS configuration.\n        $js = <<<EOT\nvar components = %s;\nif (typeof require !== \"undefined\" && require.config) {\n    require.config(components);\n} else {\n    var require = components;\n}\nif (typeof exports !== \"undefined\" && typeof module !== \"undefined\") {\n    module.exports = components;\n}\nEOT;\n\n        // Tests a basic configuration.\n        $tests[] = array(\n            array('foo' => 'bar'),\n            sprintf($js, \"{\\n    \\\"foo\\\": \\\"bar\\\"\\n}\"),\n        );\n\n        return $tests;\n    }\n\n    /**\n     * testRequireJson\n     *\n     * @dataProvider providerRequireJson\n\t * @param array $packages\n\t * @param array $config\n\t * @param string $expected\n     */\n    public function testRequireJson(array $packages, array $config, $expected = null)\n    {\n        $this->composer->getConfig()->merge(array('config' => $config));\n        $this->process->init();\n        $result = $this->process->requireJson($packages);\n        $this->assertEquals($expected, $result);\n    }\n\n    public function providerRequireJson()\n    {\n        // Test a package that doesn't have any extra information.\n        $packageWithoutExtra = array(\n            'name' => 'components/packagewithoutextra',\n            'type' => 'component',\n        );\n        $packages = array($packageWithoutExtra);\n        $expected = array(\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test switching the component directory.\n        $packages = array($packageWithoutExtra);\n        $expected = array(\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array('component-dir' => 'otherdir'), $expected);\n\n        // Test switching the baseUrl.\n        $packages = array($packageWithoutExtra);\n        $expected = array(\n            'baseUrl' => '/another/path',\n        );\n        $tests[] = array($packages, array('component-baseurl' => '/another/path'), $expected);\n\n        // Test a package with just Scripts.\n        $jquery = array(\n            'name' => 'components/jquery',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'scripts' => array(\n                        'jquery.js',\n                    )\n                )\n            )\n        );\n        $packages = array($jquery);\n        $expected = array(\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test a pckage with just shim information.\n        $underscore = array(\n            'name' => 'components/underscore',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'shim' => array(\n                        'exports' => '_',\n                    ),\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $packages = array($underscore);\n        $expected = array(\n            'shim' => array(\n                'underscore' => array(\n                    'exports' => '_',\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test a package the has everything.\n        $backbone = array(\n            'name' => 'components/backbone',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'scripts' => array(\n                        'backbone.js'\n                    ),\n                    'shim' => array(\n                        'exports' => 'Backbone',\n                        'deps' => array(\n                            'underscore',\n                            'jquery'\n                        ),\n                    ),\n                ),\n            ),\n        );\n        $packages = array($backbone);\n        $expected = array(\n            'shim' => array(\n                'backbone' => array(\n                    'exports' => 'Backbone',\n                    'deps' => array(\n                        'underscore',\n                        'jquery'\n                    ),\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test multiple packages.\n        $packages = array($backbone, $jquery);\n        $expected = array(\n            'shim' => array(\n                'backbone' => array(\n                    'exports' => 'Backbone',\n                    'deps' => array(\n                        'underscore',\n                        'jquery'\n                    ),\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Package with a config definition.\n        $packageWithConfig = array(\n            'name' => 'components/packagewithconfig',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'config' => array(\n                        'color' => 'blue',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($packageWithConfig);\n        $expected = array(\n            'config' => array(\n                'packagewithconfig' => array(\n                    'color' => 'blue',\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test building the JavaScript file.\n        $packageWithScripts = array(\n            'name' => 'components/foobar',\n            'type' => 'component',\n            'extra' => array(\n                'component' => array(\n                    'scripts' => array(\n                        'tests/ComponentInstaller/Test/Resources/test.js',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($packageWithScripts);\n        $expected = array(\n            'packages' => array(\n                array(\n                    'name' => 'foobar',\n                    'main' => 'foobar-built.js'\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test building JavaScript files with glob().\n        $packageWithScripts = array(\n            'name' => 'components/foobar2',\n            'extra' => array(\n                'component' => array(\n                    'scripts' => array(\n                        'tests/ComponentInstaller/Test/Resources/*.js',\n                    ),\n                ),\n            ),\n            'is-root' => true,\n        );\n        $packages = array($packageWithScripts);\n        $expected = array(\n            'packages' => array(\n                array(\n                    'name' => 'foobar2',\n                    'main' => 'foobar2-built.js'\n                ),\n            ),\n            'baseUrl' => 'components',\n        );\n        $tests[] = array($packages, array(), $expected);\n\n        // Test bringing in config options from the root package.\n        $package = array(\n            'name' => 'components/foobar3',\n            'extra' => array(\n                'component' => array(\n                    'config' => array(\n                       'color' => 'blue',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $config = array(\n            'component' => array(\n                'waitSeconds' => 3,\n                'baseUrl' => 'public',\n            ),\n        );\n        $expected = array(\n            'config' => array(\n                'foobar3' => array(\n                    'color' => 'blue',\n                ),\n            ),\n            'baseUrl' => 'public',\n            'waitSeconds' => 3,\n        );\n        $tests[] = array($packages, $config, $expected);\n\n        // Test overriding component config from root packages.\n        $package = array(\n            'name' => 'components/foobar3',\n            'extra' => array(\n                'component' => array(\n                    'config' => array(\n                       'color' => 'blue',\n                    ),\n                ),\n            ),\n        );\n        $packages = array($package);\n        $config = array(\n            'component' => array(\n                'waitSeconds' => 3,\n                'baseUrl' => 'public',\n                'config' => array(\n                    'foobar3' => array(\n                        'color' => 'red',\n                    ),\n                ),\n            ),\n        );\n        $expected = array(\n            'config' => array(\n                'foobar3' => array(\n                    'color' => 'red',\n                ),\n            ),\n            'baseUrl' => 'public',\n            'waitSeconds' => 3,\n        );\n        $tests[] = array($packages, $config, $expected);\n\n        return $tests;\n    }\n\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Resources/test.css",
    "content": "h1 {\n  color: red;\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Resources/test.js",
    "content": "/**\n * This is a JavaScript test file.\n */\nvar foo = \"bar\";\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Resources/test2.css",
    "content": "h1 {\n  color: blue;\n}\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Resources/test2.js",
    "content": "/**\n * This is a JavaScript test2 file.\n */\nvar bar = \"foo\";\n"
  },
  {
    "path": "tests/ComponentInstaller/Test/Util/FilesystemTest.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nnamespace ComponentInstaller\\Test\\Process;\n\nuse ComponentInstaller\\Util\\Filesystem;\n\n/**\n * Tests Process.\n */\nclass FilesystemTest extends \\PHPUnit_Framework_TestCase\n{\n    /**\n     * Tests the recursiveGlob function.\n     *\n     * @dataProvider providerRecursiveGlobFiles\n\t * @param array $expected\n\t * @param string $pattern\n\t * @param int $flags\n     */\n    public function testRecursiveGlobFiles($expected, $pattern, $flags = 0)\n    {\n        $fs = new Filesystem();\n        $result = $fs->recursiveGlobFiles($pattern, $flags);\n\n        // Sort the arrays so that the indexes don't matter.\n        sort($expected);\n        sort($result);\n\n        $this->assertEquals($expected, $result);\n    }\n\n    public function providerRecursiveGlobFiles()\n    {\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n                'tests/ComponentInstaller/Test/Resources/test.css',\n                'tests/ComponentInstaller/Test/Resources/test.js',\n                'tests/ComponentInstaller/Test/Resources/test2.css',\n                'tests/ComponentInstaller/Test/Resources/test2.js',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/test.css',\n                'tests/ComponentInstaller/Test/Resources/test2.css',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*.css',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*.jpg',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*img*',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/img.jpg',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/img3.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/subdir2/img4.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/**img*.jpg',\n        );\n\n        return $tests;\n    }\n\n    /**\n     * Tests the recursiveGlob function.\n     *\n     * @dataProvider providerRecursiveGlob\n\t * @param array $expected\n\t * @param string $pattern\n\t * @param int $flags\n     */\n    public function testRecursiveGlob($expected, $pattern, $flags = 0)\n    {\n        $fs = new Filesystem();\n        $result = $fs->recursiveGlob($pattern, $flags);\n\n        // Sort the arrays so that the indexes don't matter.\n        sort($expected);\n        sort($result);\n        $this->assertEquals($expected, $result);\n    }\n\n    public function providerRecursiveGlob()\n    {\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n                'tests/ComponentInstaller/Test/Resources/test.css',\n                'tests/ComponentInstaller/Test/Resources/test.js',\n                'tests/ComponentInstaller/Test/Resources/test2.css',\n                'tests/ComponentInstaller/Test/Resources/test2.js',\n                'tests/ComponentInstaller/Test/Resources/subdir',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/test.css',\n                'tests/ComponentInstaller/Test/Resources/test2.css',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*.css',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/img2.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/*.jpg',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/img.jpg',\n            ),\n            'tests/ComponentInstaller/Test/Resources/img.jpg',\n        );\n\n        $tests[] = array(\n            array(\n                'tests/ComponentInstaller/Test/Resources/subdir/img.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/img3.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/subdir2/img4.jpg',\n                'tests/ComponentInstaller/Test/Resources/subdir/subdir2',\n            ),\n            'tests/ComponentInstaller/Test/Resources/subdir/**',\n        );\n\n        return $tests;\n    }\n}\n"
  },
  {
    "path": "tests/bootstrap.php",
    "content": "<?php\n\n/*\n * This file is part of Component Installer.\n *\n * (c) Rob Loach (http://robloach.net)\n *\n * For the full copyright and license information, please view the LICENSE.md\n * file that was distributed with this source code.\n */\n\nerror_reporting(E_ALL);\n\n// Add the Component Installer test paths.\n$loader = require __DIR__ . '/../src/bootstrap.php';\n$loader->add('ComponentInstaller\\Test', __DIR__);\n\n// Allow use of the Composer\\Test namespace.\n$path = $loader->findFile('Composer\\\\Composer');\n$loader->add('Composer\\Test', dirname(dirname(dirname($path))) . '/tests');\n"
  }
]