1 /** vim: et:ts=4:sw=4:sts=4
2 * @license RequireJS 2.1.9 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 * Available via the MIT or new BSD license.
4 * see: http://github.com/jrburke/requirejs for details
6 //Not using strict: uneven strict support in browsers, #392, and causes
7 //problems with requirejs.exec()/transpiler plugins that may not be strict.
8 /*jslint regexp: true, nomen: true, sloppy: true */
9 /*global window, navigator, document, importScripts, setTimeout, opera */
11 var requirejs, require, define;
13 var req, s, head, baseElement, dataMain, src,
14 interactiveScript, currentlyAddingScript, mainScript, subPath,
16 commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
17 cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
18 jsSuffixRegExp = /\.js$/,
19 currDirRegExp = /^\.\//,
20 op = Object.prototype,
21 ostring = op.toString,
22 hasOwn = op.hasOwnProperty,
25 isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
26 isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
27 //PS3 indicates loaded and complete, but need to wait for complete
28 //specifically. Sequence is 'loading', 'loaded', execution,
29 // then 'complete'. The UA check is unfortunate, but not sure how
30 //to feature test w/o causing perf issues.
31 readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
32 /^complete$/ : /^(complete|loaded)$/,
34 //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
35 isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
39 useInteractive = false;
41 function isFunction(it) {
42 return ostring.call(it) === '[object Function]';
45 function isArray(it) {
46 return ostring.call(it) === '[object Array]';
50 * Helper function for iterating over an array. If the func returns
51 * a true value, it will break out of the loop.
53 function each(ary, func) {
56 for (i = 0; i < ary.length; i += 1) {
57 if (ary[i] && func(ary[i], i, ary)) {
65 * Helper function for iterating over an array backwards. If the func
66 * returns a true value, it will break out of the loop.
68 function eachReverse(ary, func) {
71 for (i = ary.length - 1; i > -1; i -= 1) {
72 if (ary[i] && func(ary[i], i, ary)) {
79 function hasProp(obj, prop) {
80 return hasOwn.call(obj, prop);
83 function getOwn(obj, prop) {
84 return hasProp(obj, prop) && obj[prop];
88 * Cycles over properties in an object and calls a function for each
89 * property value. If the function returns a truthy value, then the
90 * iteration is stopped.
92 function eachProp(obj, func) {
95 if (hasProp(obj, prop)) {
96 if (func(obj[prop], prop)) {
104 * Simple function to mix in properties from source into target,
105 * but only if target does not already have a property of the same name.
107 function mixin(target, source, force, deepStringMixin) {
109 eachProp(source, function (value, prop) {
110 if (force || !hasProp(target, prop)) {
111 if (deepStringMixin && typeof value !== 'string') {
115 mixin(target[prop], value, force, deepStringMixin);
117 target[prop] = value;
125 //Similar to Function.prototype.bind, but the 'this' object is specified
126 //first, since it is easier to read/figure out what 'this' will be.
127 function bind(obj, fn) {
129 return fn.apply(obj, arguments);
134 return document.getElementsByTagName('script');
137 function defaultOnError(err) {
141 //Allow getting a global that expressed in
142 //dot notation, like 'a.b.c'.
143 function getGlobal(value) {
148 each(value.split('.'), function (part) {
155 * Constructs an error with a pointer to an URL with more information.
156 * @param {String} id the error ID that maps to an ID on a web page.
157 * @param {String} message human readable error.
158 * @param {Error} [err] the original error, if there is one.
162 function makeError(id, msg, err, requireModules) {
163 var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
165 e.requireModules = requireModules;
167 e.originalError = err;
172 if (typeof define !== 'undefined') {
173 //If a define is already in play via another AMD loader,
178 if (typeof requirejs !== 'undefined') {
179 if (isFunction(requirejs)) {
180 //Do not overwrite and existing requirejs instance.
184 requirejs = undefined;
187 //Allow for a require config object
188 if (typeof require !== 'undefined' && !isFunction(require)) {
189 //assume it is a config object.
194 function newContext(contextName) {
195 var inCheckLoaded, Module, context, handlers,
196 checkLoadedTimeoutId,
198 //Defaults. Do not set a default for map
199 //config to speed up normalize(), which
200 //will run faster if there is no default.
209 //registry of just enabled modules, to speed
210 //cycle breaking code when lots of modules
211 //are registered, but not activated.
212 enabledRegistry = {},
218 unnormalizedCounter = 1;
221 * Trims the . and .. from an array of path segments.
222 * It will keep a leading path segment if a .. will become
223 * the first path segment, to help with module name lookups,
224 * which act like paths, but can be remapped. But the end result,
225 * all paths that use this function should look normalized.
226 * NOTE: this method MODIFIES the input array.
227 * @param {Array} ary the array of path segments.
229 function trimDots(ary) {
231 for (i = 0; ary[i]; i += 1) {
236 } else if (part === '..') {
237 if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
238 //End of the line. Keep at least one non-dot
239 //path segment at the front so it can be mapped
240 //correctly to disk. Otherwise, there is likely
241 //no path mapping for a path starting with '..'.
242 //This can still fail, but catches the most reasonable
246 ary.splice(i - 1, 2);
254 * Given a relative module name, like ./something, normalize it to
255 * a real name that can be mapped to a path.
256 * @param {String} name the relative name
257 * @param {String} baseName a real name that the name arg is relative
259 * @param {Boolean} applyMap apply the map config to the value. Should
260 * only be done if this normalization is for a dependency ID.
261 * @returns {String} normalized name
263 function normalize(name, baseName, applyMap) {
264 var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
265 foundMap, foundI, foundStarMap, starI,
266 baseParts = baseName && baseName.split('/'),
267 normalizedBaseParts = baseParts,
269 starMap = map && map['*'];
271 //Adjust any relative paths.
272 if (name && name.charAt(0) === '.') {
273 //If have a base name, try to normalize against it,
274 //otherwise, assume it is a top-level require that will
275 //be relative to baseUrl in the end.
277 if (getOwn(config.pkgs, baseName)) {
278 //If the baseName is a package name, then just treat it as one
279 //name to concat the name with.
280 normalizedBaseParts = baseParts = [baseName];
282 //Convert baseName to array, and lop off the last part,
283 //so that . matches that 'directory' and not name of the baseName's
284 //module. For instance, baseName of 'one/two/three', maps to
285 //'one/two/three.js', but we want the directory, 'one/two' for
286 //this normalization.
287 normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
290 name = normalizedBaseParts.concat(name.split('/'));
293 //Some use of packages may use a . path to reference the
294 //'main' module name, so normalize for that.
295 pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
296 name = name.join('/');
297 if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
300 } else if (name.indexOf('./') === 0) {
301 // No baseName, so this is ID is resolved relative
302 // to baseUrl, pull off the leading dot.
303 name = name.substring(2);
307 //Apply map config if available.
308 if (applyMap && map && (baseParts || starMap)) {
309 nameParts = name.split('/');
311 for (i = nameParts.length; i > 0; i -= 1) {
312 nameSegment = nameParts.slice(0, i).join('/');
315 //Find the longest baseName segment match in the config.
316 //So, do joins on the biggest to smallest lengths of baseParts.
317 for (j = baseParts.length; j > 0; j -= 1) {
318 mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
320 //baseName segment has config, find if it has one for
323 mapValue = getOwn(mapValue, nameSegment);
325 //Match, update name to the new value.
338 //Check for a star map match, but just hold on to it,
339 //if there is a shorter segment match later in a matching
340 //config, then favor over this star map.
341 if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
342 foundStarMap = getOwn(starMap, nameSegment);
347 if (!foundMap && foundStarMap) {
348 foundMap = foundStarMap;
353 nameParts.splice(0, foundI, foundMap);
354 name = nameParts.join('/');
361 function removeScript(name) {
363 each(scripts(), function (scriptNode) {
364 if (scriptNode.getAttribute('data-requiremodule') === name &&
365 scriptNode.getAttribute('data-requirecontext') === context.contextName) {
366 scriptNode.parentNode.removeChild(scriptNode);
373 function hasPathFallback(id) {
374 var pathConfig = getOwn(config.paths, id);
375 if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
376 //Pop off the first array value, since it failed, and
379 context.require.undef(id);
380 context.require([id]);
385 //Turns a plugin!resource to [plugin, resource]
386 //with the plugin being undefined if the name
387 //did not have a plugin prefix.
388 function splitPrefix(name) {
390 index = name ? name.indexOf('!') : -1;
392 prefix = name.substring(0, index);
393 name = name.substring(index + 1, name.length);
395 return [prefix, name];
399 * Creates a module mapping that includes plugin prefix, module
400 * name, and path. If parentModuleMap is provided it will
401 * also normalize the name via require.normalize()
403 * @param {String} name the module name
404 * @param {String} [parentModuleMap] parent module map
405 * for the module name, used to resolve relative names.
406 * @param {Boolean} isNormalized: is the ID already normalized.
407 * This is true if this call is done for a define() module ID.
408 * @param {Boolean} applyMap: apply the map config to the ID.
409 * Should only be true if this map is for a dependency.
413 function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
414 var url, pluginModule, suffix, nameParts,
416 parentName = parentModuleMap ? parentModuleMap.name : null,
421 //If no name, then it means it is a require call, generate an
425 name = '_@r' + (requireCounter += 1);
428 nameParts = splitPrefix(name);
429 prefix = nameParts[0];
433 prefix = normalize(prefix, parentName, applyMap);
434 pluginModule = getOwn(defined, prefix);
437 //Account for relative paths if there is a base name.
440 if (pluginModule && pluginModule.normalize) {
441 //Plugin is loaded, use its normalize method.
442 normalizedName = pluginModule.normalize(name, function (name) {
443 return normalize(name, parentName, applyMap);
446 normalizedName = normalize(name, parentName, applyMap);
450 normalizedName = normalize(name, parentName, applyMap);
452 //Normalized name may be a plugin ID due to map config
453 //application in normalize. The map config values must
454 //already be normalized, so do not need to redo that part.
455 nameParts = splitPrefix(normalizedName);
456 prefix = nameParts[0];
457 normalizedName = nameParts[1];
460 url = context.nameToUrl(normalizedName);
464 //If the id is a plugin id that cannot be determined if it needs
465 //normalization, stamp it with a unique ID so two matching relative
466 //ids that may conflict can be separate.
467 suffix = prefix && !pluginModule && !isNormalized ?
468 '_unnormalized' + (unnormalizedCounter += 1) :
473 name: normalizedName,
474 parentMap: parentModuleMap,
475 unnormalized: !!suffix,
477 originalName: originalName,
480 prefix + '!' + normalizedName :
481 normalizedName) + suffix
485 function getModule(depMap) {
487 mod = getOwn(registry, id);
490 mod = registry[id] = new context.Module(depMap);
496 function on(depMap, name, fn) {
498 mod = getOwn(registry, id);
500 if (hasProp(defined, id) &&
501 (!mod || mod.defineEmitComplete)) {
502 if (name === 'defined') {
506 mod = getModule(depMap);
507 if (mod.error && name === 'error') {
515 function onError(err, errback) {
516 var ids = err.requireModules,
522 each(ids, function (id) {
523 var mod = getOwn(registry, id);
525 //Set error on module, so it skips timeout checks.
527 if (mod.events.error) {
529 mod.emit('error', err);
541 * Internal method to transfer globalQueue items to this context's
544 function takeGlobalQueue() {
545 //Push all the globalDefQueue items into the context's defQueue
546 if (globalDefQueue.length) {
547 //Array splice in the values since the context code has a
548 //local var ref to defQueue, so cannot just reassign the one
551 [defQueue.length - 1, 0].concat(globalDefQueue));
557 'require': function (mod) {
561 return (mod.require = context.makeRequire(mod.map));
564 'exports': function (mod) {
565 mod.usingExports = true;
566 if (mod.map.isDefine) {
570 return (mod.exports = defined[mod.map.id] = {});
574 'module': function (mod) {
578 return (mod.module = {
581 config: function () {
583 pkg = getOwn(config.pkgs, mod.map.id);
584 // For packages, only support config targeted
585 // at the main module.
586 c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) :
587 getOwn(config.config, mod.map.id);
590 exports: defined[mod.map.id]
596 function cleanRegistry(id) {
597 //Clean up machinery used for waiting modules.
599 delete enabledRegistry[id];
602 function breakCycle(mod, traced, processed) {
606 mod.emit('error', mod.error);
609 each(mod.depMaps, function (depMap, i) {
610 var depId = depMap.id,
611 dep = getOwn(registry, depId);
613 //Only force things that have not completed
614 //being defined, so still in the registry,
615 //and only if it has not been matched up
616 //in the module already.
617 if (dep && !mod.depMatched[i] && !processed[depId]) {
618 if (getOwn(traced, depId)) {
619 mod.defineDep(i, defined[depId]);
620 mod.check(); //pass false?
622 breakCycle(dep, traced, processed);
626 processed[id] = true;
630 function checkLoaded() {
631 var map, modId, err, usingPathFallback,
632 waitInterval = config.waitSeconds * 1000,
633 //It is possible to disable the wait interval by using waitSeconds of 0.
634 expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
637 stillLoading = false,
638 needCycleCheck = true;
640 //Do not bother if this call was a result of a cycle break.
645 inCheckLoaded = true;
647 //Figure out the state of all the modules.
648 eachProp(enabledRegistry, function (mod) {
652 //Skip things that are not enabled or in error state.
662 //If the module should be executed, and it has not
663 //been inited and time is up, remember it.
664 if (!mod.inited && expired) {
665 if (hasPathFallback(modId)) {
666 usingPathFallback = true;
672 } else if (!mod.inited && mod.fetched && map.isDefine) {
675 //No reason to keep looking for unfinished
676 //loading. If the only stillLoading is a
677 //plugin resource though, keep going,
678 //because it may be that a plugin resource
679 //is waiting on a non-plugin cycle.
680 return (needCycleCheck = false);
686 if (expired && noLoads.length) {
687 //If wait time expired, throw error of unloaded modules.
688 err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
689 err.contextName = context.contextName;
693 //Not expired, check for a cycle.
694 if (needCycleCheck) {
695 each(reqCalls, function (mod) {
696 breakCycle(mod, {}, {});
700 //If still waiting on loads, and the waiting load is something
701 //other than a plugin resource, or there are still outstanding
702 //scripts, then just try back later.
703 if ((!expired || usingPathFallback) && stillLoading) {
704 //Something is still waiting to load. Wait for it, but only
705 //if a timeout is not already in effect.
706 if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
707 checkLoadedTimeoutId = setTimeout(function () {
708 checkLoadedTimeoutId = 0;
714 inCheckLoaded = false;
717 Module = function (map) {
718 this.events = getOwn(undefEvents, map.id) || {};
720 this.shim = getOwn(config.shim, map.id);
721 this.depExports = [];
723 this.depMatched = [];
724 this.pluginMaps = {};
727 /* this.exports this.factory
729 this.enabled, this.fetched
734 init: function (depMaps, factory, errback, options) {
735 options = options || {};
737 //Do not do more inits if already done. Can happen if there
738 //are multiple define calls for the same module. That is not
739 //a normal, common case, but it is also not unexpected.
744 this.factory = factory;
747 //Register for errors on this module.
748 this.on('error', errback);
749 } else if (this.events.error) {
750 //If no errback already, but there are error listeners
751 //on this module, set up an errback to pass to the deps.
752 errback = bind(this, function (err) {
753 this.emit('error', err);
757 //Do a copy of the dependency array, so that
758 //source inputs are not modified. For example
759 //"shim" deps are passed in here directly, and
760 //doing a direct modification of the depMaps array
761 //would affect that config.
762 this.depMaps = depMaps && depMaps.slice(0);
764 this.errback = errback;
766 //Indicate this module has be initialized
769 this.ignore = options.ignore;
771 //Could have option to init this module in enabled mode,
772 //or could have been previously marked as enabled. However,
773 //the dependencies are not known until init is called. So
774 //if enabled previously, now trigger dependencies as enabled.
775 if (options.enabled || this.enabled) {
776 //Enable this module and dependencies.
777 //Will call this.check()
784 defineDep: function (i, depExports) {
785 //Because of cycles, defined callback for a given
786 //export can be called more than once.
787 if (!this.depMatched[i]) {
788 this.depMatched[i] = true;
790 this.depExports[i] = depExports;
800 context.startTime = (new Date()).getTime();
804 //If the manager is for a plugin managed resource,
805 //ask the plugin to load it now.
807 context.makeRequire(this.map, {
808 enableBuildCallback: true
809 })(this.shim.deps || [], bind(this, function () {
810 return map.prefix ? this.callPlugin() : this.load();
813 //Regular dependency.
814 return map.prefix ? this.callPlugin() : this.load();
819 var url = this.map.url;
821 //Regular dependency.
822 if (!urlFetched[url]) {
823 urlFetched[url] = true;
824 context.load(this.map.id, url);
829 * Checks if the module is ready to define itself, and if so,
833 if (!this.enabled || this.enabling) {
839 depExports = this.depExports,
840 exports = this.exports,
841 factory = this.factory;
845 } else if (this.error) {
846 this.emit('error', this.error);
847 } else if (!this.defining) {
848 //The factory could trigger another require call
849 //that would result in checking this module to
850 //define itself again. If already in the process
851 //of doing that, skip this work.
852 this.defining = true;
854 if (this.depCount < 1 && !this.defined) {
855 if (isFunction(factory)) {
856 //If there is an error listener, favor passing
857 //to that instead of throwing an error. However,
858 //only do it for define()'d modules. require
859 //errbacks should not be called for failures in
860 //their callbacks (#699). However if a global
861 //onError is set, use that.
862 if ((this.events.error && this.map.isDefine) ||
863 req.onError !== defaultOnError) {
865 exports = context.execCb(id, factory, depExports, exports);
870 exports = context.execCb(id, factory, depExports, exports);
873 if (this.map.isDefine) {
874 //If setting exports via 'module' is in play,
875 //favor that over return value and exports. After that,
876 //favor a non-undefined return value over exports use.
877 cjsModule = this.module;
879 cjsModule.exports !== undefined &&
880 //Make sure it is not already the exports value
881 cjsModule.exports !== this.exports) {
882 exports = cjsModule.exports;
883 } else if (exports === undefined && this.usingExports) {
884 //exports already set the defined value.
885 exports = this.exports;
890 err.requireMap = this.map;
891 err.requireModules = this.map.isDefine ? [this.map.id] : null;
892 err.requireType = this.map.isDefine ? 'define' : 'require';
893 return onError((this.error = err));
897 //Just a literal value
901 this.exports = exports;
903 if (this.map.isDefine && !this.ignore) {
904 defined[id] = exports;
906 if (req.onResourceLoad) {
907 req.onResourceLoad(context, this.map, this.depMaps);
917 //Finished the define stage. Allow calling check again
918 //to allow define notifications below in the case of a
920 this.defining = false;
922 if (this.defined && !this.defineEmitted) {
923 this.defineEmitted = true;
924 this.emit('defined', this.exports);
925 this.defineEmitComplete = true;
931 callPlugin: function () {
934 //Map already normalized the prefix.
935 pluginMap = makeModuleMap(map.prefix);
937 //Mark this as a dependency for this plugin, so it
938 //can be traced for cycles.
939 this.depMaps.push(pluginMap);
941 on(pluginMap, 'defined', bind(this, function (plugin) {
942 var load, normalizedMap, normalizedMod,
943 name = this.map.name,
944 parentName = this.map.parentMap ? this.map.parentMap.name : null,
945 localRequire = context.makeRequire(map.parentMap, {
946 enableBuildCallback: true
949 //If current map is not normalized, wait for that
950 //normalized name to load instead of continuing.
951 if (this.map.unnormalized) {
952 //Normalize the ID if the plugin allows it.
953 if (plugin.normalize) {
954 name = plugin.normalize(name, function (name) {
955 return normalize(name, parentName, true);
959 //prefix and name should already be normalized, no need
960 //for applying map config again either.
961 normalizedMap = makeModuleMap(map.prefix + '!' + name,
964 'defined', bind(this, function (value) {
965 this.init([], function () { return value; }, null, {
971 normalizedMod = getOwn(registry, normalizedMap.id);
973 //Mark this as a dependency for this plugin, so it
974 //can be traced for cycles.
975 this.depMaps.push(normalizedMap);
977 if (this.events.error) {
978 normalizedMod.on('error', bind(this, function (err) {
979 this.emit('error', err);
982 normalizedMod.enable();
988 load = bind(this, function (value) {
989 this.init([], function () { return value; }, null, {
994 load.error = bind(this, function (err) {
997 err.requireModules = [id];
999 //Remove temp unnormalized modules for this module,
1000 //since they will never be resolved otherwise now.
1001 eachProp(registry, function (mod) {
1002 if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
1003 cleanRegistry(mod.map.id);
1010 //Allow plugins to load other code without having to know the
1011 //context or how to 'complete' the load.
1012 load.fromText = bind(this, function (text, textAlt) {
1013 /*jslint evil: true */
1014 var moduleName = map.name,
1015 moduleMap = makeModuleMap(moduleName),
1016 hasInteractive = useInteractive;
1018 //As of 2.1.0, support just passing the text, to reinforce
1019 //fromText only being called once per resource. Still
1020 //support old style of passing moduleName but discard
1021 //that moduleName in favor of the internal ref.
1026 //Turn off interactive script matching for IE for any define
1027 //calls in the text, then turn it back on at the end.
1028 if (hasInteractive) {
1029 useInteractive = false;
1032 //Prime the system by creating a module instance for
1034 getModule(moduleMap);
1036 //Transfer any config to this other module.
1037 if (hasProp(config.config, id)) {
1038 config.config[moduleName] = config.config[id];
1044 return onError(makeError('fromtexteval',
1045 'fromText eval for ' + id +
1051 if (hasInteractive) {
1052 useInteractive = true;
1055 //Mark this as a dependency for the plugin
1057 this.depMaps.push(moduleMap);
1059 //Support anonymous modules.
1060 context.completeLoad(moduleName);
1062 //Bind the value of that module to the value for this
1064 localRequire([moduleName], load);
1067 //Use parentName here since the plugin's name is not reliable,
1068 //could be some weird string with no path that actually wants to
1069 //reference the parentName's path.
1070 plugin.load(map.name, localRequire, load, config);
1073 context.enable(pluginMap, this);
1074 this.pluginMaps[pluginMap.id] = pluginMap;
1077 enable: function () {
1078 enabledRegistry[this.map.id] = this;
1079 this.enabled = true;
1081 //Set flag mentioning that the module is enabling,
1082 //so that immediate calls to the defined callbacks
1083 //for dependencies do not trigger inadvertent load
1084 //with the depCount still being zero.
1085 this.enabling = true;
1087 //Enable each dependency
1088 each(this.depMaps, bind(this, function (depMap, i) {
1089 var id, mod, handler;
1091 if (typeof depMap === 'string') {
1092 //Dependency needs to be converted to a depMap
1093 //and wired up to this module.
1094 depMap = makeModuleMap(depMap,
1095 (this.map.isDefine ? this.map : this.map.parentMap),
1098 this.depMaps[i] = depMap;
1100 handler = getOwn(handlers, depMap.id);
1103 this.depExports[i] = handler(this);
1109 on(depMap, 'defined', bind(this, function (depExports) {
1110 this.defineDep(i, depExports);
1115 on(depMap, 'error', bind(this, this.errback));
1122 //Skip special modules like 'require', 'exports', 'module'
1123 //Also, don't call enable if it is already enabled,
1124 //important in circular dependency cases.
1125 if (!hasProp(handlers, id) && mod && !mod.enabled) {
1126 context.enable(depMap, this);
1130 //Enable each plugin that is used in
1132 eachProp(this.pluginMaps, bind(this, function (pluginMap) {
1133 var mod = getOwn(registry, pluginMap.id);
1134 if (mod && !mod.enabled) {
1135 context.enable(pluginMap, this);
1139 this.enabling = false;
1144 on: function (name, cb) {
1145 var cbs = this.events[name];
1147 cbs = this.events[name] = [];
1152 emit: function (name, evt) {
1153 each(this.events[name], function (cb) {
1156 if (name === 'error') {
1157 //Now that the error handler was triggered, remove
1158 //the listeners, since this broken Module instance
1159 //can stay around for a while in the registry.
1160 delete this.events[name];
1165 function callGetModule(args) {
1166 //Skip modules already defined.
1167 if (!hasProp(defined, args[0])) {
1168 getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
1172 function removeListener(node, func, name, ieName) {
1173 //Favor detachEvent because of IE9
1174 //issue, see attachEvent/addEventListener comment elsewhere
1176 if (node.detachEvent && !isOpera) {
1177 //Probably IE. If not it will throw an error, which will be
1180 node.detachEvent(ieName, func);
1183 node.removeEventListener(name, func, false);
1188 * Given an event from a script node, get the requirejs info from it,
1189 * and then removes the event listeners on the node.
1190 * @param {Event} evt
1193 function getScriptData(evt) {
1194 //Using currentTarget instead of target for Firefox 2.0's sake. Not
1195 //all old browsers will be supported, but this one was easy enough
1196 //to support and still makes sense.
1197 var node = evt.currentTarget || evt.srcElement;
1199 //Remove the listeners once here.
1200 removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
1201 removeListener(node, context.onScriptError, 'error');
1205 id: node && node.getAttribute('data-requiremodule')
1209 function intakeDefines() {
1212 //Any defined modules in the global queue, intake them now.
1215 //Make sure any remaining defQueue items get properly processed.
1216 while (defQueue.length) {
1217 args = defQueue.shift();
1218 if (args[0] === null) {
1219 return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
1221 //args are id, deps, factory. Should be normalized by the
1222 //define() function.
1223 callGetModule(args);
1230 contextName: contextName,
1233 urlFetched: urlFetched,
1236 makeModuleMap: makeModuleMap,
1237 nextTick: req.nextTick,
1241 * Set a configuration for the context.
1242 * @param {Object} cfg config object to integrate.
1244 configure: function (cfg) {
1245 //Make sure the baseUrl ends in a slash.
1247 if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
1252 //Save off the paths and packages since they require special processing,
1253 //they are additive.
1254 var pkgs = config.pkgs,
1262 eachProp(cfg, function (value, prop) {
1264 if (prop === 'map') {
1268 mixin(config[prop], value, true, true);
1270 mixin(config[prop], value, true);
1273 config[prop] = value;
1279 eachProp(cfg.shim, function (value, id) {
1280 //Normalize the structure
1281 if (isArray(value)) {
1286 if ((value.exports || value.init) && !value.exportsFn) {
1287 value.exportsFn = context.makeShimExports(value);
1294 //Adjust packages if necessary.
1296 each(cfg.packages, function (pkgObj) {
1299 pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
1300 location = pkgObj.location;
1302 //Create a brand new object on pkgs, since currentPackages can
1303 //be passed in again, and config.pkgs is the internal transformed
1304 //state for all package configs.
1305 pkgs[pkgObj.name] = {
1307 location: location || pkgObj.name,
1308 //Remove leading dot in main, so main paths are normalized,
1309 //and remove any trailing .js, since different package
1310 //envs have different conventions: some use a module name,
1311 //some use a file name.
1312 main: (pkgObj.main || 'main')
1313 .replace(currDirRegExp, '')
1314 .replace(jsSuffixRegExp, '')
1318 //Done with modifications, assing packages back to context config
1322 //If there are any "waiting to execute" modules in the registry,
1323 //update the maps for them, since their info, like URLs to load,
1325 eachProp(registry, function (mod, id) {
1326 //If module already has init called, since it is too
1327 //late to modify them, and ignore unnormalized ones
1328 //since they are transient.
1329 if (!mod.inited && !mod.map.unnormalized) {
1330 mod.map = makeModuleMap(id);
1334 //If a deps array or a config callback is specified, then call
1335 //require with those args. This is useful when require is defined as a
1336 //config object before require.js is loaded.
1337 if (cfg.deps || cfg.callback) {
1338 context.require(cfg.deps || [], cfg.callback);
1342 makeShimExports: function (value) {
1346 ret = value.init.apply(global, arguments);
1348 return ret || (value.exports && getGlobal(value.exports));
1353 makeRequire: function (relMap, options) {
1354 options = options || {};
1356 function localRequire(deps, callback, errback) {
1357 var id, map, requireMod;
1359 if (options.enableBuildCallback && callback && isFunction(callback)) {
1360 callback.__requireJsBuild = true;
1363 if (typeof deps === 'string') {
1364 if (isFunction(callback)) {
1366 return onError(makeError('requireargs', 'Invalid require call'), errback);
1369 //If require|exports|module are requested, get the
1370 //value for them from the special handlers. Caveat:
1371 //this only works while module is being defined.
1372 if (relMap && hasProp(handlers, deps)) {
1373 return handlers[deps](registry[relMap.id]);
1376 //Synchronous access to one module. If require.get is
1377 //available (as in the Node adapter), prefer that.
1379 return req.get(context, deps, relMap, localRequire);
1382 //Normalize module name, if it contains . or ..
1383 map = makeModuleMap(deps, relMap, false, true);
1386 if (!hasProp(defined, id)) {
1387 return onError(makeError('notloaded', 'Module name "' +
1389 '" has not been loaded yet for context: ' +
1391 (relMap ? '' : '. Use require([])')));
1396 //Grab defines waiting in the global queue.
1399 //Mark all the dependencies as needing to be loaded.
1400 context.nextTick(function () {
1401 //Some defines could have been added since the
1402 //require call, collect them.
1405 requireMod = getModule(makeModuleMap(null, relMap));
1407 //Store if map config should be applied to this require
1408 //call for dependencies.
1409 requireMod.skipMap = options.skipMap;
1411 requireMod.init(deps, callback, errback, {
1418 return localRequire;
1421 mixin(localRequire, {
1422 isBrowser: isBrowser,
1425 * Converts a module name + .extension into an URL path.
1426 * *Requires* the use of a module name. It does not support using
1427 * plain URLs like nameToUrl.
1429 toUrl: function (moduleNamePlusExt) {
1431 index = moduleNamePlusExt.lastIndexOf('.'),
1432 segment = moduleNamePlusExt.split('/')[0],
1433 isRelative = segment === '.' || segment === '..';
1435 //Have a file extension alias, and it is not the
1436 //dots from a relative path.
1437 if (index !== -1 && (!isRelative || index > 1)) {
1438 ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
1439 moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
1442 return context.nameToUrl(normalize(moduleNamePlusExt,
1443 relMap && relMap.id, true), ext, true);
1446 defined: function (id) {
1447 return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
1450 specified: function (id) {
1451 id = makeModuleMap(id, relMap, false, true).id;
1452 return hasProp(defined, id) || hasProp(registry, id);
1456 //Only allow undef on top level require calls
1458 localRequire.undef = function (id) {
1459 //Bind any waiting define() calls to this context,
1463 var map = makeModuleMap(id, relMap, true),
1464 mod = getOwn(registry, id);
1469 delete urlFetched[map.url];
1470 delete undefEvents[id];
1473 //Hold on to listeners in case the
1474 //module will be attempted to be reloaded
1475 //using a different config.
1476 if (mod.events.defined) {
1477 undefEvents[id] = mod.events;
1485 return localRequire;
1489 * Called to enable a module if it is still in the registry
1490 * awaiting enablement. A second arg, parent, the parent module,
1491 * is passed in for context, when this method is overriden by
1492 * the optimizer. Not shown here to keep code compact.
1494 enable: function (depMap) {
1495 var mod = getOwn(registry, depMap.id);
1497 getModule(depMap).enable();
1502 * Internal method used by environment adapters to complete a load event.
1503 * A load event could be a script load or just a load pass from a synchronous
1505 * @param {String} moduleName the name of the module to potentially complete.
1507 completeLoad: function (moduleName) {
1508 var found, args, mod,
1509 shim = getOwn(config.shim, moduleName) || {},
1510 shExports = shim.exports;
1514 while (defQueue.length) {
1515 args = defQueue.shift();
1516 if (args[0] === null) {
1517 args[0] = moduleName;
1518 //If already found an anonymous module and bound it
1519 //to this name, then this is some other anon module
1520 //waiting for its completeLoad to fire.
1525 } else if (args[0] === moduleName) {
1526 //Found matching define call for this script!
1530 callGetModule(args);
1533 //Do this after the cycle of callGetModule in case the result
1534 //of those calls/init calls changes the registry.
1535 mod = getOwn(registry, moduleName);
1537 if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
1538 if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
1539 if (hasPathFallback(moduleName)) {
1542 return onError(makeError('nodefine',
1543 'No define call for ' + moduleName,
1548 //A script that does not call define(), so just simulate
1550 callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
1558 * Converts a module name to a file path. Supports cases where
1559 * moduleName may actually be just an URL.
1560 * Note that it **does not** call normalize on the moduleName,
1561 * it is assumed to have already been normalized. This is an
1562 * internal API, not a public one. Use toUrl for the public API.
1564 nameToUrl: function (moduleName, ext, skipExt) {
1565 var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
1568 //If a colon is in the URL, it indicates a protocol is used and it is just
1569 //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
1570 //or ends with .js, then assume the user meant to use an url and not a module id.
1571 //The slash is important for protocol-less URLs as well as full paths.
1572 if (req.jsExtRegExp.test(moduleName)) {
1573 //Just a plain path, not module name lookup, so just return it.
1574 //Add extension if it is included. This is a bit wonky, only non-.js things pass
1575 //an extension, this method probably needs to be reworked.
1576 url = moduleName + (ext || '');
1578 //A module that needs to be converted to a path.
1579 paths = config.paths;
1582 syms = moduleName.split('/');
1583 //For each module name segment, see if there is a path
1584 //registered for it. Start with most specific name
1585 //and work up from it.
1586 for (i = syms.length; i > 0; i -= 1) {
1587 parentModule = syms.slice(0, i).join('/');
1588 pkg = getOwn(pkgs, parentModule);
1589 parentPath = getOwn(paths, parentModule);
1591 //If an array, it means there are a few choices,
1592 //Choose the one that is desired
1593 if (isArray(parentPath)) {
1594 parentPath = parentPath[0];
1596 syms.splice(0, i, parentPath);
1599 //If module name is just the package name, then looking
1600 //for the main module.
1601 if (moduleName === pkg.name) {
1602 pkgPath = pkg.location + '/' + pkg.main;
1604 pkgPath = pkg.location;
1606 syms.splice(0, i, pkgPath);
1611 //Join the path parts together, then figure out if baseUrl is needed.
1612 url = syms.join('/');
1613 url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
1614 url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
1617 return config.urlArgs ? url +
1618 ((url.indexOf('?') === -1 ? '?' : '&') +
1619 config.urlArgs) : url;
1622 //Delegates to req.load. Broken out as a separate function to
1623 //allow overriding in the optimizer.
1624 load: function (id, url) {
1625 req.load(context, id, url);
1629 * Executes a module callback function. Broken out as a separate function
1630 * solely to allow the build system to sequence the files in the built
1631 * layer in the right sequence.
1635 execCb: function (name, callback, args, exports) {
1636 return callback.apply(exports, args);
1640 * callback for script loads, used to check status of loading.
1642 * @param {Event} evt the event from the browser for the script
1645 onScriptLoad: function (evt) {
1646 //Using currentTarget instead of target for Firefox 2.0's sake. Not
1647 //all old browsers will be supported, but this one was easy enough
1648 //to support and still makes sense.
1649 if (evt.type === 'load' ||
1650 (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
1651 //Reset interactive script so a script node is not held onto for
1653 interactiveScript = null;
1655 //Pull out the name of the module and the context.
1656 var data = getScriptData(evt);
1657 context.completeLoad(data.id);
1662 * Callback for script errors.
1664 onScriptError: function (evt) {
1665 var data = getScriptData(evt);
1666 if (!hasPathFallback(data.id)) {
1667 return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
1672 context.require = context.makeRequire();
1679 * If the only argument to require is a string, then the module that
1680 * is represented by that string is fetched for the appropriate context.
1682 * If the first argument is an array, then it will be treated as an array
1683 * of dependency string names to fetch. An optional function callback can
1684 * be specified to execute when all of those dependencies are available.
1686 * Make a local req variable to help Caja compliance (it assumes things
1687 * on a require that are not standardized), and to give a short
1688 * name for minification/local scope use.
1690 req = requirejs = function (deps, callback, errback, optional) {
1692 //Find the right context, use default
1693 var context, config,
1694 contextName = defContextName;
1696 // Determine if have config object in the call.
1697 if (!isArray(deps) && typeof deps !== 'string') {
1698 // deps is a config object
1700 if (isArray(callback)) {
1701 // Adjust args if there are dependencies
1710 if (config && config.context) {
1711 contextName = config.context;
1714 context = getOwn(contexts, contextName);
1716 context = contexts[contextName] = req.s.newContext(contextName);
1720 context.configure(config);
1723 return context.require(deps, callback, errback);
1727 * Support require.config() to make it easier to cooperate with other
1728 * AMD loaders on globally agreed names.
1730 req.config = function (config) {
1735 * Execute something after the current tick
1736 * of the event loop. Override for other envs
1737 * that have a better solution than setTimeout.
1738 * @param {Function} fn function to execute later.
1740 req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
1742 } : function (fn) { fn(); };
1745 * Export require as a global, but only if it does not already exist.
1751 req.version = version;
1753 //Used to filter out dependencies that are already paths.
1754 req.jsExtRegExp = /^\/|:|\?|\.js$/;
1755 req.isBrowser = isBrowser;
1758 newContext: newContext
1761 //Create default context.
1764 //Exports some context-sensitive methods on global require.
1770 ], function (prop) {
1771 //Reference from contexts instead of early binding to default context,
1772 //so that during builds, the latest instance of the default context
1773 //with its config gets used.
1774 req[prop] = function () {
1775 var ctx = contexts[defContextName];
1776 return ctx.require[prop].apply(ctx, arguments);
1781 head = s.head = document.getElementsByTagName('head')[0];
1782 //If BASE tag is in play, using appendChild is a problem for IE6.
1783 //When that browser dies, this can be removed. Details in this jQuery bug:
1784 //http://dev.jquery.com/ticket/2709
1785 baseElement = document.getElementsByTagName('base')[0];
1787 head = s.head = baseElement.parentNode;
1792 * Any errors that require explicitly generates will be passed to this
1793 * function. Intercept/override it if you want custom error handling.
1794 * @param {Error} err the error object.
1796 req.onError = defaultOnError;
1799 * Creates the node for the load command. Only used in browser envs.
1801 req.createNode = function (config, moduleName, url) {
1802 var node = config.xhtml ?
1803 document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
1804 document.createElement('script');
1805 node.type = config.scriptType || 'text/javascript';
1806 node.charset = 'utf-8';
1812 * Does the request to load a module for the browser case.
1813 * Make this a separate function to allow other environments
1816 * @param {Object} context the require context to find state.
1817 * @param {String} moduleName the name of the module.
1818 * @param {Object} url the URL to the module.
1820 req.load = function (context, moduleName, url) {
1821 var config = (context && context.config) || {},
1824 //In the browser so use a script tag
1825 node = req.createNode(config, moduleName, url);
1827 node.setAttribute('data-requirecontext', context.contextName);
1828 node.setAttribute('data-requiremodule', moduleName);
1830 //Set up load listener. Test attachEvent first because IE9 has
1831 //a subtle issue in its addEventListener and script onload firings
1832 //that do not match the behavior of all other browsers with
1833 //addEventListener support, which fire the onload event for a
1834 //script right after the script execution. See:
1835 //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
1836 //UNFORTUNATELY Opera implements attachEvent but does not follow the script
1837 //script execution mode.
1838 if (node.attachEvent &&
1839 //Check if node.attachEvent is artificially added by custom script or
1840 //natively supported by browser
1841 //read https://github.com/jrburke/requirejs/issues/187
1842 //if we can NOT find [native code] then it must NOT natively supported.
1843 //in IE8, node.attachEvent does not have toString()
1844 //Note the test for "[native code" with no closing brace, see:
1845 //https://github.com/jrburke/requirejs/issues/273
1846 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
1848 //Probably IE. IE (at least 6-8) do not fire
1849 //script onload right after executing the script, so
1850 //we cannot tie the anonymous define call to a name.
1851 //However, IE reports the script as being in 'interactive'
1852 //readyState at the time of the define call.
1853 useInteractive = true;
1855 node.attachEvent('onreadystatechange', context.onScriptLoad);
1856 //It would be great to add an error handler here to catch
1857 //404s in IE9+. However, onreadystatechange will fire before
1858 //the error handler, so that does not help. If addEventListener
1859 //is used, then IE will fire error before load, but we cannot
1860 //use that pathway given the connect.microsoft.com issue
1861 //mentioned above about not doing the 'script execute,
1862 //then fire the script load event listener before execute
1863 //next script' that other browsers do.
1864 //Best hope: IE10 fixes the issues,
1865 //and then destroys all installs of IE 6-9.
1866 //node.attachEvent('onerror', context.onScriptError);
1868 node.addEventListener('load', context.onScriptLoad, false);
1869 node.addEventListener('error', context.onScriptError, false);
1873 //For some cache cases in IE 6-8, the script executes before the end
1874 //of the appendChild execution, so to tie an anonymous define
1875 //call to the module name (which is stored on the node), hold on
1876 //to a reference to this node, but clear after the DOM insertion.
1877 currentlyAddingScript = node;
1879 head.insertBefore(node, baseElement);
1881 head.appendChild(node);
1883 currentlyAddingScript = null;
1886 } else if (isWebWorker) {
1888 //In a web worker, use importScripts. This is not a very
1889 //efficient use of importScripts, importScripts will block until
1890 //its script is downloaded and evaluated. However, if web workers
1891 //are in play, the expectation that a build has been done so that
1892 //only one script needs to be loaded anyway. This may need to be
1893 //reevaluated if other use cases become common.
1896 //Account for anonymous modules
1897 context.completeLoad(moduleName);
1899 context.onError(makeError('importscripts',
1900 'importScripts failed for ' +
1901 moduleName + ' at ' + url,
1908 function getInteractiveScript() {
1909 if (interactiveScript && interactiveScript.readyState === 'interactive') {
1910 return interactiveScript;
1913 eachReverse(scripts(), function (script) {
1914 if (script.readyState === 'interactive') {
1915 return (interactiveScript = script);
1918 return interactiveScript;
1921 //Look for a data-main script attribute, which could also adjust the baseUrl.
1922 if (isBrowser && !cfg.skipDataMain) {
1923 //Figure out baseUrl. Get it from the script tag with require.js in it.
1924 eachReverse(scripts(), function (script) {
1925 //Set the 'head' where we can append children by
1926 //using the script's parent.
1928 head = script.parentNode;
1931 //Look for a data-main attribute to set main script for the page
1932 //to load. If it is there, the path to data main becomes the
1933 //baseUrl, if it is not already set.
1934 dataMain = script.getAttribute('data-main');
1936 //Preserve dataMain in case it is a path (i.e. contains '?')
1937 mainScript = dataMain;
1939 //Set final baseUrl if there is not already an explicit one.
1941 //Pull off the directory of data-main for use as the
1943 src = mainScript.split('/');
1944 mainScript = src.pop();
1945 subPath = src.length ? src.join('/') + '/' : './';
1947 cfg.baseUrl = subPath;
1950 //Strip off any trailing .js since mainScript is now
1951 //like a module name.
1952 mainScript = mainScript.replace(jsSuffixRegExp, '');
1954 //If mainScript is still a path, fall back to dataMain
1955 if (req.jsExtRegExp.test(mainScript)) {
1956 mainScript = dataMain;
1959 //Put the data-main script in the files to load.
1960 cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
1968 * The function that handles definitions of modules. Differs from
1969 * require() in that a string for the module should be the first argument,
1970 * and the function to execute after dependencies are loaded should
1971 * return a value to define the module corresponding to the first argument's
1974 define = function (name, deps, callback) {
1977 //Allow for anonymous modules
1978 if (typeof name !== 'string') {
1979 //Adjust args appropriately
1985 //This module may not have dependencies
1986 if (!isArray(deps)) {
1991 //If no name, and callback is a function, then figure out if it a
1992 //CommonJS thing with dependencies.
1993 if (!deps && isFunction(callback)) {
1995 //Remove comments from the callback string,
1996 //look for require calls, and pull them into the dependencies,
1997 //but only if there are function args.
1998 if (callback.length) {
2001 .replace(commentRegExp, '')
2002 .replace(cjsRequireRegExp, function (match, dep) {
2006 //May be a CommonJS thing even without require calls, but still
2007 //could use exports, and module. Avoid doing exports and module
2008 //work though if it just needs require.
2009 //REQUIRES the function to expect the CommonJS variables in the
2010 //order listed below.
2011 deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
2015 //If in IE 6-8 and hit an anonymous define() call, do the interactive
2017 if (useInteractive) {
2018 node = currentlyAddingScript || getInteractiveScript();
2021 name = node.getAttribute('data-requiremodule');
2023 context = contexts[node.getAttribute('data-requirecontext')];
2027 //Always save off evaluating the def call until the script onload handler.
2028 //This allows multiple modules to be in a file without prematurely
2029 //tracing dependencies, and allows for anonymous module support,
2030 //where the module name is not known until the script onload event
2031 //occurs. If no context, use the global queue, and get it processed
2032 //in the onscript load callback.
2033 (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
2042 * Executes the text. Normally just uses eval, but can be modified
2043 * to use a better, environment-specific call. Only used for transpiling
2044 * loader plugins, not for plain JS modules.
2045 * @param {String} text the text to execute/evaluate.
2047 req.exec = function (text) {
2048 /*jslint evil: true */
2052 //Set up with config info.