From fd319bd5f58be4bccaff275288e9bca9d244a737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sat, 13 Jun 2015 23:01:54 +0200 Subject: [PATCH] Moved requirejs to bower, #677 --- bower.json | 4 +- public/app/components/require.config.js | 3 +- public/vendor/require/css-build.js | 78 --- public/vendor/require/css.js | 23 - public/vendor/require/tmpl.js | 17 - public/vendor/requirejs-text/.bower.json | 16 + public/vendor/requirejs-text/LICENSE | 58 ++ public/vendor/requirejs-text/README.md | 198 ++++++ public/vendor/requirejs-text/bower.json | 5 + public/vendor/requirejs-text/package.json | 30 + .../{require => requirejs-text}/text.js | 31 +- public/vendor/requirejs/.bower.json | 27 + public/vendor/requirejs/README.md | 4 + public/vendor/requirejs/bower.json | 17 + .../vendor/{require => requirejs}/require.js | 621 ++++++++++-------- public/views/index.html | 2 +- tasks/options/concat.js | 2 +- tasks/options/requirejs.js | 2 - tasks/options/uglify.js | 2 +- 19 files changed, 722 insertions(+), 418 deletions(-) delete mode 100644 public/vendor/require/css-build.js delete mode 100644 public/vendor/require/css.js delete mode 100644 public/vendor/require/tmpl.js create mode 100644 public/vendor/requirejs-text/.bower.json create mode 100644 public/vendor/requirejs-text/LICENSE create mode 100644 public/vendor/requirejs-text/README.md create mode 100644 public/vendor/requirejs-text/bower.json create mode 100644 public/vendor/requirejs-text/package.json rename public/vendor/{require => requirejs-text}/text.js (95%) create mode 100644 public/vendor/requirejs/.bower.json create mode 100644 public/vendor/requirejs/README.md create mode 100644 public/vendor/requirejs/bower.json rename public/vendor/{require => requirejs}/require.js (79%) diff --git a/bower.json b/bower.json index 43da3e5c7cd..3607de4d8f0 100644 --- a/bower.json +++ b/bower.json @@ -19,6 +19,8 @@ "angular-mocks": "~1.4.0", "angular-sanitize": "~1.4.0", "angular-native-dragdrop": "~1.1.0", - "angular-bindonce": "~0.3.3" + "angular-bindonce": "~0.3.3", + "requirejs": "~2.1.18", + "requirejs-text": "~2.0.14" } } diff --git a/public/app/components/require.config.js b/public/app/components/require.config.js index 3bcdc031161..12a72dd42e3 100644 --- a/public/app/components/require.config.js +++ b/public/app/components/require.config.js @@ -8,8 +8,7 @@ require.config({ kbn: 'components/kbn', store: 'components/store', - css: '../vendor/require/css', - text: '../vendor/require/text', + text: '../vendor/requirejs-text/text', moment: '../vendor/moment', filesaver: '../vendor/filesaver', ZeroClipboard: '../vendor/ZeroClipboard', diff --git a/public/vendor/require/css-build.js b/public/vendor/require/css-build.js deleted file mode 100644 index ad9403c58f3..00000000000 --- a/public/vendor/require/css-build.js +++ /dev/null @@ -1,78 +0,0 @@ -/** plugin builder for requirejs optimization - */ - -define(function() { - - var fs = require.nodeRequire('fs'); - - function loadfile (url, callback) { - var file = fs.readFileSync(url, 'utf8'); - //Remove BOM (Byte Mark Order) from utf8 files if it is there. - if (file.indexOf('\uFEFF') === 0) { - file = file.substring(1); - } - callback(file); - }; - - function strip (content) { - return content.replace(/[\r\n]+/g," ").replace(/[\t]/g," "); - } - - var buildMap = {}; - var writeonce = false; - - var loader = - { - load: function (name, require, load, config) { - //console.log('css-build: load: '+name); - load(true); - loadfile(config.baseUrl+name,function(F){ - buildMap[name]=strip(F); - }); - }, - - write: function (pluginName, moduleName, write, config) { - - if( !writeonce) - { - writeonce=true; - write( - "define('"+pluginName+"-embed', function()\n{\n"+ - "\tfunction embed_css(content)\n"+ - "\t{\n"+ - "\t\tvar head = document.getElementsByTagName('head')[0],\n"+ - "\t\tstyle = document.createElement('style'),\n"+ - "\t\trules = document.createTextNode(content);\n"+ - "\t\tstyle.type = 'text/css';\n"+ - "\t\tif(style.styleSheet)\n"+ - "\t\t\tstyle.styleSheet.cssText = rules.nodeValue;\n"+ - "\t\telse style.appendChild(rules);\n"+ - "\t\t\thead.appendChild(style);\n"+ - "\t}\n"+ - "\treturn embed_css;\n"+ - "});\n" - ); - } - - write( - "define('"+pluginName+'!'+moduleName+"', ['"+pluginName+"-embed'], \n"+ - "function(embed)\n{\n"+ - "\tembed(\n\t'"+buildMap[moduleName].replace(/'/g, "\\'")+"'\n\t);\n"+ - "\treturn true;\n"+ - "});\n" - ); - }, - - writeFile: function (pluginName, moduleName, write) - { - //console.log('css-build: writeFile'); - }, - - onLayerEnd: function (write, data) - { - //console.log('css-build: onLayerEnd'); - } - }; - - return loader; -}); diff --git a/public/vendor/require/css.js b/public/vendor/require/css.js deleted file mode 100644 index f23330d08a4..00000000000 --- a/public/vendor/require/css.js +++ /dev/null @@ -1,23 +0,0 @@ -/** `css` is a requirejs plugin - that loads a css file and inject it into a page. - note that this loader will return immediately, - regardless of whether the browser had finished parsing the stylesheet. - this css loader is implemented for file optimization and depedency managment - */ - -define({ - load: function (name, require, load, config) { - function inject(filename) - { - var head = document.getElementsByTagName('head')[0]; - var link = document.createElement('link'); - link.href = filename; - link.rel = 'stylesheet'; - link.type = 'text/css'; - head.appendChild(link); - } - inject(requirejs.toUrl(name)); - load(true); - }, - pluginBuilder: '../vendor/require/css-build' -}); diff --git a/public/vendor/require/tmpl.js b/public/vendor/require/tmpl.js deleted file mode 100644 index c5bce803fe6..00000000000 --- a/public/vendor/require/tmpl.js +++ /dev/null @@ -1,17 +0,0 @@ -/*jshint unused:false */ -define(['module'], function (module) { - 'use strict'; - - var masterConfig = (module.config && module.config()) || {}; - - return { - load: function (name, require, onLoad, config) { - var url = require.toUrl(name); - require(['text!'+name], function (text) { - masterConfig.registerTemplate && masterConfig.registerTemplate(url, text); - onLoad(text); - }); - } - }; - -}); \ No newline at end of file diff --git a/public/vendor/requirejs-text/.bower.json b/public/vendor/requirejs-text/.bower.json new file mode 100644 index 00000000000..f433899afe3 --- /dev/null +++ b/public/vendor/requirejs-text/.bower.json @@ -0,0 +1,16 @@ +{ + "name": "text", + "version": "2.0.14", + "main": "text.js", + "homepage": "https://github.com/requirejs/text", + "_release": "2.0.14", + "_resolution": { + "type": "version", + "tag": "2.0.14", + "commit": "195a482d24f1d515979ab26f29e968e99c4ab63c" + }, + "_source": "git://github.com/requirejs/text.git", + "_target": "~2.0.14", + "_originalSource": "requirejs-text", + "_direct": true +} \ No newline at end of file diff --git a/public/vendor/requirejs-text/LICENSE b/public/vendor/requirejs-text/LICENSE new file mode 100644 index 00000000000..d3b4181d59d --- /dev/null +++ b/public/vendor/requirejs-text/LICENSE @@ -0,0 +1,58 @@ +RequireJS is released under two licenses: new BSD, and MIT. You may pick the +license that best suits your development needs. The text of both licenses are +provided below. + + +The "New" BSD License: +---------------------- + +Copyright (c) 2010-2014, The Dojo Foundation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the Dojo Foundation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +MIT License +----------- + +Copyright (c) 2010-2014, The Dojo Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/public/vendor/requirejs-text/README.md b/public/vendor/requirejs-text/README.md new file mode 100644 index 00000000000..0ee79beac23 --- /dev/null +++ b/public/vendor/requirejs-text/README.md @@ -0,0 +1,198 @@ +# text + +A [RequireJS](http://requirejs.org)/AMD loader plugin for loading text +resources. + +Known to work in RequireJS, but should work in other AMD loaders that support +the same loader plugin API. + +## Docs + +See the [RequireJS API text section](http://requirejs.org/docs/api.html#text). + +## Latest release + +The latest release is always available from [the "latest" tag](https://raw.github.com/requirejs/text/latest/text.js). + +It can also be installed using [volo](https://github.com/volojs/volo): + + volo add requirejs/text + +## Usage + +It is nice to build HTML using regular HTML tags, instead of building up DOM +structures in script. However, there is no good way to embed HTML in a +JavaScript file. The best that can be done is using a string of HTML, but that +can be hard to manage, particularly for multi-line HTML. + +The text.js AMD loader plugin can help with this issue. It will automatically be +loaded if the text! prefix is used for a dependency. Download the plugin and put +it in the app's [baseUrl](http://requirejs.org/docs/api.html#config-baseUrl) +directory (or use the [paths config](http://requirejs.org/docs/api.html#config-paths) to place it in other areas). + +You can specify a text file resource as a dependency like so: + +```javascript +require(["some/module", "text!some/module.html", "text!some/module.css"], + function(module, html, css) { + //the html variable will be the text + //of the some/module.html file + //the css variable will be the text + //of the some/module.css file. + } +); +``` + +Notice the .html and .css suffixes to specify the extension of the file. The +"some/module" part of the path will be resolved according to normal module name +resolution: it will use the **baseUrl** and **paths** [configuration +options](http://requirejs.org/docs/api.html#config) to map that name to a path. + +For HTML/XML/SVG files, there is another option. You can pass !strip, which +strips XML declarations so that external SVG and XML documents can be added to a +document without worry. Also, if the string is an HTML document, only the part +inside the body tag is returned. Example: + +```javascript +require(["text!some/module.html!strip"], + function(html) { + //the html variable will be the text of the + //some/module.html file, but only the part + //inside the body tag. + } +); +``` + +The text files are loaded via asynchronous XMLHttpRequest (XHR) calls, so you +can only fetch files from the same domain as the web page (see **XHR +restrictions** below). + +However, [the RequireJS optimizer](http://requirejs.org/docs/optimization.html) +will inline any text! references with the actual text file contents into the +modules, so after a build, the modules that have text! dependencies can be used +from other domains. + +## Configuration + +### XHR restrictions + +The text plugin works by using XMLHttpRequest (XHR) to fetch the text for the +resources it handles. + +However, XHR calls have some restrictions, due to browser/web security policies: + +1) Many browsers do not allow file:// access to just any file. You are better +off serving the application from a local web server than using local file:// +URLs. You will likely run into trouble otherwise. + +2) There are restrictions for using XHR to access files on another web domain. +While CORS can help enable the server for cross-domain access, doing so must +be done with care (in particular if you also host an API from that domain), +and not all browsers support CORS. + +So if the text plugin determines that the request for the resource is on another +domain, it will try to access a ".js" version of the resource by using a +script tag. Script tag GET requests are allowed across domains. The .js version +of the resource should just be a script with a define() call in it that returns +a string for the module value. + +Example: if the resource is 'text!example.html' and that resolves to a path +on another web domain, the text plugin will do a script tag load for +'example.html.js'. + +The [requirejs optimizer](http://requirejs.org/docs/optimization.html) will +generate these '.js' versions of the text resources if you set this in the +build profile: + + optimizeAllPluginResources: true + +In some cases, you may want the text plugin to not try the .js resource, maybe +because you have configured CORS on the other server, and you know that only +browsers that support CORS will be used. In that case you can use the +[module config](http://requirejs.org/docs/api.html#config-moduleconfig) +(requires RequireJS 2+) to override some of the basic logic the plugin uses to +determine if the .js file should be requested: + +```javascript +requirejs.config({ + config: { + text: { + useXhr: function (url, protocol, hostname, port) { + //Override function for determining if XHR should be used. + //url: the URL being requested + //protocol: protocol of page text.js is running on + //hostname: hostname of page text.js is running on + //port: port of page text.js is running on + //Use protocol, hostname, and port to compare against the url + //being requested. + //Return true or false. true means "use xhr", false means + //"fetch the .js version of this resource". + } + } + } +}); +``` + +### Custom XHR hooks + +There may be cases where you might want to provide the XHR object to use +in the request, or you may just want to add some custom headers to the +XHR object used to make the request. You can use the following hooks: + +```javascript +requirejs.config({ + config: { + text: { + onXhr: function (xhr, url) { + //Called after the XHR has been created and after the + //xhr.open() call, but before the xhr.send() call. + //Useful time to set headers. + //xhr: the xhr object + //url: the url that is being used with the xhr object. + }, + createXhr: function () { + //Overrides the creation of the XHR object. Return an XHR + //object from this function. + //Available in text.js 2.0.1 or later. + }, + onXhrComplete: function (xhr, url) { + //Called whenever an XHR has completed its work. Useful + //if browser-specific xhr cleanup needs to be done. + } + } + } +}); +``` + +### Forcing the environment implemention + +The text plugin tries to detect what environment it is available for loading +text resources, Node, XMLHttpRequest (XHR) or Rhino, but sometimes the +Node or Rhino environment may have loaded a library that introduces an XHR +implementation. You can force the environment implementation to use by passing +an "env" module config to the plugin: + +```javascript +requirejs.config({ + config: { + text: { + //Valid values are 'node', 'xhr', or 'rhino' + env: 'rhino' + } + } +}); +``` + +## License + +Dual-licensed -- new BSD or MIT. + +## Where are the tests? + +They are in the [requirejs](https://github.com/jrburke/requirejs) and +[r.js](https://github.com/jrburke/r.js) repos. + +## History + +This plugin was in the [requirejs repo](https://github.com/jrburke/requirejs) +up until the requirejs 2.0 release. diff --git a/public/vendor/requirejs-text/bower.json b/public/vendor/requirejs-text/bower.json new file mode 100644 index 00000000000..5c9772a5f95 --- /dev/null +++ b/public/vendor/requirejs-text/bower.json @@ -0,0 +1,5 @@ +{ + "name": "text", + "version": "2.0.14", + "main": "text.js" +} \ No newline at end of file diff --git a/public/vendor/requirejs-text/package.json b/public/vendor/requirejs-text/package.json new file mode 100644 index 00000000000..ad54dd3a892 --- /dev/null +++ b/public/vendor/requirejs-text/package.json @@ -0,0 +1,30 @@ +{ + "name": "text", + "version": "2.0.14", + "description": "An AMD loader plugin for loading text resources.", + "categories": [ + "Loader plugins" + ], + "main": "text.js", + "github": "https://github.com/requirejs/text", + "bugs": { + "web": "https://github.com/requirejs/text/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/requirejs/text.git" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/mit-license.php" + }, + { + "type": "BSD New", + "url": "http://opensource.org/licenses/BSD-3-Clause" + } + ], + "volo": { + "url": "https://raw.github.com/requirejs/text/{version}/text.js" + } +} diff --git a/public/vendor/require/text.js b/public/vendor/requirejs-text/text.js similarity index 95% rename from public/vendor/require/text.js rename to public/vendor/requirejs-text/text.js index 3c31b6f9cc8..4c311edcebe 100644 --- a/public/vendor/require/text.js +++ b/public/vendor/requirejs-text/text.js @@ -1,5 +1,5 @@ /** - * @license RequireJS text 2.0.10 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * @license RequireJS text 2.0.14 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/text for details */ @@ -23,7 +23,7 @@ define(['module'], function (module) { masterConfig = (module.config && module.config()) || {}; text = { - version: '2.0.10', + version: '2.0.14', strip: function (content) { //Strips declarations so that external SVG and XML @@ -85,13 +85,13 @@ define(['module'], function (module) { parseName: function (name) { var modName, ext, temp, strip = false, - index = name.indexOf("."), + index = name.lastIndexOf("."), isRelative = name.indexOf('./') === 0 || name.indexOf('../') === 0; if (index !== -1 && (!isRelative || index > 1)) { modName = name.substring(0, index); - ext = name.substring(index + 1, name.length); + ext = name.substring(index + 1); } else { modName = name; } @@ -162,12 +162,12 @@ define(['module'], function (module) { // Do not bother with the work if a build and text will // not be inlined. - if (config.isBuild && !config.inlineText) { + if (config && config.isBuild && !config.inlineText) { onLoad(); return; } - masterConfig.isBuild = config.isBuild; + masterConfig.isBuild = config && config.isBuild; var parsed = text.parseName(name), nonStripName = parsed.moduleName + @@ -244,7 +244,8 @@ define(['module'], function (module) { typeof process !== "undefined" && process.versions && !!process.versions.node && - !process.versions['node-webkit'])) { + !process.versions['node-webkit'] && + !process.versions['atom-shell'])) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); @@ -252,12 +253,14 @@ define(['module'], function (module) { try { var file = fs.readFileSync(url, 'utf8'); //Remove BOM (Byte Mark Order) from utf8 files if it is there. - if (file.indexOf('\uFEFF') === 0) { + if (file[0] === '\uFEFF') { file = file.substring(1); } callback(file); } catch (e) { - errback(e); + if (errback) { + errback(e); + } } }; } else if (masterConfig.env === 'xhr' || (!masterConfig.env && @@ -285,12 +288,14 @@ define(['module'], function (module) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { - status = xhr.status; + status = xhr.status || 0; if (status > 399 && status < 600) { //An http 4xx or 5xx error. Signal an error. err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; - errback(err); + if (errback) { + errback(err); + } } else { callback(xhr.responseText); } @@ -347,7 +352,7 @@ define(['module'], function (module) { typeof Components !== 'undefined' && Components.classes && Components.interfaces)) { //Avert your gaze! - Cc = Components.classes, + Cc = Components.classes; Ci = Components.interfaces; Components.utils['import']('resource://gre/modules/FileUtils.jsm'); xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc); @@ -383,4 +388,4 @@ define(['module'], function (module) { }; } return text; -}); \ No newline at end of file +}); diff --git a/public/vendor/requirejs/.bower.json b/public/vendor/requirejs/.bower.json new file mode 100644 index 00000000000..5a363a0e40a --- /dev/null +++ b/public/vendor/requirejs/.bower.json @@ -0,0 +1,27 @@ +{ + "name": "requirejs", + "version": "2.1.18", + "homepage": "http://requirejs.org", + "authors": [ + "jrburke.com" + ], + "description": "A file and module loader for JavaScript", + "main": "require.js", + "keywords": [ + "AMD" + ], + "license": [ + "BSD-3-Clause", + "MIT" + ], + "_release": "2.1.18", + "_resolution": { + "type": "version", + "tag": "2.1.18", + "commit": "833b2db37b0899f7f2c8b6ada741f49c3a7bfbe9" + }, + "_source": "git://github.com/jrburke/requirejs-bower.git", + "_target": "~2.1.18", + "_originalSource": "requirejs", + "_direct": true +} \ No newline at end of file diff --git a/public/vendor/requirejs/README.md b/public/vendor/requirejs/README.md new file mode 100644 index 00000000000..1fe6a9c14ff --- /dev/null +++ b/public/vendor/requirejs/README.md @@ -0,0 +1,4 @@ +# requirejs-bower + +Bower packaging for [RequireJS](http://requirejs.org). + diff --git a/public/vendor/requirejs/bower.json b/public/vendor/requirejs/bower.json new file mode 100644 index 00000000000..d6cbb03644d --- /dev/null +++ b/public/vendor/requirejs/bower.json @@ -0,0 +1,17 @@ +{ + "name": "requirejs", + "version": "2.1.18", + "homepage": "http://requirejs.org", + "authors": [ + "jrburke.com" + ], + "description": "A file and module loader for JavaScript", + "main": "require.js", + "keywords": [ + "AMD" + ], + "license": [ + "BSD-3-Clause", + "MIT" + ] +} diff --git a/public/vendor/require/require.js b/public/vendor/requirejs/require.js similarity index 79% rename from public/vendor/require/require.js rename to public/vendor/requirejs/require.js index fabdfe5cf7d..36280477eed 100644 --- a/public/vendor/require/require.js +++ b/public/vendor/requirejs/require.js @@ -1,6 +1,5 @@ -/* jshint indent:4, maxlen: false */ /** vim: et:ts=4:sw=4:sts=4 - * @license RequireJS 2.1.8 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * @license RequireJS 2.1.18 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ @@ -10,10 +9,10 @@ /*global window, navigator, document, importScripts, setTimeout, opera */ var requirejs, require, define; -(function(global) { +(function (global) { var req, s, head, baseElement, dataMain, src, - interactiveScript, currentlyAddingScript, mainScript, subPath, - version = '2.1.8', + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.1.18', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, @@ -23,13 +22,14 @@ var requirejs, require, define; hasOwn = op.hasOwnProperty, ap = Array.prototype, apsp = ap.splice, - isBrowser = !! (typeof window !== 'undefined' && navigator && window.document), + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. - readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', @@ -106,9 +106,12 @@ var requirejs, require, define; */ function mixin(target, source, force, deepStringMixin) { if (source) { - eachProp(source, function(value, prop) { + eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { - if (deepStringMixin && typeof value !== 'string') { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + if (!target[prop]) { target[prop] = {}; } @@ -125,7 +128,7 @@ var requirejs, require, define; //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { - return function() { + return function () { return fn.apply(obj, arguments); }; } @@ -138,14 +141,14 @@ var requirejs, require, define; throw err; } - //Allow getting a global that expressed in + //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; - each(value.split('.'), function(part) { + each(value.split('.'), function (part) { g = g[part]; }); return g; @@ -177,7 +180,7 @@ var requirejs, require, define; if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { - //Do not overwrite and existing requirejs instance. + //Do not overwrite an existing requirejs instance. return; } cfg = requirejs; @@ -193,27 +196,29 @@ var requirejs, require, define; function newContext(contextName) { var inCheckLoaded, Module, context, handlers, - checkLoadedTimeoutId, - config = { - //Defaults. Do not set a default for map - //config to speed up normalize(), which - //will run faster if there is no default. - waitSeconds: 7, - baseUrl: './', - paths: {}, - pkgs: {}, - shim: {}, - config: {} - }, - registry = {}, - //registry of just enabled modules, to speed - //cycle breaking code when lots of modules - //are registered, but not activated. - enabledRegistry = {}, - undefEvents = {}, - defQueue = [], + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], defined = {}, urlFetched = {}, + bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; @@ -228,20 +233,19 @@ var requirejs, require, define; */ function trimDots(ary) { var i, part; - for (i = 0; ary[i]; i += 1) { + for (i = 0; i < ary.length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { - if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { - //End of the line. Keep at least one non-dot - //path segment at the front so it can be mapped - //correctly to disk. Otherwise, there is likely - //no path mapping for a path starting with '..'. - //This can still fail, but catches the most reasonable - //uses of .. - break; + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; @@ -261,54 +265,45 @@ var requirejs, require, define; * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { - var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, - foundMap, foundI, foundStarMap, starI, - baseParts = baseName && baseName.split('/'), - normalizedBaseParts = baseParts, + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), map = config.map, starMap = map && map['*']; //Adjust any relative paths. - if (name && name.charAt(0) === '.') { - //If have a base name, try to normalize against it, - //otherwise, assume it is a top-level require that will - //be relative to baseUrl in the end. - if (baseName) { - if (getOwn(config.pkgs, baseName)) { - //If the baseName is a package name, then just treat it as one - //name to concat the name with. - normalizedBaseParts = baseParts = [baseName]; - } else { - //Convert baseName to array, and lop off the last part, - //so that . matches that 'directory' and not name of the baseName's - //module. For instance, baseName of 'one/two/three', maps to - //'one/two/three.js', but we want the directory, 'one/two' for - //this normalization. - normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); - } + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; - name = normalizedBaseParts.concat(name.split('/')); - trimDots(name); - - //Some use of packages may use a . path to reference the - //'main' module name, so normalize for that. - pkgConfig = getOwn(config.pkgs, (pkgName = name[0])); - name = name.join('/'); - if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { - name = pkgName; - } - } else if (name.indexOf('./') === 0) { - // No baseName, so this is ID is resolved relative - // to baseUrl, pull off the leading dot. - name = name.substring(2); + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); - for (i = nameParts.length; i > 0; i -= 1) { + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { @@ -325,16 +320,12 @@ var requirejs, require, define; //Match, update name to the new value. foundMap = mapValue; foundI = i; - break; + break outerLoop; } } } } - if (foundMap) { - break; - } - //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. @@ -355,13 +346,18 @@ var requirejs, require, define; } } - return name; + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { - each(scripts(), function(scriptNode) { - if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } @@ -372,12 +368,17 @@ var requirejs, require, define; function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { - removeScript(id); //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); - context.require([id]); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + return true; } } @@ -387,7 +388,7 @@ var requirejs, require, define; //did not have a plugin prefix. function splitPrefix(name) { var prefix, - index = name ? name.indexOf('!') : -1; + index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); @@ -412,7 +413,7 @@ var requirejs, require, define; */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, - prefix = null, + prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, @@ -439,11 +440,20 @@ var requirejs, require, define; if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. - normalizedName = pluginModule.normalize(name, function(name) { + normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { - normalizedName = normalize(name, parentName, applyMap); + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; } } else { //A regular module. @@ -464,17 +474,21 @@ var requirejs, require, define; //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. - suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, - unnormalized: !! suffix, + unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, - id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix }; } @@ -493,7 +507,8 @@ var requirejs, require, define; var id = depMap.id, mod = getOwn(registry, id); - if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } @@ -514,7 +529,7 @@ var requirejs, require, define; if (errback) { errback(err); } else { - each(ids, function(id) { + each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. @@ -542,45 +557,41 @@ var requirejs, require, define; //Array splice in the values since the context code has a //local var ref to defQueue, so cannot just reassign the one //on context. - apsp.apply(defQueue, [defQueue.length - 1, 0].concat(globalDefQueue)); + apsp.apply(defQueue, + [defQueue.length, 0].concat(globalDefQueue)); globalDefQueue = []; } } handlers = { - 'require': function(mod) { + 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, - 'exports': function(mod) { + 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { - return mod.exports; + return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, - 'module': function(mod) { + 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, - config: function() { - var c, - pkg = getOwn(config.pkgs, mod.map.id); - // For packages, only support config targeted - // at the main module. - c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) : getOwn(config.config, mod.map.id); - return c || {}; + config: function () { + return getOwn(config.config, mod.map.id) || {}; }, - exports: defined[mod.map.id] + exports: mod.exports || (mod.exports = {}) }); } } @@ -599,7 +610,7 @@ var requirejs, require, define; mod.emit('error', mod.error); } else { traced[id] = true; - each(mod.depMaps, function(depMap, i) { + each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); @@ -621,8 +632,8 @@ var requirejs, require, define; } function checkLoaded() { - var map, modId, err, usingPathFallback, - waitInterval = config.waitSeconds * 1000, + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], @@ -638,9 +649,9 @@ var requirejs, require, define; inCheckLoaded = true; //Figure out the state of all the modules. - eachProp(enabledRegistry, function(mod) { - map = mod.map; - modId = map.id; + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { @@ -685,7 +696,7 @@ var requirejs, require, define; //Not expired, check for a cycle. if (needCycleCheck) { - each(reqCalls, function(mod) { + each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } @@ -697,7 +708,7 @@ var requirejs, require, define; //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { - checkLoadedTimeoutId = setTimeout(function() { + checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); @@ -707,7 +718,7 @@ var requirejs, require, define; inCheckLoaded = false; } - Module = function(map) { + Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); @@ -724,7 +735,7 @@ var requirejs, require, define; }; Module.prototype = { - init: function(depMaps, factory, errback, options) { + init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there @@ -742,7 +753,7 @@ var requirejs, require, define; } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. - errback = bind(this, function(err) { + errback = bind(this, function (err) { this.emit('error', err); }); } @@ -774,7 +785,7 @@ var requirejs, require, define; } }, - defineDep: function(i, depExports) { + defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { @@ -784,7 +795,7 @@ var requirejs, require, define; } }, - fetch: function() { + fetch: function () { if (this.fetched) { return; } @@ -799,7 +810,7 @@ var requirejs, require, define; if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true - })(this.shim.deps || [], bind(this, function() { + })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { @@ -808,7 +819,7 @@ var requirejs, require, define; } }, - load: function() { + load: function () { var url = this.map.url; //Regular dependency. @@ -822,13 +833,13 @@ var requirejs, require, define; * Checks if the module is ready to define itself, and if so, * define it. */ - check: function() { + check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, - id = this.map.id, + id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; @@ -852,7 +863,8 @@ var requirejs, require, define; //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. - if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { @@ -862,16 +874,14 @@ var requirejs, require, define; exports = context.execCb(id, factory, depExports, exports); } - if (this.map.isDefine) { - //If setting exports via 'module' is in play, - //favor that over return value and exports. After that, - //favor a non-undefined return value over exports use. + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { cjsModule = this.module; - if (cjsModule && cjsModule.exports !== undefined && - //Make sure it is not already the exports value - cjsModule.exports !== this.exports) { + if (cjsModule) { exports = cjsModule.exports; - } else if (exports === undefined && this.usingExports) { + } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } @@ -919,7 +929,7 @@ var requirejs, require, define; } }, - callPlugin: function() { + callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. @@ -929,9 +939,10 @@ var requirejs, require, define; //can be traced for cycles. this.depMaps.push(pluginMap); - on(pluginMap, 'defined', bind(this, function(plugin) { + on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, - name = this.map.name, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true @@ -942,7 +953,7 @@ var requirejs, require, define; if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { - name = plugin.normalize(name, function(name) { + name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } @@ -950,15 +961,14 @@ var requirejs, require, define; //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, - this.map.parentMap); - on(normalizedMap, 'defined', bind(this, function(value) { - this.init([], function() { - return value; - }, null, { - enabled: true, - ignore: true - }); - })); + this.map.parentMap); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { @@ -967,7 +977,7 @@ var requirejs, require, define; this.depMaps.push(normalizedMap); if (this.events.error) { - normalizedMod.on('error', bind(this, function(err) { + normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } @@ -977,22 +987,28 @@ var requirejs, require, define; return; } - load = bind(this, function(value) { - this.init([], function() { - return value; - }, null, { + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { enabled: true }); }); - load.error = bind(this, function(err) { + load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. - eachProp(registry, function(mod) { + eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } @@ -1003,7 +1019,7 @@ var requirejs, require, define; //Allow plugins to load other code without having to know the //context or how to 'complete' the load. - load.fromText = bind(this, function(text, textAlt) { + load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), @@ -1035,8 +1051,11 @@ var requirejs, require, define; try { req.exec(text); } catch (e) { - return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, - e, [id])); + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); } if (hasInteractive) { @@ -1065,7 +1084,7 @@ var requirejs, require, define; this.pluginMaps[pluginMap.id] = pluginMap; }, - enable: function() { + enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; @@ -1076,14 +1095,16 @@ var requirejs, require, define; this.enabling = true; //Enable each dependency - each(this.depMaps, bind(this, function(depMap, i) { + each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. - depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), - false, !this.skipMap); + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); @@ -1095,13 +1116,23 @@ var requirejs, require, define; this.depCount += 1; - on(depMap, 'defined', bind(this, function(depExports) { + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); } } @@ -1118,7 +1149,7 @@ var requirejs, require, define; //Enable each plugin that is used in //a dependency - eachProp(this.pluginMaps, bind(this, function(pluginMap) { + eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); @@ -1130,7 +1161,7 @@ var requirejs, require, define; this.check(); }, - on: function(name, cb) { + on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; @@ -1138,8 +1169,8 @@ var requirejs, require, define; cbs.push(cb); }, - emit: function(name, evt) { - each(this.events[name], function(cb) { + emit: function (name, evt) { + each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { @@ -1205,7 +1236,8 @@ var requirejs, require, define; while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { - return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. @@ -1230,7 +1262,7 @@ var requirejs, require, define; * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ - configure: function(cfg) { + configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { @@ -1238,34 +1270,41 @@ var requirejs, require, define; } } - //Save off the paths and packages since they require special processing, + //Save off the paths since they require special processing, //they are additive. - var pkgs = config.pkgs, - shim = config.shim, + var shim = config.shim, objs = { paths: true, + bundles: true, config: true, map: true }; - eachProp(cfg, function(value, prop) { + eachProp(cfg, function (value, prop) { if (objs[prop]) { - if (prop === 'map') { - if (!config.map) { - config.map = {}; - } - mixin(config[prop], value, true, true); - } else { - mixin(config[prop], value, true); + if (!config[prop]) { + config[prop] = {}; } + mixin(config[prop], value, true, true); } else { config[prop] = value; } }); + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + //Merge shim if (cfg.shim) { - eachProp(cfg.shim, function(value, id) { + eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { @@ -1282,43 +1321,37 @@ var requirejs, require, define; //Adjust packages if necessary. if (cfg.packages) { - each(cfg.packages, function(pkgObj) { - var location; + each(cfg.packages, function (pkgObj) { + var location, name; - pkgObj = typeof pkgObj === 'string' ? { - name: pkgObj - } : pkgObj; + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } - //Create a brand new object on pkgs, since currentPackages can - //be passed in again, and config.pkgs is the internal transformed - //state for all package configs. - pkgs[pkgObj.name] = { - name: pkgObj.name, - location: location || pkgObj.name, - //Remove leading dot in main, so main paths are normalized, - //and remove any trailing .js, since different package - //envs have different conventions: some use a module name, - //some use a file name. - main: (pkgObj.main || 'main') - .replace(currDirRegExp, '') - .replace(jsSuffixRegExp, '') - }; + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); }); - - //Done with modifications, assing packages back to context config - config.pkgs = pkgs; } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. - eachProp(registry, function(mod, id) { + eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { - mod.map = makeModuleMap(id); + mod.map = makeModuleMap(id, null, true); } }); @@ -1330,7 +1363,7 @@ var requirejs, require, define; } }, - makeShimExports: function(value) { + makeShimExports: function (value) { function fn() { var ret; if (value.init) { @@ -1341,7 +1374,7 @@ var requirejs, require, define; return fn; }, - makeRequire: function(relMap, options) { + makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { @@ -1375,7 +1408,11 @@ var requirejs, require, define; id = map.id; if (!hasProp(defined, id)) { - return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); } return defined[id]; } @@ -1384,7 +1421,7 @@ var requirejs, require, define; intakeDefines(); //Mark all the dependencies as needing to be loaded. - context.nextTick(function() { + context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); @@ -1413,9 +1450,9 @@ var requirejs, require, define; * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ - toUrl: function(moduleNamePlusExt) { + toUrl: function (moduleNamePlusExt) { var ext, - index = moduleNamePlusExt.lastIndexOf('.'), + index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; @@ -1427,14 +1464,14 @@ var requirejs, require, define; } return context.nameToUrl(normalize(moduleNamePlusExt, - relMap && relMap.id, true), ext, true); + relMap && relMap.id, true), ext, true); }, - defined: function(id) { + defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, - specified: function(id) { + specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } @@ -1442,7 +1479,7 @@ var requirejs, require, define; //Only allow undef on top level require calls if (!relMap) { - localRequire.undef = function(id) { + localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); @@ -1450,10 +1487,22 @@ var requirejs, require, define; var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); + mod.undefed = true; + removeScript(id); + delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded @@ -1473,10 +1522,10 @@ var requirejs, require, define; /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, - * is passed in for context, when this method is overriden by + * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ - enable: function(depMap) { + enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); @@ -1489,10 +1538,10 @@ var requirejs, require, define; * load call. * @param {String} moduleName the name of the module to potentially complete. */ - completeLoad: function(moduleName) { + completeLoad: function (moduleName) { var found, args, mod, - shim = getOwn(config.shim, moduleName) || {}, - shExports = shim.exports; + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; takeGlobalQueue(); @@ -1524,8 +1573,10 @@ var requirejs, require, define; if (hasPathFallback(moduleName)) { return; } else { - return onError(makeError('nodefine', 'No define call for ' + moduleName, - null, [moduleName])); + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); } } else { //A script that does not call define(), so just simulate @@ -1544,9 +1595,20 @@ var requirejs, require, define; * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ - nameToUrl: function(moduleName, ext, skipExt) { - var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, - parentPath; + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) @@ -1560,7 +1622,6 @@ var requirejs, require, define; } else { //A module that needs to be converted to a path. paths = config.paths; - pkgs = config.pkgs; syms = moduleName.split('/'); //For each module name segment, see if there is a path @@ -1568,7 +1629,7 @@ var requirejs, require, define; //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); - pkg = getOwn(pkgs, parentModule); + parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, @@ -1578,31 +1639,23 @@ var requirejs, require, define; } syms.splice(0, i, parentPath); break; - } else if (pkg) { - //If module name is just the package name, then looking - //for the main module. - if (moduleName === pkg.name) { - pkgPath = pkg.location + '/' + pkg.main; - } else { - pkgPath = pkg.location; - } - syms.splice(0, i, pkgPath); - break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); - url += (ext || (/\?/.test(url) || skipExt ? '' : '.js')); + url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } - return config.urlArgs ? url + ((url.indexOf('?') === -1 ? '?' : '&') + config.urlArgs) : url; + return config.urlArgs ? url + + ((url.indexOf('?') === -1 ? '?' : '&') + + config.urlArgs) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. - load: function(id, url) { + load: function (id, url) { req.load(context, id, url); }, @@ -1613,7 +1666,7 @@ var requirejs, require, define; * * @private */ - execCb: function(name, callback, args, exports) { + execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, @@ -1623,11 +1676,12 @@ var requirejs, require, define; * @param {Event} evt the event from the browser for the script * that was loaded. */ - onScriptLoad: function(evt) { + onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. - if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; @@ -1641,7 +1695,7 @@ var requirejs, require, define; /** * Callback for script errors. */ - onScriptError: function(evt) { + onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); @@ -1667,11 +1721,11 @@ var requirejs, require, define; * on a require that are not standardized), and to give a short * name for minification/local scope use. */ - req = requirejs = function(deps, callback, errback, optional) { + req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, - contextName = defContextName; + contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { @@ -1707,7 +1761,7 @@ var requirejs, require, define; * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ - req.config = function(config) { + req.config = function (config) { return req(config); }; @@ -1717,11 +1771,9 @@ var requirejs, require, define; * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ - req.nextTick = typeof setTimeout !== 'undefined' ? function(fn) { + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); - } : function(fn) { - fn(); - }; + } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. @@ -1744,11 +1796,16 @@ var requirejs, require, define; req({}); //Exports some context-sensitive methods on global require. - each(['toUrl', 'undef', 'defined', 'specified'], function(prop) { + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. - req[prop] = function() { + req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; @@ -1775,8 +1832,10 @@ var requirejs, require, define; /** * Creates the node for the load command. Only used in browser envs. */ - req.createNode = function(config, moduleName, url) { - var node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; @@ -1792,9 +1851,9 @@ var requirejs, require, define; * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ - req.load = function(context, moduleName, url) { + req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, - node; + node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); @@ -1811,14 +1870,15 @@ var requirejs, require, define; //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && - //Check if node.attachEvent is artificially added by custom script or - //natively supported by browser - //read https://github.com/jrburke/requirejs/issues/187 - //if we can NOT find [native code] then it must NOT natively supported. - //in IE8, node.attachEvent does not have toString() - //Note the test for "[native code" with no closing brace, see: - //https://github.com/jrburke/requirejs/issues/273 - !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/jrburke/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/jrburke/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. @@ -1870,8 +1930,11 @@ var requirejs, require, define; //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { - context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, - e, [moduleName])); + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); } } }; @@ -1881,7 +1944,7 @@ var requirejs, require, define; return interactiveScript; } - eachReverse(scripts(), function(script) { + eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } @@ -1890,9 +1953,9 @@ var requirejs, require, define; } //Look for a data-main script attribute, which could also adjust the baseUrl. - if (isBrowser) { + if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. - eachReverse(scripts(), function(script) { + eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { @@ -1913,7 +1976,7 @@ var requirejs, require, define; //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); - subPath = src.length ? src.join('/') + '/' : './'; + subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } @@ -1942,7 +2005,7 @@ var requirejs, require, define; * return a value to define the module corresponding to the first argument's * name. */ - define = function(name, deps, callback) { + define = function (name, deps, callback) { var node, context; //Allow for anonymous modules @@ -1967,11 +2030,12 @@ var requirejs, require, define; //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { - callback.toString() + callback + .toString() .replace(commentRegExp, '') - .replace(cjsRequireRegExp, function(match, dep) { - deps.push(dep); - }); + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module @@ -2007,18 +2071,17 @@ var requirejs, require, define; jQuery: true }; - /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ - req.exec = function(text) { + req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); -}(this)); \ No newline at end of file +}(this)); diff --git a/public/views/index.html b/public/views/index.html index 4239f77aa76..47f00728eb7 100644 --- a/public/views/index.html +++ b/public/views/index.html @@ -18,7 +18,7 @@ - + diff --git a/tasks/options/concat.js b/tasks/options/concat.js index 36a69965229..c325afd7f51 100644 --- a/tasks/options/concat.js +++ b/tasks/options/concat.js @@ -27,7 +27,7 @@ module.exports = function(config) { js: { src: [ - '<%= destDir %>/vendor/require/require.js', + '<%= destDir %>/vendor/requirejs/require.js', '<%= destDir %>/app/components/require.config.js', '<%= destDir %>/app/app.js', ], diff --git a/tasks/options/requirejs.js b/tasks/options/requirejs.js index 5a785ffce7f..e9068dcbd04 100644 --- a/tasks/options/requirejs.js +++ b/tasks/options/requirejs.js @@ -40,7 +40,6 @@ module.exports = function(config,grunt) { // main/common module name: 'app', include: [ - 'css', 'kbn', 'text', 'jquery', @@ -75,7 +74,6 @@ module.exports = function(config,grunt) { // create a module for each directory in public/app/panels/ fs.readdirSync(panelPath).forEach(function (panelName) { requireModules[0].include.push('panels/'+panelName+'/module'); - requireModules[0].include.push('text!panels/'+panelName+'/module.html'); }); return { options: options }; diff --git a/tasks/options/uglify.js b/tasks/options/uglify.js index 583dbab78cb..2428331b021 100644 --- a/tasks/options/uglify.js +++ b/tasks/options/uglify.js @@ -2,7 +2,7 @@ module.exports = function(config) { return { dest: { expand: true, - src: ['**/*.js', '!dashboards/*.js'], + src: ['**/*.js', '!dashboards/*.js', '!vendor/jquery/**/*.js'], dest: '<%= destDir %>', cwd: '<%= destDir %>', options: {