From 46821604fb06ebb13fd23c90d1c13d185dfee378 Mon Sep 17 00:00:00 2001 From: Alan Kligman Date: Sun, 7 Oct 2012 01:42:58 -0400 Subject: [PATCH] Initial commit. --- .gitignore | 1 + examples/test.html | 23 + lib/debug.js | 273 ++++++ lib/require.js | 2041 ++++++++++++++++++++++++++++++++++++++++++++ lib/when.js | 738 ++++++++++++++++ src/filesystem.js | 194 +++++ 6 files changed, 3270 insertions(+) create mode 100644 .gitignore create mode 100644 examples/test.html create mode 100644 lib/debug.js create mode 100644 lib/require.js create mode 100644 lib/when.js create mode 100644 src/filesystem.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a392472 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +filesystemapi.js diff --git a/examples/test.html b/examples/test.html new file mode 100644 index 0000000..5c70caf --- /dev/null +++ b/examples/test.html @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file diff --git a/lib/debug.js b/lib/debug.js new file mode 100644 index 0000000..000ccd5 --- /dev/null +++ b/lib/debug.js @@ -0,0 +1,273 @@ +/*! + * JavaScript Debug - v0.4 - 6/22/2010 + * http://benalman.com/projects/javascript-debug-console-log/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + * + * With lots of help from Paul Irish! + * http://paulirish.com/ + */ + +// Script: JavaScript Debug: A simple wrapper for console.log +// +// *Version: 0.4, Last Updated: 6/22/2010* +// +// Tested with Internet Explorer 6-8, Firefox 3-3.6, Safari 3-4, Chrome 3-5, Opera 9.6-10.5 +// +// Home - http://benalman.com/projects/javascript-debug-console-log/ +// GitHub - http://github.com/cowboy/javascript-debug/ +// Source - http://github.com/cowboy/javascript-debug/raw/master/ba-debug.js +// (Minified) - http://github.com/cowboy/javascript-debug/raw/master/ba-debug.min.js (1.1kb) +// +// About: License +// +// Copyright (c) 2010 "Cowboy" Ben Alman, +// Dual licensed under the MIT and GPL licenses. +// http://benalman.com/about/license/ +// +// About: Support and Testing +// +// Information about what browsers this code has been tested in. +// +// Browsers Tested - Internet Explorer 6-8, Firefox 3-3.6, Safari 3-4, Chrome +// 3-5, Opera 9.6-10.5 +// +// About: Examples +// +// These working examples, complete with fully commented code, illustrate a few +// ways in which this plugin can be used. +// +// Examples - http://benalman.com/code/projects/javascript-debug/examples/debug/ +// +// About: Revision History +// +// 0.4 - (6/22/2010) Added missing passthrough methods: exception, +// groupCollapsed, table +// 0.3 - (6/8/2009) Initial release +// +// Topic: Pass-through console methods +// +// assert, clear, count, dir, dirxml, exception, group, groupCollapsed, +// groupEnd, profile, profileEnd, table, time, timeEnd, trace +// +// These console methods are passed through (but only if both the console and +// the method exists), so use them without fear of reprisal. Note that these +// methods will not be passed through if the logging level is set to 0 via +// . +(function(define, console) { +define(function() { "use strict"; + // Some convenient shortcuts. + var aps = Array.prototype.slice, + con = console, + + // Public object to be returned. + that = {}, + + callback_func, + callback_force, + + // Default logging level, show everything. + log_level = 9, + + // Logging methods, in "priority order". Not all console implementations + // will utilize these, but they will be used in the callback passed to + // setCallback. + log_methods = [ 'error', 'warn', 'info', 'debug', 'log' ], + + // Pass these methods through to the console if they exist, otherwise just + // fail gracefully. These methods are provided for convenience. + pass_methods = 'assert clear count dir dirxml exception group groupCollapsed groupEnd profile profileEnd table time timeEnd trace'.split(' '), + idx = pass_methods.length, + + // Logs are stored here so that they can be recalled as necessary. + logs = []; + + while ( --idx >= 0 ) { + (function( method ){ + + // Generate pass-through methods. These methods will be called, if they + // exist, as long as the logging level is non-zero. + that[ method ] = function() { + log_level !== 0 && con && con[ method ] + && con[ method ].apply( con, arguments ); + } + + })( pass_methods[idx] ); + } + + idx = log_methods.length; + while ( --idx >= 0 ) { + (function( idx, level ){ + + // Method: debug.log + // + // Call the console.log method if available. Adds an entry into the logs + // array for a callback specified via . + // + // Usage: + // + // debug.log( object [, object, ...] ); - - + // + // Arguments: + // + // object - (Object) Any valid JavaScript object. + + // Method: debug.debug + // + // Call the console.debug method if available, otherwise call console.log. + // Adds an entry into the logs array for a callback specified via + // . + // + // Usage: + // + // debug.debug( object [, object, ...] ); - - + // + // Arguments: + // + // object - (Object) Any valid JavaScript object. + + // Method: debug.info + // + // Call the console.info method if available, otherwise call console.log. + // Adds an entry into the logs array for a callback specified via + // . + // + // Usage: + // + // debug.info( object [, object, ...] ); - - + // + // Arguments: + // + // object - (Object) Any valid JavaScript object. + + // Method: debug.warn + // + // Call the console.warn method if available, otherwise call console.log. + // Adds an entry into the logs array for a callback specified via + // . + // + // Usage: + // + // debug.warn( object [, object, ...] ); - - + // + // Arguments: + // + // object - (Object) Any valid JavaScript object. + + // Method: debug.error + // + // Call the console.error method if available, otherwise call console.log. + // Adds an entry into the logs array for a callback specified via + // . + // + // Usage: + // + // debug.error( object [, object, ...] ); - - + // + // Arguments: + // + // object - (Object) Any valid JavaScript object. + + that[ level ] = function() { + var args = aps.call( arguments ), + log_arr = [ level ].concat( args ); + + logs.push( log_arr ); + exec_callback( log_arr ); + + if ( !con || !is_level( idx ) ) { return; } + + con.firebug ? con[ level ].apply( window, args ) + : con[ level ] ? con[ level ].apply( window, args ) + : con.log.apply( window, args ); + }; + + })( idx, log_methods[idx] ); + } + + // Execute the callback function if set. + function exec_callback( args ) { + if ( callback_func && (callback_force || !con || !con.log) ) { + callback_func.apply( window, args ); + } + }; + + // Method: debug.setLevel + // + // Set a minimum or maximum logging level for the console. Doesn't affect + // the callback function, but if set to 0 to disable + // logging, will be disabled as well. + // + // Usage: + // + // debug.setLevel( [ level ] ) - - + // + // Arguments: + // + // level - (Number) If 0, disables logging. If negative, shows N lowest + // priority levels of log messages. If positive, shows N highest priority + // levels of log messages. + // + // Priority levels: + // + // log (1) < debug (2) < info (3) < warn (4) < error (5) + + that.setLevel = function( level ) { + log_level = typeof level === 'number' ? level : 9; + }; + + // Determine if the level is visible given the current log_level. + function is_level( level ) { + return log_level > 0 + ? log_level > level + : log_methods.length + log_level <= level; + }; + + // Method: debug.setCallback + // + // Set a callback to be used if logging isn't possible due to console.log + // not existing. If unlogged logs exist when callback is set, they will all + // be logged immediately unless a limit is specified. + // + // Usage: + // + // debug.setCallback( callback [, force ] [, limit ] ) + // + // Arguments: + // + // callback - (Function) The aforementioned callback function. The first + // argument is the logging level, and all subsequent arguments are those + // passed to the initial debug logging method. + // force - (Boolean) If false, log to console.log if available, otherwise + // callback. If true, log to both console.log and callback. + // limit - (Number) If specified, number of lines to limit initial scrollback + // to. + + that.setCallback = function() { + var args = aps.call( arguments ), + max = logs.length, + i = max; + + callback_func = args.shift() || null; + callback_force = typeof args[0] === 'boolean' ? args.shift() : false; + + i -= typeof args[0] === 'number' ? args.shift() : max; + + while ( i < max ) { + exec_callback( logs[i++] ); + } + }; + + return that; +}); +})(typeof define == 'function' + ? define + : function (factory) { typeof exports != 'undefined' + ? (module.exports = factory()) + : (this.when = factory()); + }, + window.console + // Boilerplate for AMD, Node, and browser global +); \ No newline at end of file diff --git a/lib/require.js b/lib/require.js new file mode 100644 index 0000000..b592d5f --- /dev/null +++ b/lib/require.js @@ -0,0 +1,2041 @@ +/** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/jrburke/requirejs for details + */ +//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, jQuery, setTimeout, opera */ + +var requirejs, require, define; +(function (global) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.0.6', + 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, + aps = ap.slice, + apsp = ap.splice, + isBrowser = !!(typeof window !== 'undefined' && navigator && 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]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + 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; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + 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; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + /** + * 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 eachProp(obj, func) { + var prop; + for (prop in obj) { + if (obj.hasOwnProperty(prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + * This is not robust in IE for transferring methods that match + * Object.prototype names, but the uses of mixin here seem unlikely to + * trigger a problem related to that. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value !== 'string') { + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //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); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + //Allow getting a global that 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; + } + + function makeContextModuleFunc(func, relMap, enableBuildCallback) { + return function () { + //A version of a require function that passes a moduleName + //value for items that may need to + //look up paths relative to the moduleName + var args = aps.call(arguments, 0), lastArg; + if (enableBuildCallback && + isFunction((lastArg = args[args.length - 1]))) { + lastArg.__requireJsBuild = true; + } + args.push(relMap); + return func.apply(null, args); + }; + } + + function addRequireMethods(req, context, relMap) { + each([ + ['toUrl'], + ['undef'], + ['defined', 'requireDefined'], + ['specified', 'requireSpecified'] + ], function (item) { + var prop = item[1] || item[0]; + req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) : + //If no context, then use default context. 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. + function () { + var ctx = contexts[defContextName]; + return ctx[prop].apply(ctx, arguments); + }; + }); + } + + /** + * 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. + * + * @returns {Error} + */ + 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; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite and existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + waitSeconds: 7, + baseUrl: './', + paths: {}, + pkgs: {}, + shim: {} + }, + registry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + requireCounter = 1, + unnormalizedCounter = 1, + //Used to track the order in which modules + //should be executed, by the order they + //load. Important for consistent cycle resolution + //behavior. + waitAry = []; + + /** + * 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; ary[i]; i += 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * 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 pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment, + foundMap, foundI, foundStarMap, starI, + baseParts = baseName && baseName.split('/'), + normalizedBaseParts = baseParts, + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name && name.charAt(0) === '.') { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if (baseName) { + if (config.pkgs[baseName]) { + //If the baseName is a package name, then just treat it as one + //name to concat the name with. + normalizedBaseParts = baseParts = [baseName]; + } else { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + } + + name = normalizedBaseParts.concat(name.split('/')); + trimDots(name); + + //Some use of packages may use a . path to reference the + //'main' module name, so normalize for that. + pkgConfig = config.pkgs[(pkgName = name[0])]; + name = name.join('/'); + if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { + name = pkgName; + } + } else if (name.indexOf('./') === 0) { + // No baseName, so this is ID is resolved relative + // to baseUrl, pull off the leading dot. + name = name.substring(2); + } + } + + //Apply map config if available. + if (applyMap && (baseParts || starMap) && map) { + nameParts = name.split('/'); + + 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 = map[baseParts.slice(0, j).join('/')]; + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = mapValue[nameSegment]; + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break; + } + } + } + } + + if (foundMap) { + break; + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && starMap[nameSegment]) { + foundStarMap = starMap[nameSegment]; + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + return name; + } + + 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; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = config.paths[id]; + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + removeScript(id); + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.undef(id); + context.require([id]); + return true; + } + } + + /** + * 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, + index = name ? name.indexOf('!') : -1, + 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); + } + + if (index !== -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = defined[prefix]; + } + + //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 { + normalizedName = normalize(name, parentName, applyMap); + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + url = context.nameToUrl(normalizedName); + } + } + + //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 + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = registry[id]; + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = registry[id]; + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + getModule(depMap).on(name, fn); + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = 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); + } + } + } + + /** + * 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 - 1, 0].concat(globalDefQueue)); + globalDefQueue = []; + } + } + + /** + * 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(mod, enableBuildCallback, altRequire) { + var relMap = mod && mod.map, + modRequire = makeContextModuleFunc(altRequire || context.require, + relMap, + enableBuildCallback); + + addRequireMethods(modRequire, context, relMap); + modRequire.isBrowser = isBrowser; + + return modRequire; + } + + handlers = { + 'require': function (mod) { + return makeRequire(mod); + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + return (mod.exports = defined[mod.map.id] = {}); + } + }, + 'module': function (mod) { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return (config.config && config.config[mod.map.id]) || {}; + }, + exports: defined[mod.map.id] + }); + } + }; + + function removeWaiting(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + + each(waitAry, function (mod, i) { + if (mod.map.id === id) { + waitAry.splice(i, 1); + if (!mod.defined) { + context.waitCount -= 1; + } + return true; + } + }); + } + + function findCycle(mod, traced, processed) { + var id = mod.map.id, + depArray = mod.depMaps, + foundModule; + + //Do not bother with unitialized modules or not yet enabled + //modules. + if (!mod.inited) { + return; + } + + //Found the cycle. + if (traced[id]) { + return mod; + } + + traced[id] = true; + + //Trace through the dependencies. + each(depArray, function (depMap) { + var depId = depMap.id, + depMod = registry[depId]; + + if (!depMod || processed[depId] || + !depMod.inited || !depMod.enabled) { + return; + } + + return (foundModule = findCycle(depMod, traced, processed)); + }); + + processed[id] = true; + + return foundModule; + } + + function forceExec(mod, traced, uninited) { + var id = mod.map.id, + depArray = mod.depMaps; + + if (!mod.inited || !mod.map.isDefine) { + return; + } + + if (traced[id]) { + return defined[id]; + } + + traced[id] = mod; + + each(depArray, function (depMap) { + var depId = depMap.id, + depMod = registry[depId], + value; + + if (handlers[depId]) { + return; + } + + if (depMod) { + if (!depMod.inited || !depMod.enabled) { + //Dependency is not inited, + //so this module cannot be + //given a forced value yet. + uninited[id] = true; + return; + } + + //Get the value for the current dependency + value = forceExec(depMod, traced, uninited); + + //Even with forcing it may not be done, + //in particular if the module is waiting + //on a plugin resource. + if (!uninited[depId]) { + mod.defineDepById(depId, value); + } + } + }); + + mod.check(true); + + return defined[id]; + } + + function modCheck(mod) { + mod.check(); + } + + function checkLoaded() { + var map, modId, 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 = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(registry, function (mod) { + map = mod.map; + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + 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); + } + } + } + }); + + 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); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + + each(waitAry, function (mod) { + if (mod.defined) { + return; + } + + var cycleMod = findCycle(mod, {}, {}), + traced = {}; + + if (cycleMod) { + forceExec(cycleMod, traced, {}); + + //traced modules may have been + //removed from the registry, but + //their listeners still need to + //be called. + eachProp(traced, modCheck); + } + }); + + //Now that dependencies have + //been satisfied, trigger the + //completion check that then + //notifies listeners. + eachProp(registry, modCheck); + } + + //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; + } + + Module = function (map) { + this.events = undefEvents[map.id] || {}; + this.map = map; + this.shim = config.shim[map.id]; + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //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; + } + + 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); + }); + } + + //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); + this.depMaps.rjsSkipMap = depMaps.rjsSkipMap; + + this.errback = errback; + + //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(); + } + }, + + defineDepById: function (id, depExports) { + var i; + + //Find the index for this dependency. + each(this.depMaps, function (map, index) { + if (map.id === id) { + i = index; + return true; + } + }); + + return this.defineDep(i, depExports); + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + makeRequire(this, true)(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks is the module is ready to define itself, and if so, + * define it. If the silent argument is true, then it will just + * define, but not notify listeners, and not ask for a context-wide + * check of all loaded modules. That is useful for cycle breaking. + */ + check: function (silent) { + if (!this.enabled || this.enabling) { + return; + } + + 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. + if (this.events.error) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + if (this.map.isDefine) { + //If setting exports via 'module' is in play, + //favor that over return value and exports. After that, + //favor a non-undefined return value over exports use. + cjsModule = this.module; + if (cjsModule && + cjsModule.exports !== undefined && + //Make sure it is not already the exports value + cjsModule.exports !== this.exports) { + exports = cjsModule.exports; + } else if (exports === undefined && this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = [this.map.id]; + err.requireType = 'define'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + req.onResourceLoad(context, this.map, this.depMaps); + } + } + + //Clean up + delete registry[id]; + + this.defined = true; + context.waitCount -= 1; + if (context.waitCount === 0) { + //Clear the wait array used for cycles. + waitAry = []; + } + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (!silent) { + 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, + pluginMap = makeModuleMap(map.prefix, null, false, true); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null; + + //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); + }) || ''; + } + + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap, + false, + true); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + normalizedMod = registry[normalizedMap.id]; + if (normalizedMod) { + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + 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) { + removeWaiting(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 = function (moduleName, text) { + /*jslint evil: true */ + var hasInteractive = useInteractive; + + //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(makeModuleMap(moduleName)); + + req.exec(text); + + if (hasInteractive) { + useInteractive = true; + } + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + + //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, makeRequire(map.parentMap, true, function (deps, cb, er) { + deps.rjsSkipMap = true; + return context.require(deps, cb, er); + }), load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + this.enabled = true; + + if (!this.waitPushed) { + waitAry.push(this); + context.waitCount += 1; + this.waitPushed = 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.depMaps.rjsSkipMap); + this.depMaps[i] = depMap; + + handler = 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', 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 (!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 = 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/waitAry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + + 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 { + node.removeEventListener(name, func, false); + } + } + + /** + * 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') + }; + } + + return (context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + waitCount: 0, + defQueue: defQueue, + Module: Module, + makeModuleMap: makeModuleMap, + + /** + * 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 += '/'; + } + } + + //Save off the paths and packages since they require special processing, + //they are additive. + var pkgs = config.pkgs, + shim = config.shim, + paths = config.paths, + map = config.map; + + //Mix in the config values, favoring the new values over + //existing ones in context.config. + mixin(config, cfg, true); + + //Merge paths. + config.paths = mixin(paths, cfg.paths, true); + + //Merge map + if (cfg.map) { + config.map = mixin(map || {}, cfg.map, true, true); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if (value.exports && !value.exports.__buildReady) { + value.exports = context.makeShimExports(value.exports); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location; + + pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; + location = pkgObj.location; + + //Create a brand new object on pkgs, since currentPackages can + //be passed in again, and config.pkgs is the internal transformed + //state for all package configs. + pkgs[pkgObj.name] = { + name: pkgObj.name, + location: location || pkgObj.name, + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + main: (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, '') + }; + }); + + //Done with modifications, assing packages back to context config + config.pkgs = pkgs; + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //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); + } + }); + + //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); + } + }, + + makeShimExports: function (exports) { + var func; + if (typeof exports === 'string') { + func = function () { + return getGlobal(exports); + }; + //Save the exports for use in nodefine checking. + func.exports = exports; + return func; + } else { + return function () { + return exports.apply(global, arguments); + }; + } + }, + + requireDefined: function (id, relMap) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + requireSpecified: function (id, relMap) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + }, + + require: function (deps, callback, errback, relMap) { + var moduleName, id, map, requireMod, args; + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + //In this case deps is the moduleName and callback is + //the relMap + if (req.get) { + return req.get(context, deps, callback); + } + + //Just return the module wanted. In this scenario, the + //second arg (if passed) is just the relMap. + moduleName = deps; + relMap = callback; + + //Normalize module name, if it contains . or .. + map = makeModuleMap(moduleName, 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)); + } + return defined[id]; + } + + //Callback require. Normalize args. if callback or errback is + //not a function, it means it is a relMap. Test errback first. + if (errback && !isFunction(errback)) { + relMap = errback; + errback = undefined; + } + if (callback && !isFunction(callback)) { + relMap = callback; + callback = undefined; + } + + //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); + } + } + + //Mark all the dependencies as needing to be loaded. + requireMod = getModule(makeModuleMap(null, relMap)); + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + + return context.require; + }, + + undef: function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, null, true), + mod = registry[id]; + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + 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; + } + + removeWaiting(id); + } + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. parent module is passed in for context, + * used by the optimizer. + */ + enable: function (depMap, parent) { + var mod = 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 = config.shim[moduleName] || {}, + shExports = shim.exports && shim.exports.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); + } + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = registry[moduleName]; + + if (!found && !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.exports]); + } + } + + checkLoaded(); + }, + + /** + * 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, relModuleMap) { + var index = moduleNamePlusExt.lastIndexOf('.'), + ext = null; + + if (index !== -1) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true), + ext); + }, + + /** + * 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) { + var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, + parentPath; + + //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; + pkgs = config.pkgs; + + 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('/'); + pkg = pkgs[parentModule]; + parentPath = 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; + } else if (pkg) { + //If module name is just the package name, then looking + //for the main module. + if (moduleName === pkg.name) { + pkgPath = pkg.location + '/' + pkg.main; + } else { + pkgPath = pkg.location; + } + syms.splice(0, i, pkgPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/\?/.test(url) ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs ? url + + ((url.indexOf('?') === -1 ? '?' : '&') + + config.urlArgs) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * 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. + * + * @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', evt, [data.id])); + } + } + }); + } + + /** + * 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. + * + * 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 = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // 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 = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = contexts[contextName]; + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Export require as a global, but only if it does not already exist. + */ + 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, using + //default context if no context specified. + addRequireMethods(req); + + 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 = function (err) { + throw err; + }; + + /** + * 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.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + 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; + + 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 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', 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 addEvenListener + //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 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) { + head.insertBefore(node, baseElement); + } else { + 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. + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + 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) { + //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 (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //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) { + //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 = dataMain.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + dataMain = mainScript; + } + + //Strip off any trailing .js since dataMain is now + //like a module name. + dataMain = dataMain.replace(jsSuffixRegExp, ''); + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; + + return true; + } + }); + } + + /** + * 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 = function (name, deps, callback) { + var node, context; + + //Allow for anonymous functions + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = []; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps.length && isFunction(callback)) { + //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 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]); + }; + + define.amd = { + jQuery: true + }; + + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this)); diff --git a/lib/when.js b/lib/when.js new file mode 100644 index 0000000..726d38e --- /dev/null +++ b/lib/when.js @@ -0,0 +1,738 @@ +/** @license MIT License (c) copyright B Cavalier & J Hann */ + +/** + * when + * A lightweight CommonJS Promises/A and when() implementation + * + * when is part of the cujo.js family of libraries (http://cujojs.com/) + * + * Licensed under the MIT License at: + * http://www.opensource.org/licenses/mit-license.php + * + * @version 1.0.4 + */ + +(function(define) { +define(function() { + var freeze, reduceArray, undef; + + /** + * No-Op function used in method replacement + * @private + */ + function noop() {} + + /** + * Allocate a new Array of size n + * @private + * @param n {number} size of new Array + * @returns {Array} + */ + function allocateArray(n) { + return new Array(n); + } + + /** + * Use freeze if it exists + * @function + * @private + */ + freeze = Object.freeze || function(o) { return o; }; + + // ES5 reduce implementation if native not available + // See: http://es5.github.com/#x15.4.4.21 as there are many + // specifics and edge cases. + reduceArray = [].reduce || + function(reduceFunc /*, initialValue */) { + // ES5 dictates that reduce.length === 1 + + // This implementation deviates from ES5 spec in the following ways: + // 1. It does not check if reduceFunc is a Callable + + var arr, args, reduced, len, i; + + i = 0; + arr = Object(this); + len = arr.length >>> 0; + args = arguments; + + // If no initialValue, use first item of array (we know length !== 0 here) + // and adjust i to start at second item + if(args.length <= 1) { + // Skip to the first real element in the array + for(;;) { + if(i in arr) { + reduced = arr[i++]; + break; + } + + // If we reached the end of the array without finding any real + // elements, it's a TypeError + if(++i >= len) { + throw new TypeError(); + } + } + } else { + // If initialValue provided, use it + reduced = args[1]; + } + + // Do the actual reduce + for(;i < len; ++i) { + // Skip holes + if(i in arr) + reduced = reduceFunc(reduced, arr[i], i, arr); + } + + return reduced; + }; + + /** + * Trusted Promise constructor. A Promise created from this constructor is + * a trusted when.js promise. Any other duck-typed promise is considered + * untrusted. + */ + function Promise() {} + + /** + * Create an already-resolved promise for the supplied value + * @private + * + * @param value anything + * @return {Promise} + */ + function resolved(value) { + + var p = new Promise(); + + p.then = function(callback) { + checkCallbacks(arguments); + + var nextValue; + try { + if(callback) nextValue = callback(value); + return promise(nextValue === undef ? value : nextValue); + } catch(e) { + return rejected(e); + } + }; + + return freeze(p); + } + + /** + * Create an already-rejected {@link Promise} with the supplied + * rejection reason. + * @private + * + * @param reason rejection reason + * @return {Promise} + */ + function rejected(reason) { + + var p = new Promise(); + + p.then = function(callback, errback) { + checkCallbacks(arguments); + + var nextValue; + try { + if(errback) { + nextValue = errback(reason); + return promise(nextValue === undef ? reason : nextValue) + } + + return rejected(reason); + + } catch(e) { + return rejected(e); + } + }; + + return freeze(p); + } + + /** + * Helper that checks arrayOfCallbacks to ensure that each element is either + * a function, or null or undefined. + * + * @param arrayOfCallbacks {Array} array to check + * @throws {Error} if any element of arrayOfCallbacks is something other than + * a Functions, null, or undefined. + */ + function checkCallbacks(arrayOfCallbacks) { + var arg, i = arrayOfCallbacks.length; + while(i) { + arg = arrayOfCallbacks[--i]; + if (arg != null && typeof arg != 'function') throw new Error('callback is not a function'); + } + } + + /** + * Creates a new, CommonJS compliant, Deferred with fully isolated + * resolver and promise parts, either or both of which may be given out + * safely to consumers. + * The Deferred itself has the full API: resolve, reject, progress, and + * then. The resolver has resolve, reject, and progress. The promise + * only has then. + * + * @memberOf when + * @function + * + * @returns {Deferred} + */ + function defer() { + var deferred, promise, listeners, progressHandlers, _then, _progress, complete; + + listeners = []; + progressHandlers = []; + + /** + * Pre-resolution then() that adds the supplied callback, errback, and progback + * functions to the registered listeners + * + * @private + * + * @param [callback] {Function} resolution handler + * @param [errback] {Function} rejection handler + * @param [progback] {Function} progress handler + * + * @throws {Error} if any argument is not null, undefined, or a Function + */ + _then = function unresolvedThen(callback, errback, progback) { + // Check parameters and fail immediately if any supplied parameter + // is not null/undefined and is also not a function. + // That is, any non-null/undefined parameter must be a function. + checkCallbacks(arguments); + + var deferred = defer(); + + listeners.push(function(promise) { + promise.then(callback, errback) + .then(deferred.resolve, deferred.reject, deferred.progress); + }); + + progback && progressHandlers.push(progback); + + return deferred.promise; + }; + + /** + * Registers a handler for this {@link Deferred}'s {@link Promise}. Even though all arguments + * are optional, each argument that *is* supplied must be null, undefined, or a Function. + * Any other value will cause an Error to be thrown. + * + * @memberOf Promise + * + * @param [callback] {Function} resolution handler + * @param [errback] {Function} rejection handler + * @param [progback] {Function} progress handler + * + * @throws {Error} if any argument is not null, undefined, or a Function + */ + function then(callback, errback, progback) { + return _then(callback, errback, progback); + } + + /** + * Resolves this {@link Deferred}'s {@link Promise} with val as the + * resolution value. + * + * @memberOf Resolver + * + * @param val anything + */ + function resolve(val) { + complete(resolved(val)); + } + + /** + * Rejects this {@link Deferred}'s {@link Promise} with err as the + * reason. + * + * @memberOf Resolver + * + * @param err anything + */ + function reject(err) { + complete(rejected(err)); + } + + /** + * @private + * @param update + */ + _progress = function(update) { + var progress, i = 0; + while (progress = progressHandlers[i++]) progress(update); + }; + + /** + * Emits a progress update to all progress observers registered with + * this {@link Deferred}'s {@link Promise} + * + * @memberOf Resolver + * + * @param update anything + */ + function progress(update) { + _progress(update); + } + + /** + * Transition from pre-resolution state to post-resolution state, notifying + * all listeners of the resolution or rejection + * + * @private + * + * @param completed {Promise} the completed value of this deferred + */ + complete = function(completed) { + var listener, i = 0; + + // Replace _then with one that directly notifies with the result. + _then = completed.then; + + // Replace complete so that this Deferred can only be completed + // once. Also Replace _progress, so that subsequent attempts to issue + // progress throw. + complete = _progress = function alreadyCompleted() { + // TODO: Consider silently returning here so that parties who + // have a reference to the resolver cannot tell that the promise + // has been resolved using try/catch + throw new Error("already completed"); + }; + + // Free progressHandlers array since we'll never issue progress events + // for this promise again now that it's completed + progressHandlers = undef; + + // Notify listeners + // Traverse all listeners registered directly with this Deferred + + while (listener = listeners[i++]) { + listener(completed); + } + + listeners = []; + }; + + /** + * The full Deferred object, with both {@link Promise} and {@link Resolver} + * parts + * @class Deferred + * @name Deferred + * @augments Resolver + * @augments Promise + */ + deferred = {}; + + // Promise and Resolver parts + // Freeze Promise and Resolver APIs + + /** + * The Promise API + * @namespace Promise + * @name Promise + */ + promise = new Promise(); + promise.then = deferred.then = then; + + /** + * The {@link Promise} for this {@link Deferred} + * @memberOf Deferred + * @name promise + * @type {Promise} + */ + deferred.promise = freeze(promise); + + /** + * The {@link Resolver} for this {@link Deferred} + * @namespace Resolver + * @name Resolver + * @memberOf Deferred + * @name resolver + * @type {Resolver} + */ + deferred.resolver = freeze({ + resolve: (deferred.resolve = resolve), + reject: (deferred.reject = reject), + progress: (deferred.progress = progress) + }); + + return deferred; + } + + /** + * Determines if promiseOrValue is a promise or not. Uses the feature + * test from http://wiki.commonjs.org/wiki/Promises/A to determine if + * promiseOrValue is a promise. + * + * @param promiseOrValue anything + * + * @returns {Boolean} true if promiseOrValue is a {@link Promise} + */ + function isPromise(promiseOrValue) { + return promiseOrValue && typeof promiseOrValue.then === 'function'; + } + + /** + * Register an observer for a promise or immediate value. + * + * @function + * @name when + * @namespace + * + * @param promiseOrValue anything + * @param {Function} [callback] callback to be called when promiseOrValue is + * successfully resolved. If promiseOrValue is an immediate value, callback + * will be invoked immediately. + * @param {Function} [errback] callback to be called when promiseOrValue is + * rejected. + * @param {Function} [progressHandler] callback to be called when progress updates + * are issued for promiseOrValue. + * + * @returns {Promise} a new {@link Promise} that will complete with the return + * value of callback or errback or the completion value of promiseOrValue if + * callback and/or errback is not supplied. + */ + function when(promiseOrValue, callback, errback, progressHandler) { + // Get a promise for the input promiseOrValue + // See promise() + var trustedPromise = promise(promiseOrValue); + + // Register promise handlers + return trustedPromise.then(callback, errback, progressHandler); + } + + /** + * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if + * promiseOrValue is a foreign promise, or a new, already-resolved {@link Promise} + * whose resolution value is promiseOrValue if promiseOrValue is an immediate value. + * + * Note that this function is not safe to export since it will return its + * input when promiseOrValue is a {@link Promise} + * + * @private + * + * @param promiseOrValue anything + * + * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise} + * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise} + * whose resolution value is: + * * the resolution value of promiseOrValue if it's a foreign promise, or + * * promiseOrValue if it's a value + */ + function promise(promiseOrValue) { + var promise, deferred; + + if(promiseOrValue instanceof Promise) { + // It's a when.js promise, so we trust it + promise = promiseOrValue; + + } else { + // It's not a when.js promise. Check to see if it's a foreign promise + // or a value. + + deferred = defer(); + if(isPromise(promiseOrValue)) { + // It's a compliant promise, but we don't know where it came from, + // so we don't trust its implementation entirely. Introduce a trusted + // middleman when.js promise + + // IMPORTANT: This is the only place when.js should ever call .then() on + // an untrusted promise. + promiseOrValue.then(deferred.resolve, deferred.reject, deferred.progress); + promise = deferred.promise; + + } else { + // It's a value, not a promise. Create an already-resolved promise + // for it. + deferred.resolve(promiseOrValue); + promise = deferred.promise; + } + } + + return promise; + } + + /** + * Return a promise that will resolve when howMany of the supplied promisesOrValues + * have resolved. The resolution value of the returned promise will be an array of + * length howMany containing the resolutions values of the triggering promisesOrValues. + * + * @memberOf when + * + * @param promisesOrValues {Array} array of anything, may contain a mix + * of {@link Promise}s and values + * @param howMany + * @param [callback] + * @param [errback] + * @param [progressHandler] + * + * @returns {Promise} + */ + function some(promisesOrValues, howMany, callback, errback, progressHandler) { + var toResolve, results, ret, deferred, resolver, rejecter, handleProgress, len, i; + + len = promisesOrValues.length >>> 0; + + toResolve = Math.max(0, Math.min(howMany, len)); + results = []; + deferred = defer(); + ret = when(deferred, callback, errback, progressHandler); + + // Wrapper so that resolver can be replaced + function resolve(val) { + resolver(val); + } + + // Wrapper so that rejecter can be replaced + function reject(err) { + rejecter(err); + } + + // Wrapper so that progress can be replaced + function progress(update) { + handleProgress(update); + } + + function complete() { + resolver = rejecter = handleProgress = noop; + } + + // No items in the input, resolve immediately + if (!toResolve) { + deferred.resolve(results); + + } else { + // Resolver for promises. Captures the value and resolves + // the returned promise when toResolve reaches zero. + // Overwrites resolver var with a noop once promise has + // be resolved to cover case where n < promises.length + resolver = function(val) { + // This orders the values based on promise resolution order + // Another strategy would be to use the original position of + // the corresponding promise. + results.push(val); + + if (!--toResolve) { + complete(); + deferred.resolve(results); + } + }; + + // Rejecter for promises. Rejects returned promise + // immediately, and overwrites rejecter var with a noop + // once promise to cover case where n < promises.length. + // TODO: Consider rejecting only when N (or promises.length - N?) + // promises have been rejected instead of only one? + rejecter = function(err) { + complete(); + deferred.reject(err); + }; + + handleProgress = deferred.progress; + + // TODO: Replace while with forEach + for(i = 0; i < len; ++i) { + if(i in promisesOrValues) { + when(promisesOrValues[i], resolve, reject, progress); + } + } + } + + return ret; + } + + /** + * Return a promise that will resolve only once all the supplied promisesOrValues + * have resolved. The resolution value of the returned promise will be an array + * containing the resolution values of each of the promisesOrValues. + * + * @memberOf when + * + * @param promisesOrValues {Array} array of anything, may contain a mix + * of {@link Promise}s and values + * @param [callback] {Function} + * @param [errback] {Function} + * @param [progressHandler] {Function} + * + * @returns {Promise} + */ + function all(promisesOrValues, callback, errback, progressHandler) { + var results, promise; + + results = allocateArray(promisesOrValues.length); + promise = reduce(promisesOrValues, reduceIntoArray, results); + + return when(promise, callback, errback, progressHandler); + } + + function reduceIntoArray(current, val, i) { + current[i] = val; + return current; + } + + /** + * Return a promise that will resolve when any one of the supplied promisesOrValues + * has resolved. The resolution value of the returned promise will be the resolution + * value of the triggering promiseOrValue. + * + * @memberOf when + * + * @param promisesOrValues {Array} array of anything, may contain a mix + * of {@link Promise}s and values + * @param [callback] {Function} + * @param [errback] {Function} + * @param [progressHandler] {Function} + * + * @returns {Promise} + */ + function any(promisesOrValues, callback, errback, progressHandler) { + + function unwrapSingleResult(val) { + return callback(val[0]); + } + + return some(promisesOrValues, 1, unwrapSingleResult, errback, progressHandler); + } + + /** + * Traditional map function, similar to `Array.prototype.map()`, but allows + * input to contain {@link Promise}s and/or values, and mapFunc may return + * either a value or a {@link Promise} + * + * @memberOf when + * + * @param promisesOrValues {Array} array of anything, may contain a mix + * of {@link Promise}s and values + * @param mapFunc {Function} mapping function mapFunc(value) which may return + * either a {@link Promise} or value + * + * @returns {Promise} a {@link Promise} that will resolve to an array containing + * the mapped output values. + */ + function map(promisesOrValues, mapFunc) { + + var results, i; + + // Since we know the resulting length, we can preallocate the results + // array to avoid array expansions. + i = promisesOrValues.length; + results = allocateArray(i); + + // Since mapFunc may be async, get all invocations of it into flight + // asap, and then use reduce() to collect all the results + for(;i >= 0; --i) { + if(i in promisesOrValues) + results[i] = when(promisesOrValues[i], mapFunc); + } + + // Could use all() here, but that would result in another array + // being allocated, i.e. map() would end up allocating 2 arrays + // of size len instead of just 1. Since all() uses reduce() + // anyway, avoid the additional allocation by calling reduce + // directly. + return reduce(results, reduceIntoArray, results); + } + + /** + * Traditional reduce function, similar to `Array.prototype.reduce()`, but + * input may contain {@link Promise}s and/or values, but reduceFunc + * may return either a value or a {@link Promise}, *and* initialValue may + * be a {@link Promise} for the starting value. + * + * @memberOf when + * + * @param promisesOrValues {Array} array of anything, may contain a mix + * of {@link Promise}s and values + * @param reduceFunc {Function} reduce function reduce(currentValue, nextValue, index, total), + * where total is the total number of items being reduced, and will be the same + * in each call to reduceFunc. + * @param initialValue starting value, or a {@link Promise} for the starting value + * + * @returns {Promise} that will resolve to the final reduced value + */ + function reduce(promisesOrValues, reduceFunc, initialValue) { + + var total, args; + + total = promisesOrValues.length; + + // Skip promisesOrValues, since it will be used as 'this' in the call + // to the actual reduce engine below. + + // Wrap the supplied reduceFunc with one that handles promises and then + // delegates to the supplied. + + args = [ + function (current, val, i) { + return when(current, function (c) { + return when(val, function (value) { + return reduceFunc(c, value, i, total); + }); + }); + } + ]; + + if (arguments.length >= 3) args.push(initialValue); + + return promise(reduceArray.apply(promisesOrValues, args)); + } + + /** + * Ensure that resolution of promiseOrValue will complete resolver with the completion + * value of promiseOrValue, or instead with resolveValue if it is provided. + * + * @memberOf when + * + * @param promiseOrValue + * @param resolver {Resolver} + * @param [resolveValue] anything + * + * @returns {Promise} + */ + function chain(promiseOrValue, resolver, resolveValue) { + var useResolveValue = arguments.length > 2; + + return when(promiseOrValue, + function(val) { + if(useResolveValue) val = resolveValue; + resolver.resolve(val); + return val; + }, + function(e) { + resolver.reject(e); + return rejected(e); + }, + resolver.progress + ); + } + + // + // Public API + // + + when.defer = defer; + + when.isPromise = isPromise; + when.some = some; + when.all = all; + when.any = any; + + when.reduce = reduce; + when.map = map; + + when.chain = chain; + + return when; +}); +})(typeof define == 'function' + ? define + : function (factory) { typeof module != 'undefined' + ? (module.exports = factory()) + : (this.when = factory()); + } + // Boilerplate for AMD, Node, and browser global +); diff --git a/src/filesystem.js b/src/filesystem.js new file mode 100644 index 0000000..894b776 --- /dev/null +++ b/src/filesystem.js @@ -0,0 +1,194 @@ +/* +Copyright (c) 2012, Alan Kligman +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +define(function(require) { + 'use strict'; + + var when = require("when"); + var debug = require("debug"); + + var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; + var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; + + var TEMPORARY = 0; + var PERSISTENT = 1; + + function guid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); + return v.toString(16); + }).toUpperCase(); + } + + function FileError(code) { + this.code = code; + // FIXME: add a message field with the text error + }; + FileError.NOT_FOUND_ERR = 1; + FileError.SECURITY_ERR = 2; + FileError.ABORT_ERR = 3; + FileError.NOT_READABLE_ERR = 4; + FileError.ENCODING_ERR = 5; + FileError.NO_MODIFICATION_ALLOWED_ERR = 6; + FileError.INVALID_STATE_ERR = 7; + FileError.SYNTAX_ERR = 8; + FileError.INVALID_MODIFICATION_ERR = 9; + FileError.QUOTA_EXCEEDED_ERR = 10; + FileError.TYPE_MISMATCH_ERR = 11; + FileError.PATH_EXISTS_ERR = 12; + + function Entry() {} + Entry.prototype.move = function move(parent, newName, successCallback, errorCallback) { + }; + Entry.prototype.copy = function copy(parent, newName, successCallback, errorCallback) { + }; + Entry.prototype.remove = function remove(successCallback, errorCallback) { + }; + Entry.prototype.getParent = function getParent(successCallback, errorCallback) { + }; + Entry.prototype.getMetadata = function getMetadata(successCallback, errorCallback) { + }; + /*Entry.prototype.toUrl = function toUrl(mimeType) { + };*/ + + function DirectoryEntry(fs, path, name, parent) { + this.isFile = false; + this.isDirectory = true; + this.name = name; + this.path = path; // FIXME: account for the parent path + this.filesystem = fs; + this.parent = parent; + } + DirectoryEntry.prototype = new Entry(); + DirectoryEntry.prototype.createReader = function createReader() { + }; + DirectoryEntry.prototype.removeRecursively = function removeRecursively(successCallback, errorCallback) { + }; + DirectoryEntry.prototype.getFile = function getFile(path, options, successCallback, errorCallback) { + }; + DirectoryEntry.prototype.getDirectory = function getDirectory(path, options, successCallback, errorCallback) { + }; + + function FileEntry(fs, path, name, parent) { + this.isFile = true; + this.isDirectory = false; + this.name = name; + this.path = path; // FIXME: account for the parent path + this.filesystem = fs; + this.parent = parent; + } + FileEntry.prototype = new Entry(); + FileEntry.prototype.createWriter = function createWriter(successCallback, errorCallback) { + }; + FileEntry.prototype.file = function file(successCallback, errorCallback) { + }; + + var RO = "readonly", + RW = "readwrite"; + + function FileSystem(name, optFormat) { + var fs = this; + var FILES = "files"; + fs.name = name || "default"; + fs.pending = {}; + + fs.state = FileSystem.UNINITIALIZED; + var deferred; + fs.then; + fs.root; + + function updateState() { + if(FileSystem.READY === fs.state && Object.keys(fs.pending).length > 0) { + debug.info("filesystem has pending requests"); + fs.state = FileSystem.PENDING; + deferred = when.defer(); + fs.then = deferred.promise.then; + } else if(FileSystem.PENDING === fs.state && Object.keys(fs.pending).length === 0) { + debug.info("filesystem is ready"); + fs.state = FileSystem.READY; + deferred.resolve(fs); + } else if(FileSystem.UNINITIALIZED === fs.state) { + // Start the file system in the READY state and provide an initial resolved promise + fs.state = FileSystem.READY; + deferred = when.defer(); + fs.then = deferred.promise.then; + deferred.resolve(fs); + debug.info("filesystem is initialized"); + } + } + + function queuePending(request) { + var id = guid(); + request.id = id; + fs.pending[id] = request; + updateState(); + return request; + } + + function clearPending(request) { + var id = request.id; + if(fs.pending.hasOwnProperty(id)) { + delete fs.pending[id]; + } + delete request.id; + updateState(); + return request; + } + + var db; + var format = undefined !== optFormat ? optFormat : false; + var deferred = when.defer(); + fs.then = deferred.promise.then; + + updateState(); + var openRequest = queuePending(indexedDB.open(name)); + fs.state = FileSystem.PENDING; + + openRequest.onsuccess = function(e) { + db = e.target.result; + if(format) { + debug.info("format required"); + var transaction = db.transaction([FILES], RW); + var store = transaction.objectStore(FILES); + var formatRequest = queuePending(store.put({}, "/")); + formatRequest.onsuccess = function(e) { + debug.info("format complete"); + clearPending(formatRequest); + }; + } + clearPending(openRequest); + }; + + openRequest.onupgradeneeded = function(e) { + db = e.target.result; + if(db.objectStoreNames.contains("files")) { + db.deleteObjectStore("files"); + } + var store = db.createObjectStore("files"); + store.createIndex("parent", "parent"); + store.createIndex("name", "name"); + + format = true; + }; + + openRequest.onerror = function(e) { + clearPending(openRequest); + }; + } + FileSystem.READY = 0; + FileSystem.PENDING = 1; + FileSystem.UNINITIALIZED = 2; + + return FileSystem; + +}); \ No newline at end of file