diff --git a/has.js b/has.js index ef140a1..8eb8f88 100644 --- a/has.js +++ b/has.js @@ -149,7 +149,14 @@ // Expose has() // some AMD build optimizers, like r.js, check for specific condition patterns like the following: if(typeof define == "function" && typeof define.amd == "object" && define.amd){ - define("has", function(){ + define("has", ["module"], function(module){ + var propKey, moduleConfig; + if(typeof module.config == "function"){ + moduleConfig = module.config(); + } + for(propKey in moduleConfig){ + has.add(propKey, moduleConfig[propKey]); + } return has; }); } diff --git a/tests/require.js b/tests/require.js index 71a7d79..8a4e6e1 100644 --- a/tests/require.js +++ b/tests/require.js @@ -1,1750 +1,2076 @@ /** vim: et:ts=4:sw=4:sts=4 - * @license RequireJS 0.14.5 Copyright (c) 2010, The Dojo Foundation All Rights Reserved. + * @license RequireJS 2.1.14 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ -//laxbreak is true to allow build pragmas to change some statements. -/*jslint plusplus: false, nomen: false, laxbreak: true, regexp: false */ -/*global window: false, document: false, navigator: false, -setTimeout: false, traceDeps: true, clearInterval: false, self: false, -setInterval: false, importScripts: false, jQuery: false */ -"use strict"; - -var require, define; -(function () { - //Change this version number for each release. - var version = "0.14.5+", - empty = {}, s, - i, defContextName = "_", contextLoads = [], - scripts, script, rePkg, src, m, dataMain, cfg = {}, setReadyState, - readyRegExp = /^(complete|loaded)$/, - commentRegExp = /(\/\*([\s\S]*?)\*\/|\/\/(.*)$)/mg, - cjsRequireRegExp = /require\(["']([\w-_\.\/]+)["']\)/g, - main, - isBrowser = !!(typeof window !== "undefined" && navigator && document), - isWebWorker = !isBrowser && typeof importScripts !== "undefined", - ostring = Object.prototype.toString, - ap = Array.prototype, - aps = ap.slice, scrollIntervalId, req, baseElement, - defQueue = [], useInteractive = false, currentlyAddingScript; +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + +var requirejs, require, define; +(function (global) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.1.14', + commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + ap = Array.prototype, + apsp = ap.splice, + 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)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; function isFunction(it) { - return ostring.call(it) === "[object Function]"; + return ostring.call(it) === '[object Function]'; } - //Check for an existing version of require. If so, then exit out. Only allow - //one version of require to be active in a page. However, allow for a require - //config object, just exit quickly if require is an actual function. - if (typeof require !== "undefined") { - if (isFunction(require)) { - return; - } else { - //assume it is a config object. - cfg = require; - } + function isArray(it) { + return ostring.call(it) === '[object Array]'; } - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); /** - * Calls a method on a plugin. The obj object should have two property, - * name: the name of the method to call on the plugin - * args: the arguments to pass to the plugin method. + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. */ - function callPlugin(prefix, context, obj) { - //Call the plugin, or load it. - var plugin = s.plugins.defined[prefix], waiting; - if (plugin) { - plugin[obj.name].apply(null, obj.args); - } else { - //Put the call in the waiting call BEFORE requiring the module, - //since the require could be synchronous in some environments, - //like builds - waiting = s.plugins.waiting[prefix] || (s.plugins.waiting[prefix] = []); - waiting.push(obj); - - //Load the module - req(["require/" + prefix], context.contextName); + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } } } - //>>excludeEnd("requireExcludePlugin"); - - /** - * Convenience method to call main for a require.def call that was put on - * hold in the defQueue. - */ - function callDefMain(args, context) { - main.apply(req, args); - //Mark the module loaded. Must do it here in addition - //to doing it in require.def in case a script does - //not call require.def - context.loaded[args[0]] = true; - } /** - * Used to set up package paths from a packagePaths or packages config object. - * @param {Object} packages the object to store the new package config - * @param {Array} currentPackages an array of packages to configure - * @param {String} [dir] a prefix dir to use. + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. */ - function configurePackageDir(packages, currentPackages, dir) { - var i, location, pkgObj; - for (i = 0; (pkgObj = currentPackages[i]); i++) { - pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj; - location = pkgObj.location; - - //Add dir to the path, but avoid paths that start with a slash - //or have a colon (indicates a protocol) - if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) { - pkgObj.location = dir + "/" + (pkgObj.location || pkgObj.name); + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } } + } + } - //Normalize package paths. - pkgObj.location = pkgObj.location || pkgObj.name; - pkgObj.lib = pkgObj.lib || "lib"; - pkgObj.main = pkgObj.main || "main"; + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } - packages[pkgObj.name] = pkgObj; - } + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; } /** - * Determine if priority loading is done. If so clear the priorityWait + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. */ - function isPriorityDone(context) { - var priorityDone = true, - priorityWait = context.config.priorityWait, - priorityName, i; - if (priorityWait) { - for (i = 0; (priorityName = priorityWait[i]); i++) { - if (!context.loaded[priorityName]) { - priorityDone = false; + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { break; } } - if (priorityDone) { - delete context.config.priorityWait; - } } - return priorityDone; } /** - * Resumes tracing of dependencies and then checks if everything is loaded. + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. */ - function resume(context) { - var args, i, paused = s.paused; - if (context.scriptCount <= 0) { - //Synchronous envs will push the number below zero with the - //decrement above, be sure to set it back to zero for good measure. - //require() calls that also do not end up loading scripts could - //push the number negative too. - context.scriptCount = 0; - - //Make sure any remaining defQueue items get properly processed. - while (defQueue.length) { - args = defQueue.shift(); - if (args[0] === null) { - req.onError(new Error('Mismatched anonymous require.def modules')); - } else { - callDefMain(args, context); + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } } - } + }); + } + return target; + } - //Skip the resume if current context is in priority wait. - if (context.config.priorityWait && !isPriorityDone(context)) { - return; - } + //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 fn.apply(obj, arguments); + }; + } - if (paused.length) { - for (i = 0; (args = paused[i]); i++) { - req.checkDeps.apply(req, args); - } - } + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } - req.checkLoaded(s.ctxName); + //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) { + g = g[part]; + }); + return g; } /** - * Main entry point. + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. * - * If the only argument to require is a string, then the module that - * is represented by that string is fetched for the appropriate context. - * - * If the first argument is an array, then it will be treated as an array - * of dependency string names to fetch. An optional function callback can - * be specified to execute when all of those dependencies are available. + * @returns {Error} */ - require = function (deps, callback, contextName, relModuleName) { - var context, config; - if (typeof deps === "string" && !isFunction(callback)) { - //Just return the module wanted. In this scenario, the - //second arg (if passed) is just the contextName. - return require.get(deps, callback, contextName, relModuleName); - } - // Dependencies first - if (!require.isArray(deps)) { - // deps is a config object - config = deps; - if (require.isArray(callback)) { - // Adjust args if there are dependencies - deps = callback; - callback = contextName; - contextName = relModuleName; - relModuleName = arguments[4]; - } else { - deps = []; - } - } + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } - main(null, deps, callback, config, contextName, relModuleName); + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } - //If the require call does not trigger anything new to load, - //then resume the dependency processing. Context will be undefined - //on first run of require. - context = s.contexts[(contextName || (config && config.context) || s.ctxName)]; - if (context && context.scriptCount === 0) { - resume(context); + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; } - //Returning undefined for Spidermonky strict checking in Komodo - return undefined; - }; + cfg = requirejs; + requirejs = undefined; + } - //Alias for caja compliance internally - - //specifically: "Dynamically computed names should use require.async()" - //even though this spec isn't really decided on. - //Since it is here, use this alias to make typing shorter. - req = require; + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } - /** - * Any errors that require explicitly generates will be passed to this - * function. Intercept/override it if you want custom error handling. - * If you do override it, this method should *always* throw an error - * to stop the execution flow correctly. Otherwise, other weird errors - * will occur. - * @param {Error} err the error object. - */ - req.onError = function (err) { - throw err; - }; + 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: {}, + 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; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // 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; + } + } + } + } - /** - * The function that handles definitions of modules. Differs from - * require() in that a string for the module should be the first argument, - * and the function to execute after dependencies are loaded should - * return a value to define the module corresponding to the first argument's - * name. - */ - define = req.def = function (name, deps, callback, contextName) { - var i, scripts, script, node = currentlyAddingScript; + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + 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 = name.split('/'); + lastIndex = name.length - 1; + + // 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, ''); + } - //Allow for anonymous functions - if (typeof name !== 'string') { - //Adjust args appropriately - contextName = callback; - callback = deps; - deps = name; - name = null; - } + // 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); + } - //This module may not have dependencies - if (!req.isArray(deps)) { - contextName = callback; - callback = deps; - deps = []; - } + trimDots(name); + name = name.join('/'); + } - //If no name, and callback is a function, then figure out if it a - //CommonJS thing with dependencies. - if (!name && !deps.length && req.isFunction(callback)) { - //Remove comments from the callback string, - //look for require calls, and pull them into the dependencies. - callback - .toString() - .replace(commentRegExp, "") - .replace(cjsRequireRegExp, function (match, dep) { - deps.push(dep); - }); + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } - //May be a CommonJS thing even without require calls, but still - //could use exports, and such, so always add those as dependencies. - //This is a bit wasteful for RequireJS modules that do not need - //an exports or module object, but erring on side of safety. - //REQUIRES the function to expect the CommonJS variables in the - //order listed below. - deps = ["require", "exports", "module"].concat(deps); - } + //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. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } - //If in IE 6-8 and hit an anonymous require.def call, do the interactive/ - //currentlyAddingScript scripts stuff. - if (!name && useInteractive) { - scripts = document.getElementsByTagName('script'); - for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { - if (script.readyState === 'interactive') { - node = script; - break; + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); } } - if (!node) { - req.onError(new Error("ERROR: No matching script interactive for " + callback)); - } - name = node.getAttribute("data-requiremodule"); + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; } - if (typeof name === 'string') { - //Do not try to auto-register a jquery later. - //Do this work here and in main, since for IE/useInteractive, this function - //is the earliest touch-point. - s.contexts[s.ctxName].jQueryDef = (name === "jquery"); + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } } - //Always save off evaluating the def call until the script onload handler. - //This allows multiple modules to be in a file without prematurely - //tracing dependencies, and allows for anonymous module support, - //where the module name is not known until the script onload event - //occurs. - defQueue.push([name, deps, callback, null, contextName]); - }; + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } - main = function (name, deps, callback, config, contextName, relModuleName) { - //Grab the context, or create a new one for the given context name. - var context, newContext, loaded, pluginPrefix, - canSetContext, prop, newLength, outDeps, mods, paths, index, i, - deferMods, deferModArgs, lastModArg, waitingName, packages, - packagePaths; - - contextName = contextName ? contextName : (config && config.context ? config.context : s.ctxName); - context = s.contexts[contextName]; - - if (name) { - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - // Pull off any plugin prefix. - index = name.indexOf("!"); - if (index !== -1) { - pluginPrefix = name.substring(0, index); + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); name = name.substring(index + 1, name.length); - } else { - //Could be that the plugin name should be auto-applied. - //Used by i18n plugin to enable anonymous i18n modules, but - //still associating the auto-generated name with the i18n plugin. - pluginPrefix = context.defPlugin[name]; + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); } - //>>excludeEnd("requireExcludePlugin"); + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; - //If module already defined for context, or already waiting to be - //evaluated, leave. - waitingName = context.waiting[name]; - if (context && (context.defined[name] || (waitingName && waitingName !== ap[name]))) { - return; + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); } - } - if (contextName !== s.ctxName) { - //If nothing is waiting on being loaded in the current context, - //then switch s.ctxName to current contextName. - loaded = (s.contexts[s.ctxName] && s.contexts[s.ctxName].loaded); - canSetContext = true; - if (loaded) { - for (prop in loaded) { - if (!(prop in empty)) { - if (!loaded[prop]) { - canSetContext = false; - break; - } + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // 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. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); } } - if (canSetContext) { - s.ctxName = contextName; - } - } - if (!context) { - newContext = { - contextName: contextName, - config: { - waitSeconds: 7, - baseUrl: s.baseUrl || "./", - paths: {}, - packages: {} - }, - waiting: [], - specified: { - "require": true, - "exports": true, - "module": true - }, - loaded: {}, - scriptCount: 0, - urlFetched: {}, - defPlugin: {}, - defined: {}, - modifiers: {} + //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) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix }; + } - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - if (s.plugins.newContext) { - s.plugins.newContext(newContext); + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); } - //>>excludeEnd("requireExcludePlugin"); - context = s.contexts[contextName] = newContext; + return mod; } - //If have a config object, update the context's config object with - //the config values. - if (config) { - //Make sure the baseUrl ends in a slash. - if (config.baseUrl) { - if (config.baseUrl.charAt(config.baseUrl.length - 1) !== "/") { - config.baseUrl += "/"; + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); } } + } - //Save off the paths and packages since they require special processing, - //they are additive. - paths = context.config.paths; - packages = context.config.packages; - - //Mix in the config values, favoring the new values over - //existing ones in context.config. - req.mixin(context.config, config, true); + function onError(err, errback) { + var ids = err.requireModules, + notified = false; - //Adjust paths if necessary. - if (config.paths) { - for (prop in config.paths) { - if (!(prop in empty)) { - paths[prop] = config.paths[prop]; + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } } + }); + + if (!notified) { + req.onError(err); } - context.config.paths = paths; } + } - packagePaths = config.packagePaths; - if (packagePaths || config.packages) { - //Convert packagePaths into a packages config. - if (packagePaths) { - for (prop in packagePaths) { - if (!(prop in empty)) { - configurePackageDir(packages, packagePaths[prop], prop); - } + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + //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, 0].concat(globalDefQueue)); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); } } - - //Adjust packages if necessary. - if (config.packages) { - configurePackageDir(packages, config.packages); + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); } - - //Done with modifications, assing packages back to context config - context.config.packages = packages; } + }; - //If priority loading is in effect, trigger the loads now - if (config.priority) { - //Create a separate config property that can be - //easily tested for config priority completion. - //Do this instead of wiping out the config.priority - //in case it needs to be inspected for debug purposes later. - req(config.priority); - context.config.priorityWait = config.priority; - } + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } - //If a deps array or a config callback is specified, then call - //require with those args. This is useful when require is defined as a - //config object before require.js is loaded. - if (config.deps || config.callback) { - req(config.deps || [], config.callback); - } + function breakCycle(mod, traced, processed) { + var id = mod.map.id; - //>>excludeStart("requireExcludePageLoad", pragmas.requireExcludePageLoad); - //Set up ready callback, if asked. Useful when require is defined as a - //config object before require.js is loaded. - if (config.ready) { - req.ready(config.ready); + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; } - //>>excludeEnd("requireExcludePageLoad"); + } + + function checkLoaded() { + 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 = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; - //If it is just a config block, nothing else, - //then return. - if (!deps) { + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { return; } - } - //Normalize dependency strings: need to determine if they have - //prefixes and to also normalize any relative paths. Replace the deps - //array of strings with an array of objects. - if (deps) { - outDeps = deps; - deps = []; - for (i = 0; i < outDeps.length; i++) { - deps[i] = req.splitPrefix(outDeps[i], (name || relModuleName), context); - } - } + inCheckLoaded = true; - //Store the module for later evaluation - newLength = context.waiting.push({ - name: name, - deps: deps, - callback: callback - }); + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; - if (name) { - //Store index of insertion for quick lookup - context.waiting[name] = newLength - 1; - - //Mark the module as specified so no need to fetch it again. - //Important to set specified here for the - //pause/resume case where there are multiple modules in a file. - context.specified[name] = true; - - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); - //Load any modifiers for the module. - mods = context.modifiers[name]; - if (mods) { - req(mods, contextName); - deferMods = mods.__deferMods; - if (deferMods) { - for (i = 0; i < deferMods.length; i++) { - deferModArgs = deferMods[i]; - - //Add the context name to the def call. - lastModArg = deferModArgs[deferModArgs.length - 1]; - if (lastModArg === undefined) { - deferModArgs[deferModArgs.length - 1] = contextName; - } else if (typeof lastModArg === "string") { - deferMods.push(contextName); - } + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } - require.def.apply(require, deferModArgs); + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } } } - } - //>>excludeEnd("requireExcludeModify"); - } + }); - //If the callback is not an actual function, it means it already - //has the definition of the module as a literal value. - if (name && callback && !req.isFunction(callback)) { - context.defined[name] = callback; - } + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } - //If a pluginPrefix is available, call the plugin, or load it. - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - if (pluginPrefix) { - callPlugin(pluginPrefix, context, { - name: "require", - args: [name, deps, callback, context] - }); - } - //>>excludeEnd("requireExcludePlugin"); - - //Hold on to the module until a script load or other adapter has finished - //evaluating the whole file. This helps when a file has more than one - //module in it -- dependencies are not traced and fetched until the whole - //file is processed. - s.paused.push([pluginPrefix, name, deps, context]); - - //Set loaded here for modules that are also loaded - //as part of a layer, where onScriptLoad is not fired - //for those cases. Do this after the inline define and - //dependency tracing is done. - //Also check if auto-registry of jQuery needs to be skipped. - if (name) { - context.loaded[name] = true; - context.jQueryDef = (name === "jquery"); - } - }; + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } - /** - * Simple function to mix in properties from source into target, - * but only if target does not already have a property of the same name. - */ - req.mixin = function (target, source, force) { - for (var prop in source) { - if (!(prop in empty) && (!(prop in target) || force)) { - target[prop] = source[prop]; + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //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 = 0; + checkLoaded(); + }, 50); + } } + + inCheckLoaded = false; } - return req; - }; - req.version = version; + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; - //Set up page state. - s = req.s = { - ctxName: defContextName, - contexts: {}, - paused: [], - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - plugins: { - defined: {}, - callbacks: {}, - waiting: {} - }, - //>>excludeEnd("requireExcludePlugin"); - //Stores a list of URLs that should not get async script tag treatment. - skipAsync: {}, - isBrowser: isBrowser, - isPageLoaded: !isBrowser, - readyCalls: [], - doc: isBrowser ? document : null - }; + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; - req.isBrowser = s.isBrowser; - if (isBrowser) { - s.head = document.getElementsByTagName("head")[0]; - //If BASE tag is in play, using appendChild is a problem for IE6. - //When that browser dies, this can be removed. Details in this jQuery bug: - //http://dev.jquery.com/ticket/2709 - baseElement = document.getElementsByTagName("base")[0]; - if (baseElement) { - s.head = baseElement.parentNode; - } - } + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - /** - * Sets up a plugin callback name. Want to make it easy to test if a plugin - * needs to be called for a certain lifecycle event by testing for - * if (s.plugins.onLifeCyleEvent) so only define the lifecycle event - * if there is a real plugin that registers for it. - */ - function makePluginCallback(name, returnOnTrue) { - var cbs = s.plugins.callbacks[name] = []; - s.plugins[name] = function () { - for (var i = 0, cb; (cb = cbs[i]); i++) { - if (cb.apply(null, arguments) === true && returnOnTrue) { - return true; + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; } - } - return false; - }; - } - /** - * Registers a new plugin for require. - */ - req.plugin = function (obj) { - var i, prop, call, prefix = obj.prefix, cbs = s.plugins.callbacks, - waiting = s.plugins.waiting[prefix], generics, - defined = s.plugins.defined, contexts = s.contexts, context; - - //Do not allow redefinition of a plugin, there may be internal - //state in the plugin that could be lost. - if (defined[prefix]) { - return req; - } + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } 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) { + this.emit('error', err); + }); + } - //Save the plugin. - defined[prefix] = obj; + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); - //Set up plugin callbacks for methods that need to be generic to - //require, for lifecycle cases where it does not care about a particular - //plugin, but just that some plugin work needs to be done. - generics = ["newContext", "isWaiting", "orderDeps"]; - for (i = 0; (prop = generics[i]); i++) { - if (!s.plugins[prop]) { - makePluginCallback(prop, prop === "isWaiting"); - } - cbs[prop].push(obj[prop]); - } + this.errback = errback; - //Call newContext for any contexts that were already created. - if (obj.newContext) { - for (prop in contexts) { - if (!(prop in empty)) { - context = contexts[prop]; - obj.newContext(context); + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); } - } - } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, - //If there are waiting requests for a plugin, execute them now. - if (waiting) { - for (i = 0; (call = waiting[i]); i++) { - if (obj[call.name]) { - obj[call.name].apply(null, call.args); + fetch: function () { + if (this.fetched) { + return; } - } - delete s.plugins.waiting[prefix]; - } + this.fetched = true; - return req; - }; - //>>excludeEnd("requireExcludePlugin"); + context.startTime = (new Date()).getTime(); - /** - * As of jQuery 1.4.3, it supports a readyWait property that will hold off - * calling jQuery ready callbacks until all scripts are loaded. Be sure - * to track it if readyWait is available. Also, since jQuery 1.4.3 does - * not register as a module, need to do some global inference checking. - * Even if it does register as a module, not guaranteed to be the precise - * name of the global. If a jQuery is tracked for this context, then go - * ahead and register it as a module too, if not already in process. - */ - function jQueryCheck(context, jqCandidate) { - if (!context.jQuery) { - var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null); - if ($ && "readyWait" in $) { - context.jQuery = $; - - //Manually create a "jquery" module entry if not one already - //or in process. - if (!context.defined.jquery && !context.jQueryDef) { - context.defined.jquery = $; - } + var map = this.map; - //Make sure - if (context.scriptCount) { - $.readyWait += 1; - context.jQueryIncremented = true; + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); } - } - } - } + }, - /** - * Internal method used by environment adapters to complete a load event. - * A load event could be a script load or just a load pass from a synchronous - * load call. - * @param {String} moduleName the name of the module to potentially complete. - * @param {Object} context the context object - */ - req.completeLoad = function (moduleName, context) { - //If there is a waiting require.def call - var args; - while (defQueue.length) { - args = defQueue.shift(); - if (args[0] === null) { - args[0] = moduleName; - break; - } else if (args[0] === moduleName) { - //Found matching require.def call for this script! - break; - } else { - //Some other named require.def call, most likely the result - //of a build layer that included many require.def calls. - callDefMain(args, context); - } - } - if (args) { - callDefMain(args, context); - } + load: function () { + var url = this.map.url; - //Mark the script as loaded. Note that this can be different from a - //moduleName that maps to a require.def call. This line is important - //for traditional browser scripts. - context.loaded[moduleName] = true; + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } - //If a global jQuery is defined, check for it. Need to do it here - //instead of main() since stock jQuery does not register as - //a module via define. - jQueryCheck(context); + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + this.fetch(); + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //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) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // 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) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } - context.scriptCount -= 1; - resume(context); - }; + this.exports = exports; - /** - * Legacy function, remove at some point - */ - req.pause = req.resume = function () {}; + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; - /** - * Trace down the dependencies to see if they are loaded. If not, trigger - * the load. - * @param {String} pluginPrefix the plugin prefix, if any associated with the name. - * - * @param {String} name: the name of the module that has the dependencies. - * - * @param {Array} deps array of dependencies. - * - * @param {Object} context: the loading context. - * - * @private - */ - req.checkDeps = function (pluginPrefix, name, deps, context) { - //Figure out if all the modules are loaded. If the module is not - //being loaded or already loaded, add it to the "to load" list, - //and request it to be loaded. - var i, dep; - - if (pluginPrefix) { - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - callPlugin(pluginPrefix, context, { - name: "checkDeps", - args: [name, deps, context] - }); - //>>excludeEnd("requireExcludePlugin"); - } else { - for (i = 0; (dep = deps[i]); i++) { - if (!context.specified[dep.fullName]) { - context.specified[dep.fullName] = true; - - //Reset the start time to use for timeouts - context.startTime = (new Date()).getTime(); - - //If a plugin, call its load method. - if (dep.prefix) { - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - callPlugin(dep.prefix, context, { - name: "load", - args: [dep.name, context.contextName] + if (req.onResourceLoad) { + req.onResourceLoad(context, this.map, this.depMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + 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 }); - //>>excludeEnd("requireExcludePlugin"); - } else { - req.load(dep.name, context.contextName); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //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 + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //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) { + 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) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //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) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + 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); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; } } - } - }; + }; - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); - /** - * Register a module that modifies another module. The modifier will - * only be called once the target module has been loaded. - * - * First syntax: - * - * require.modify({ - * "some/target1": "my/modifier1", - * "some/target2": "my/modifier2", - * }); - * - * With this syntax, the my/modifier1 will only be loaded when - * "some/target1" is loaded. - * - * Second syntax, defining a modifier. - * - * require.modify("some/target1", "my/modifier", - * ["some/target1", "some/other"], - * function (target, other) { - * //Modify properties of target here. - * Only properties of target can be modified, but - * target cannot be replaced. - * } - * ); - */ - req.modify = function (target, name, deps, callback, contextName) { - var prop, modifier, list, - cName = (typeof target === "string" ? contextName : name) || s.ctxName, - context = s.contexts[cName], - mods = context.modifiers; - - if (typeof target === "string") { - //A modifier module. - //First store that it is a modifier. - list = mods[target] || (mods[target] = []); - if (!list[name]) { - list.push(name); - list[name] = true; + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } + } - //Trigger the normal module definition logic if the target - //is already in the system. - if (context.specified[target]) { - req.def(name, deps, callback, contextName); + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } } else { - //Hold on to the execution/dependency checks for the modifier - //until the target is fetched. - (list.__deferMods || (list.__deferMods = [])).push([name, deps, callback, contextName]); + node.removeEventListener(name, func, false); } - } else { - //A list of modifiers. Save them for future reference. - for (prop in target) { - if (!(prop in empty)) { - //Store the modifier for future use. - modifier = target[prop]; - list = mods[prop] || (context.modifiers[prop] = []); - if (!list[modifier]) { - list.push(modifier); - list[modifier] = true; - - if (context.specified[prop]) { - //Load the modifier right away. - req([modifier], cName); - } - } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(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. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + 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. + callGetModule(args); } } } - }; - //>>excludeEnd("requireExcludeModify"); - req.isArray = function (it) { - return ostring.call(it) === "[object Array]"; - }; + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } - req.isFunction = isFunction; + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; - /** - * Gets one module's exported value. This method is used by require(). - * It is broken out as a separate function to allow a host environment - * shim to overwrite this function with something appropriate for that - * environment. - * - * @param {String} moduleName the name of the module. - * @param {String} [contextName] the name of the context to use. Uses - * default context if no contextName is provided. You should never - * pass the contextName explicitly -- it is handled by the require() code. - * @param {String} [relModuleName] a module name to use for relative - * module name lookups. You should never pass this argument explicitly -- - * it is handled by the require() code. - * - * @returns {Object} the exported module value. - */ - req.get = function (moduleName, contextName, relModuleName) { - if (moduleName === "require" || moduleName === "exports" || moduleName === "module") { - req.onError(new Error("Explicit require of " + moduleName + " is not allowed.")); - } - contextName = contextName || s.ctxName; + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); - var ret, context = s.contexts[contextName]; + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } - //Normalize module name, if it contains . or .. - moduleName = req.normalizeName(moduleName, relModuleName, context); + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } - ret = context.defined[moduleName]; - if (ret === undefined) { - req.onError(new Error("require: module name '" + - moduleName + - "' has not been loaded yet for context: " + - contextName)); - } - return ret; - }; + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; - /** - * Makes the request to load a module. May be an async load depending on - * the environment and the circumstance of the load call. Override this - * method in a host environment shim to do something specific for that - * environment. - * - * @param {String} moduleName the name of the module. - * @param {String} contextName the name of the context to use. - */ - req.load = function (moduleName, contextName) { - var context = s.contexts[contextName], - urlFetched = context.urlFetched, - loaded = context.loaded, url; - s.isDone = false; - - //Only set loaded to false for tracking if it has not already been set. - if (!loaded[moduleName]) { - loaded[moduleName] = false; - } + pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } - if (contextName !== s.ctxName) { - //Not in the right context now, hold on to it until - //the current context finishes all its loading. - contextLoads.push(arguments); - } else { - //First derive the path name for the module. - url = req.nameToUrl(moduleName, null, contextName); - if (!urlFetched[url]) { - context.scriptCount += 1; - req.attach(url, contextName, moduleName); - urlFetched[url] = true; - - //If tracking a jQuery, then make sure its readyWait - //is incremented to prevent its ready callbacks from - //triggering too soon. - if (context.jQuery && !context.jQueryIncremented) { - context.jQuery.readyWait += 1; - context.jQueryIncremented = true; + //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, ''); + }); } - } - } - }; - req.jsExtRegExp = /\.js$/; + //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) { + //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); + } + }); - /** - * Given a relative module name, like ./something, normalize it to - * a real name that can be mapped to a path. - * @param {String} name the relative name - * @param {String} baseName a real name that the name arg is relative - * to. - * @param {Object} context - * @returns {String} normalized name - */ - req.normalizeName = function (name, baseName, context) { - //Adjust any relative paths. - var part; - if (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 (context.config.packages[baseName]) { - //If the baseName is a package name, then just treat it as one - //name to concat the name with. - baseName = [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. - baseName = baseName.split("/"); - baseName = baseName.slice(0, baseName.length - 1); + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); } + }, - name = baseName.concat(name.split("/")); - for (i = 0; (part = name[i]); i++) { - if (part === ".") { - name.splice(i, 1); - i -= 1; - } else if (part === "..") { - name.splice(i - 1, 2); - i -= 2; + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); } + return ret || (value.exports && getGlobal(value.exports)); } - name = name.join("/"); - } - } - return name; - }; + return fn; + }, - /** - * Splits a name into a possible plugin prefix and - * the module name. If baseName is provided it will - * also normalize the name via require.normalizeName() - * - * @param {String} name the module name - * @param {String} [baseName] base name that name is - * relative to. - * @param {Object} context - * - * @returns {Object} with properties, 'prefix' (which - * may be null), 'name' and 'fullName', which is a combination - * of the prefix (if it exists) and the name. - */ - req.splitPrefix = function (name, baseName, context) { - var index = name.indexOf("!"), prefix = null; - if (index !== -1) { - prefix = name.substring(0, index); - name = name.substring(index + 1, name.length); - } + makeRequire: function (relMap, options) { + options = options || {}; - //Account for relative paths if there is a base name. - name = req.normalizeName(name, baseName, context); + function localRequire(deps, callback, errback) { + var id, map, requireMod; - return { - prefix: prefix, - name: name, - fullName: prefix ? prefix + "!" + name : name - }; - }; + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } - /** - * Converts a module name to a file path. - */ - req.nameToUrl = function (moduleName, ext, contextName, relModuleName) { - var paths, packages, pkg, pkgPath, syms, i, parentModule, url, - context = s.contexts[contextName], - config = context.config; - - //Normalize module name if have a base relative module name to work from. - moduleName = req.normalizeName(moduleName, relModuleName, context); - - //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 or ends with .js, it is just a plain file. - //The slash is important for protocol-less URLs as well as full paths. - if (moduleName.indexOf(":") !== -1 || moduleName.charAt(0) === '/' || req.jsExtRegExp.test(moduleName)) { - //Just a plain path, not module name lookup, so just return it. - //Add extension if it is included. This is a bit wonky, only non-.js things pass - //an extension, this method probably needs to be reworked. - url = moduleName + (ext ? ext : ""); - } else { - //A module that needs to be converted to a path. - paths = config.paths; - packages = config.packages; - - syms = moduleName.split("/"); - //For each module name segment, see if there is a path - //registered for it. Start with most specific name - //and work up from it. - for (i = syms.length; i > 0; i--) { - parentModule = syms.slice(0, i).join("/"); - if (paths[parentModule]) { - syms.splice(0, i, paths[parentModule]); - break; - } else if ((pkg = packages[parentModule])) { - //pkg can have just a string value to the path - //or can be an object with props: - //main, lib, name, location. - pkgPath = pkg.location + '/' + pkg.lib; - //If module name is just the package name, then looking - //for the main module. - if (moduleName === pkg.name) { - pkgPath += '/' + pkg.main; + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + 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 defined[id]; } - syms.splice(0, i, pkgPath); - break; + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; } - } - //Join the path parts together, then figure out if baseUrl is needed. - url = syms.join("/") + (ext || ".js"); - url = (url.charAt(0) === '/' || url.match(/^\w+:/) ? "" : config.baseUrl) + url; - } - return config.urlArgs ? url + - ((url.indexOf('?') === -1 ? '?' : '&') + - config.urlArgs) : url; - }; + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } - /** - * Checks if all modules for a context are loaded, and if so, evaluates the - * new ones in right dependency order. - * - * @private - */ - req.checkLoaded = function (contextName) { - var context = s.contexts[contextName || s.ctxName], - waitInterval = context.config.waitSeconds * 1000, - //It is possible to disable the wait interval by using waitSeconds of 0. - expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), - loaded, defined = context.defined, - modifiers = context.modifiers, waiting, noLoads = "", - hasLoadedProp = false, stillLoading = false, prop, + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - pIsWaiting = s.plugins.isWaiting, pOrderDeps = s.plugins.orderDeps, - //>>excludeEnd("requireExcludePlugin"); + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, - i, module, allDone, loads, loadArgs, err; + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); - //If already doing a checkLoaded call, - //then do not bother checking loaded state. - if (context.isCheckLoaded) { - return; - } + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + 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); + } + }); - //Determine if priority loading is done. If so clear the priority. If - //not, then do not check - if (context.config.priorityWait) { - if (isPriorityDone(context)) { - //Call resume, since it could have - //some waiting dependencies to trace. - resume(context); - } else { - return; - } - } + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } - //Signal that checkLoaded is being require, so other calls that could be triggered - //by calling a waiting callback that then calls require and then this function - //should not proceed. At the end of this function, if there are still things - //waiting, then checkLoaded will be called again. - context.isCheckLoaded = true; - - //Grab waiting and loaded lists here, since it could have changed since - //this function was first called. - waiting = context.waiting; - loaded = context.loaded; - - //See if anything is still in flight. - for (prop in loaded) { - if (!(prop in empty)) { - hasLoadedProp = true; - if (!loaded[prop]) { - if (expired) { - noLoads += prop + " "; - } else { - stillLoading = true; - break; + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * 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 overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; } + + callGetModule(args); } - } - } - //Check for exit conditions. - if (!hasLoadedProp && !waiting.length - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - && (!pIsWaiting || !pIsWaiting(context)) - //>>excludeEnd("requireExcludePlugin"); - ) { - //If the loaded object had no items, then the rest of - //the work below does not need to be done. - context.isCheckLoaded = false; - return; - } - if (expired && noLoads) { - //If wait time expired, throw error of unloaded modules. - err = new Error("require.js load timeout for modules: " + noLoads); - err.requireType = "timeout"; - err.requireModules = noLoads; - req.onError(err); - } - if (stillLoading) { - //Something is still waiting to load. Wait for it. - context.isCheckLoaded = false; - if (isBrowser || isWebWorker) { - setTimeout(function () { - req.checkLoaded(contextName); - }, 50); - } - return; - } + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } - //Order the dependencies. Also clean up state because the evaluation - //of modules might create new loading tasks, so need to reset. - //Be sure to call plugins too. - context.waiting = []; - context.loaded = {}; - - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - //Call plugins to order their dependencies, do their - //module definitions. - if (pOrderDeps) { - pOrderDeps(context); - } - //>>excludeEnd("requireExcludePlugin"); - - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); - //Before defining the modules, give priority treatment to any modifiers - //for modules that are already defined. - for (prop in modifiers) { - if (!(prop in empty)) { - if (defined[prop]) { - req.execModifiers(prop, {}, waiting, context); + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * 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, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; } - } - } - //>>excludeEnd("requireExcludeModify"); - //Define the modules, doing a depth first search. - for (i = 0; (module = waiting[i]); i++) { - req.exec(module, {}, waiting, context); - } + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } - //Indicate checkLoaded is now done. - context.isCheckLoaded = false; - - if (context.waiting.length - //>>excludeStart("requireExcludePlugin", pragmas.requireExcludePlugin); - || (pIsWaiting && pIsWaiting(context)) - //>>excludeEnd("requireExcludePlugin"); - ) { - //More things in this context are waiting to load. They were probably - //added while doing the work above in checkLoaded, calling module - //callbacks that triggered other require calls. - req.checkLoaded(contextName); - } else if (contextLoads.length) { - //Check for other contexts that need to load things. - //First, make sure current context has no more things to - //load. After defining the modules above, new require calls - //could have been made. - loaded = context.loaded; - allDone = true; - for (prop in loaded) { - if (!(prop in empty)) { - if (!loaded[prop]) { - allDone = false; - break; + //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. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } - } - if (allDone) { - s.ctxName = contextLoads[0][1]; - loads = contextLoads; - //Reset contextLoads in case some of the waiting loads - //are for yet another context. - contextLoads = []; - for (i = 0; (loadArgs = loads[i]); i++) { - req.load.apply(req, loadArgs); + 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) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + 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))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); } } - } else { - //Make sure we reset to default context. - s.ctxName = defContextName; - s.isDone = true; - if (req.callReady) { - req.callReady(); - } - } - }; - - /** - * Helper function that creates a setExports function for a "module" - * CommonJS dependency. Do this here to avoid creating a closure that - * is part of a loop in require.exec. - */ - function makeSetExports(moduleObj) { - return function (exports) { - moduleObj.exports = exports; - }; - } - - function makeContextModuleFunc(name, contextName, moduleName) { - return function () { - //A version of a require function that forces a contextName value - //and also passes a moduleName value for items that may need to - //look up paths relative to the moduleName - var args = [].concat(aps.call(arguments, 0)); - args.push(contextName, moduleName); - return (name ? require[name] : require).apply(null, args); }; - } - /** - * Helper function that creates a require function object to give to - * modules that ask for it as a dependency. It needs to be specific - * per module because of the implication of path mappings that may - * need to be relative to the module name. - */ - function makeRequire(context, moduleName) { - var contextName = context.contextName, - modRequire = makeContextModuleFunc(null, contextName, moduleName); - - req.mixin(modRequire, { - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); - modify: makeContextModuleFunc("modify", contextName, moduleName), - //>>excludeEnd("requireExcludeModify"); - def: makeContextModuleFunc("def", contextName, moduleName), - get: makeContextModuleFunc("get", contextName, moduleName), - nameToUrl: makeContextModuleFunc("nameToUrl", contextName, moduleName), - ready: req.ready, - context: context, - config: context.config, - isBrowser: s.isBrowser - }); - return modRequire; + context.require = context.makeRequire(); + return context; } /** - * Executes the modules in the correct order. + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. * - * @private + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. */ - req.exec = function (module, traced, waiting, context) { - //Some modules are just plain script files, abddo not have a formal - //module definition, - if (!module) { - //Returning undefined for Spidermonky strict checking in Komodo - return undefined; - } + req = requirejs = function (deps, callback, errback, optional) { - var name = module.name, cb = module.callback, deps = module.deps, j, dep, - defined = context.defined, ret, args = [], depModule, cjsModule, - usingExports = false, depName; + //Find the right context, use default + var context, config, + contextName = defContextName; - //If already traced or defined, do not bother a second time. - if (name) { - if (traced[name] || name in defined) { - return defined[name]; + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; } - - //Mark this module as being traced, so that it is not retraced (as in a circular - //dependency) - traced[name] = true; } - if (deps) { - for (j = 0; (dep = deps[j]); j++) { - depName = dep.name; - if (depName === "require") { - depModule = makeRequire(context, name); - } else if (depName === "exports") { - //CommonJS module spec 1.1 - depModule = defined[name] = {}; - usingExports = true; - } else if (depName === "module") { - //CommonJS module spec 1.1 - cjsModule = depModule = { - id: name, - uri: name ? req.nameToUrl(name, null, context.contextName) : undefined - }; - cjsModule.setExports = makeSetExports(cjsModule); - } else { - //Get dependent module. It could not exist, for a circular - //dependency or if the loaded dependency does not actually call - //require. Favor not throwing an error here if undefined because - //we want to allow code that does not use require as a module - //definition framework to still work -- allow a web site to - //gradually update to contained modules. That is more - //important than forcing a throw for the circular dependency case. - depModule = depName in defined ? defined[depName] : (traced[depName] ? undefined : req.exec(waiting[waiting[depName]], traced, waiting, context)); - } - - args.push(depModule); - } + if (config && config.context) { + contextName = config.context; } - //Call the callback to define the module, if necessary. - cb = module.callback; - if (cb && req.isFunction(cb)) { - ret = req.execCb(name, cb, args); - if (name) { - //If using exports and the function did not return a value, - //and the "module" object for this definition function did not - //define an exported value, then use the exports object. - if (usingExports && ret === undefined && (!cjsModule || !("exports" in cjsModule))) { - ret = defined[name]; - } else { - if (cjsModule && "exports" in cjsModule) { - ret = defined[name] = cjsModule.exports; - } else { - if (name in defined && !usingExports) { - req.onError(new Error(name + " has already been defined")); - } - defined[name] = ret; - } - } - } + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); } - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); - //Execute modifiers, if they exist. - req.execModifiers(name, traced, waiting, context); - //>>excludeEnd("requireExcludeModify"); + if (config) { + context.configure(config); + } - return ret; + return context.require(deps, callback, errback); }; /** - * Executes a module callack function. Broken out as a separate function - * solely to allow the build system to sequence the files in the built - * layer in the right sequence. - * @param {String} name the module name. - * @param {Function} cb the module callback/definition function. - * @param {Array} args The arguments (dependent modules) to pass to callback. - * - * @private + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. */ - req.execCb = function (name, cb, args) { - return cb.apply(null, args); + req.config = function (config) { + return req(config); }; - //>>excludeStart("requireExcludeModify", pragmas.requireExcludeModify); /** - * Executes modifiers for the given module name. - * @param {String} target - * @param {Object} traced - * @param {Object} context - * - * @private + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. */ - req.execModifiers = function (target, traced, waiting, context) { - var modifiers = context.modifiers, mods = modifiers[target], mod, i; - if (mods) { - for (i = 0; i < mods.length; i++) { - mod = mods[i]; - //Not all modifiers define a module, they might collect other modules. - //If it is just a collection it will not be in waiting. - if (mod in waiting) { - req.exec(waiting[waiting[mod]], traced, waiting, context); - } - } - delete modifiers[target]; - } - }; - //>>excludeEnd("requireExcludeModify"); + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; /** - * callback for script loads, used to check status of loading. - * - * @param {Event} evt the event from the browser for the script - * that was loaded. - * - * @private + * Export require as a global, but only if it does not already exist. */ - req.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. - var node = evt.currentTarget || evt.srcElement, contextName, moduleName, - context; - if (evt.type === "load" || readyRegExp.test(node.readyState)) { - //Pull out the name of the module and the context. - contextName = node.getAttribute("data-requirecontext"); - moduleName = node.getAttribute("data-requiremodule"); - context = s.contexts[contextName]; - - req.completeLoad(moduleName, context); - - //Clean up script binding. - if (node.removeEventListener) { - node.removeEventListener("load", req.onScriptLoad, false); - } else { - //Probably IE. If not it will throw an error, which will be - //useful to know. - node.detachEvent("onreadystatechange", req.onScriptLoad); - } + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + 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 () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * 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'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; }; /** - * Attaches the script represented by the URL to the current - * environment. Right now only supports browser loading, - * but can be redefined in other environments to do the right thing. - * @param {String} url the url of the script to attach. - * @param {String} contextName the name of the context that wants the script. - * @param {moduleName} the name of the module that is associated with the script. - * @param {Function} [callback] optional callback, defaults to require.onScriptLoad - * @param {String} [type] optional type, defaults to text/javascript + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. */ - req.attach = function (url, contextName, moduleName, callback, type) { - var node, loaded, context; + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; if (isBrowser) { //In the browser so use a script tag - callback = callback || req.onScriptLoad; - node = document.createElement("script"); - node.type = type || "text/javascript"; - node.charset = "utf-8"; - //Use async so Gecko does not block on executing the script if something - //like a long-polling comet tag is being run first. Gecko likes - //to evaluate scripts in DOM order, even for dynamic scripts. - //It will fetch them async, but only evaluate the contents in DOM - //order, so a long-polling script tag can delay execution of scripts - //after it. But telling Gecko we expect async gets us the behavior - //we want -- execute it whenever it is finished downloading. Only - //Helps Firefox 3.6+ - //Allow some URLs to not be fetched async. Mostly helps the order! - //plugin - if (!s.skipAsync[url]) { - node.async = true; - } - node.setAttribute("data-requirecontext", contextName); - node.setAttribute("data-requiremodule", moduleName); - - //Set up load listener. - if (node.addEventListener) { - node.addEventListener("load", callback, false); - } else { - //Probably IE. If not it will throw an error, which will be - //useful to know. IE (at least 6-8) do not fire + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //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) { + //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so - //we cannot tie the anonymous require.def call to a name. - //However, IE reports the script as being in "interactive" - //readyState at the time of the require.def call. + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. useInteractive = true; - node.attachEvent("onreadystatechange", callback); + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); } node.src = url; //For some cache cases in IE 6-8, the script executes before the end - //of the appendChild execution, so to tie an anonymous require.def + //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { - s.head.insertBefore(node, baseElement); + head.insertBefore(node, baseElement); } else { - s.head.appendChild(node); + head.appendChild(node); } currentlyAddingScript = null; + return node; } else if (isWebWorker) { - //In a web worker, use importScripts. This is not a very - //efficient use of importScripts, importScripts will block until - //its script is downloaded and evaluated. However, if web workers - //are in play, the expectation that a build has been done so that - //only one script needs to be loaded anyway. This may need to be - //reevaluated if other use cases become common. - context = s.contexts[contextName]; - loaded = context.loaded; - loaded[moduleName] = false; - importScripts(url); - - //Account for anonymous modules - req.completeLoad(moduleName, context); + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation that a build has been done so that + //only one script needs to be loaded anyway. This may need to be + //reevaluated if other use cases become common. + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } } - return null; }; - //Determine what baseUrl should be if not already defined via a require config object - s.baseUrl = cfg.baseUrl; - if (isBrowser && (!s.baseUrl || !s.head)) { - //Figure out baseUrl. Get it from the script tag with require.js in it. - scripts = document.getElementsByTagName("script"); - if (cfg.baseUrlMatch) { - rePkg = cfg.baseUrlMatch; - } else { - //>>includeStart("jquery", pragmas.jquery); - rePkg = /(requireplugins-|require-)?jquery[\-\d\.]*(min)?\.js(\W|$)/i; - //>>includeEnd("jquery"); - - //>>includeStart("dojoConvert", pragmas.dojoConvert); - rePkg = /dojo\.js(\W|$)/i; - //>>includeEnd("dojoConvert"); - - //>>excludeStart("dojoConvert", pragmas.dojoConvert); - - //>>excludeStart("jquery", pragmas.jquery); - rePkg = /(allplugins-)?require\.js(\W|$)/i; - //>>excludeEnd("jquery"); - - //>>excludeEnd("dojoConvert"); + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; } - for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { - //Set the "head" where we can append children by + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by //using the script's parent. - if (!s.head) { - s.head = script.parentNode; + if (!head) { + head = script.parentNode; } //Look for a data-main attribute to set main script for the page - //to load. - if (!cfg.deps) { - dataMain = script.getAttribute('data-main'); - if (dataMain) { - cfg.deps = [dataMain]; + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one. + if (!cfg.baseUrl) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; } - } - //Using .src instead of getAttribute to get an absolute URL. - //While using a relative URL will be fine for script tags, other - //URLs used for text! resources that use XHR calls might benefit - //from an absolute URL. - src = script.src; - if (src && !s.baseUrl) { - m = src.match(rePkg); - if (m) { - s.baseUrl = src.substring(0, m.index); - break; + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; } - } + }); } - //>>excludeStart("requireExcludePageLoad", pragmas.requireExcludePageLoad); - //****** START page load functionality **************** /** - * Sets the page as loaded and triggers check for all modules loaded. + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. */ - req.pageLoaded = function () { - if (!s.isPageLoaded) { - s.isPageLoaded = true; - if (scrollIntervalId) { - clearInterval(scrollIntervalId); - } + define = function (name, deps, callback) { + var node, context; - //Part of a fix for FF < 3.6 where readyState was not set to - //complete so libraries like jQuery that check for readyState - //after page load where not getting initialized correctly. - //Original approach suggested by Andrea Giammarchi: - //http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html - //see other setReadyState reference for the rest of the fix. - if (setReadyState) { - document.readyState = "complete"; - } + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } - req.callReady(); + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; } - }; - /** - * Internal function that calls back any ready functions. If you are - * integrating RequireJS with another library without require.ready support, - * you can define this method to call your page ready code instead. - */ - req.callReady = function () { - var callbacks = s.readyCalls, i, callback, contexts, context, prop; - - if (s.isPageLoaded && s.isDone) { - if (callbacks.length) { - s.readyCalls = []; - for (i = 0; (callback = callbacks[i]); i++) { - callback(); - } + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, '') + .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 + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } + } - //If jQuery with readyWait is being tracked, updated its - //readyWait count. - contexts = s.contexts; - for (prop in contexts) { - if (!(prop in empty)) { - context = contexts[prop]; - if (context.jQueryIncremented) { - context.jQuery.readyWait -= 1; - context.jQueryIncremented = false; - } + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); } + context = contexts[node.getAttribute('data-requirecontext')]; } } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); }; - /** - * Registers functions to call when the page is loaded - */ - req.ready = function (callback) { - if (s.isPageLoaded && s.isDone) { - callback(); - } else { - s.readyCalls.push(callback); - } - return req; + define.amd = { + jQuery: true }; - if (isBrowser) { - if (document.addEventListener) { - //Standards. Hooray! Assumption here that if standards based, - //it knows about DOMContentLoaded. - document.addEventListener("DOMContentLoaded", req.pageLoaded, false); - window.addEventListener("load", req.pageLoaded, false); - //Part of FF < 3.6 readystate fix (see setReadyState refs for more info) - if (!document.readyState) { - setReadyState = true; - document.readyState = "loading"; - } - } else if (window.attachEvent) { - window.attachEvent("onload", req.pageLoaded); - - //DOMContentLoaded approximation, as found by Diego Perini: - //http://javascript.nwbox.com/IEContentLoaded/ - if (self === self.top) { - scrollIntervalId = setInterval(function () { - try { - //From this ticket: - //http://bugs.dojotoolkit.org/ticket/11106, - //In IE HTML Application (HTA), such as in a selenium test, - //javascript in the iframe can't see anything outside - //of it, so self===self.top is true, but the iframe is - //not the top window and doScroll will be available - //before document.body is set. Test document.body - //before trying the doScroll trick. - if (document.body) { - document.documentElement.doScroll("left"); - req.pageLoaded(); - } - } catch (e) {} - }, 30); - } - } - //Check if document already complete, and if so, just trigger page load - //listeners. NOTE: does not work with Firefox before 3.6. To support - //those browsers, manually call require.pageLoaded(). - if (document.readyState === "complete") { - req.pageLoaded(); - } - } - //****** END page load functionality **************** - //>>excludeEnd("requireExcludePageLoad"); + /** + * 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) { + /*jslint evil: true */ + return eval(text); + }; - //Set up default context. If require was a configuration object, use that as base config. + //Set up with config info. req(cfg); - - //If modules are built into require.js, then need to make sure dependencies are - //traced. Use a setTimeout in the browser world, to allow all the modules to register - //themselves. In a non-browser env, assume that modules are not built into require.js, - //which seems odd to do on the server. - if (typeof setTimeout !== "undefined") { - setTimeout(function () { - var ctx = s.contexts[(cfg.context || defContextName)]; - //Allow for jQuery to be loaded/already in the page, and if jQuery 1.4.3, - //make sure to hold onto it for readyWait triggering. - jQueryCheck(ctx); - resume(ctx); - }, 0); - } -}()); +}(this)); \ No newline at end of file diff --git a/tests/runTests.html b/tests/runTests.html index d00e7fb..c9a461a 100644 --- a/tests/runTests.html +++ b/tests/runTests.html @@ -32,8 +32,6 @@ - - @@ -51,6 +49,7 @@ + @@ -61,125 +60,129 @@

has.js