Repository: requirejs/alameda Branch: master Commit: 3d3c32c73cfb Files: 73 Total size: 207.6 KB Directory structure: gitextract_3mab732j/ ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── alameda.js ├── bower.json ├── copyrequirejstests.sh ├── package.json ├── shrinktest.sh └── tests/ ├── all.js ├── circular/ │ ├── 414/ │ │ ├── 414.html │ │ └── 414.js │ ├── circular.html │ └── transpiler/ │ ├── transpiler.html │ └── transpiler.js ├── context/ │ └── context.html ├── dataMainBaseUrl/ │ ├── dataMainBaseUrl.html │ └── js/ │ └── sub/ │ ├── main.js │ └── other.js ├── defineDouble/ │ └── defineDouble.html ├── doh/ │ ├── LICENSE │ ├── README │ ├── _browserRunner.js │ ├── _nodeRunner.js │ ├── _rhinoRunner.js │ ├── _sounds/ │ │ └── LICENSE │ ├── runner.html │ ├── runner.js │ └── runner.sh ├── emptyRequire/ │ └── emptyRequire.html ├── errback/ │ └── errback.html ├── hasOwnProperty/ │ └── hasOwnProperty.html ├── index.html ├── insertRequire/ │ └── insertRequire.html ├── mapConfig/ │ ├── mapConfig.html │ ├── mapConfig.js │ ├── mapConfigPlugin.html │ ├── mapConfigPlugin.js │ ├── mapConfigSpecificity.html │ ├── mapConfigSpecificity.js │ ├── mapConfigStar.html │ ├── mapConfigStar.js │ ├── mapConfigStarAdapter.html │ └── mapConfigStarAdapter.js ├── moduleConfig/ │ ├── moduleConfig.html │ └── moduleConfig.js ├── onNodeCreated/ │ ├── a.js │ ├── b.js │ └── onNodeCreated.html ├── plugins/ │ ├── coffee.html │ ├── coffee.js │ ├── pluginMapSameName/ │ │ ├── pluginMapSameName.html │ │ └── pluginMapSameName.js │ ├── plugins.html │ ├── plugins.js │ ├── pluginsConfig/ │ │ ├── pluginsConfig.html │ │ └── pluginsConfig.js │ ├── text.html │ └── text.js ├── preserveDeps/ │ └── preserveDeps.html ├── promiseRequire/ │ ├── app.js │ ├── bar.js │ └── promiseRequire.html ├── relativePaths/ │ └── relativePaths.html ├── runner.js ├── server.js ├── shim/ │ ├── shim.html │ └── shim.js ├── simple.html ├── simple.js ├── specialDeps/ │ ├── specialDeps-tests.js │ └── specialDeps.html └── timeoutErrors/ └── timeoutErrors.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ alameda.min.js alameda.min.js.gz copy-to-prim.sh require.js testBaseUrl.js tests-requirejs ================================================ FILE: .npmignore ================================================ LICENSE alameda.min.js alameda.min.js.gz copyrequirejstests.sh copy-to-prim.sh require.js shrinktest.sh testBaseUrl.js tests tests-requirejs ================================================ FILE: LICENSE ================================================ Copyright jQuery Foundation and other contributors, https://jquery.org/ This software consists of voluntary contributions made by many individuals. For exact contribution history, see the revision history available at https://github.com/requirejs/alameda The following license applies to all parts of this software except as documented below: ==== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ==== Copyright and related rights for sample code are waived via CC0. Sample code is defined as all source code displayed within the prose of the documentation. CC0: http://creativecommons.org/publicdomain/zero/1.0/ ==== Files located in the node_modules directory, and certain utilities used to build or test the software in the tests and tests-requirejs directories, are externally maintained libraries used by this software which have their own licenses; we recommend you read them, as their terms may differ from the terms above. ================================================ FILE: README.md ================================================ # alameda An AMD loader, like [requirejs](http://requirejs.org), but with the following implementation changes: * Assumes Promises are available in the JS environment. * Targets "modern" web browsers that implement standardized script.onload behavior: execute load listener right after script execution, something IE9 and below did not do. * Assumes browser support for Array.isArray, array extras, ES5 features. * Does not support a couple of less-used APIs (see tests section below). These changes means alameda is around 35% smaller than requirejs, 4.1 KB vs 6.4 KB, minified+gzipped sizes. Browser support: browsers that [natively provide Promises](http://caniuse.com/#feat=promises). If you need to support IE 10 and 11, the [alameda-prim](https://github.com/requirejs/alameda-prim) project includes a private promise shim. You can continue to use requirejs and the r.js optimizer for other scenarios. The r.js optimizer works well with alameda-based projects. ## Install [Latest release information](https://github.com/requirejs/alameda/releases) If using a package manager: ``` npm install alameda # or [npm | bower | volo] install requirejs/alameda ``` ## API alameda supports [the requirejs API](http://requirejs.org/docs/api.html). It even declares `requirejs`, to make passing the requirejs tests easier. alameda also has a good chance of becoming requirejs in a far-future requirejs version. There are some differences with requirejs though: ### require promise `require([])` will return a promise. The success callback passed to `require([])` should return a value if you want a value to be passed to the next .then() in the promise chain. ```javascript require(['a', 'b'], function(a, b) { // succes callback. Return a value for the next part in the promise chain. return [a, b]; }).then(function(mods) { //mods[0] is the 'a' module, mods[1] is the 'b' module in this case. }); ``` ### config.defaultErrback In requirejs and alameda, with this sort of call, the errback will be called if there is an error in either loading `['a', 'b']` or if the success callback throws an error. ```javascript require(['a', 'b'], function(a, b) { // success callback }, function(err) { // errback, called if 'a', 'b' do not load, or // if the success callback is called. }); ``` So, the errback operates like: ```javascript require([], function() {}).catch(function(err) {})`; ```` If you do not pass an errback into the require() call, and instead use a .then() or .catch() to deal with the error, you still may see the error surface outside. This is done because browsers do not all show unhandled errors in a promise chain, and the require() call itself does not know if an error handler was chained on the end, so it generates an error to make debugging and development easier. However, if you are properly chaining error handlers but do not pass an errback as the third arg to the require([]) call, then you can turn off this extra error surfacing by doing: ```javascript requirejs.config({ defaultErrback: null }); ``` If you pass a function for the `defaultErrback` value, then that will be used instead of the default "delayedError" handler used by alameda to surface the error. ## onError is context-specific When using contexts, in requirejs, all top level errors would bubble up to requirejs.onError, but in alameda, the context's onError is called instead. Example: ```javascript var fooReq = requirejs.config({ context: 'foo' }); requirejs.onError = function () { console.log('requirejs.onError'); }; fooReq.onError = function () { console.log('fooReq.onError'); }; fooReq(['nonexistent']); // In alameda, fooReq.onError() is called, in requirejs, requirejs.onError is called. ``` ## onResourceLoad requirejs supports a hook into its internals, [onResourceLoad](https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad). alameda supports an onResourceLoad function too, but the arguments passed to the function are objects that have different property names than the ones in requirejs. This is the general signature, which is the same between alameda and requirejs: ```javascript alameda.onResourceLoad = function (context, map, depArray) {}; ``` The differences between property names in the different argument objects is described below. See the [onResourceLoad page](https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad) for the description of the arguments. ### context | alameda | requirejs | | ------- | --------- | | `id` | `contextName` | ### map | alameda | requirejs | | ------- | --------- | | `pr` | `prefix` | | `n` | `name` | | n/a | `parentMap` | | `url` | `url` | | n/a | `originalName` | | `id` | `fullName` | ### depArray An array of `map` objects with the same properties as the `map` listing above. ## License MIT ## Code of Conduct [jQuery Foundation Code of Conduct](https://jquery.org/conduct/). ## Running tests The tests are pulled from almond and requirejs. All tests should be served through a local web server, as the text loader plugin is used for some tests, and some browsers restrict local XHR usage when the files are served from a `file://` URL. ### Bundled tests To run the tests that are just part of this repo, open `tests/index.html` in a web browser. ### requirejs tests To run the requirejs tests, first make sure the following projects have been cloned and are **siblings** to the the alameda repo: * https://github.com/requirejs/requirejs * https://github.com/requirejs/domReady * https://github.com/requirejs/text * https://github.com/requirejs/i18n Then do the following: * symlink alameda.js to require.js * ./copyrequirejstests.sh #### requirejs tests that do not pass * require.undef()-related tests. * onResourceLoadNestedRequire: depends on implementing requirejs.onResourceLoad hook used for builds/some third party tools. This API is not required for normal module loading. ## How to get help * Open issues in the [issue tracker](https://github.com/requirejs/alameda/issues). * Contact the [requirejs list](https://groups.google.com/group/requirejs). ================================================ FILE: alameda.js ================================================ /** * @license alameda 1.4.0 Copyright jQuery Foundation and other contributors. * Released under MIT license, https://github.com/requirejs/alameda/blob/master/LICENSE */ // Going sloppy because loader plugin execs may depend on non-strict execution. /*jslint sloppy: true, nomen: true, regexp: true */ /*global document, navigator, importScripts, Promise, setTimeout */ var requirejs, require, define; (function (global, Promise, undef) { if (!Promise) { throw new Error('No Promise implementation available'); } var topReq, dataMain, src, subPath, bootstrapConfig = requirejs || require, hasOwn = Object.prototype.hasOwnProperty, contexts = {}, queue = [], currDirRegExp = /^\.\//, urlRegExp = /^\/|\:|\?|\.js$/, commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, slice = Array.prototype.slice; if (typeof requirejs === 'function') { return; } var asap = Promise.resolve(undefined); // Could match something like ')//comment', do not lose the prefix to comment. function commentReplace(match, singlePrefix) { return singlePrefix || ''; } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return obj && hasProp(obj, prop) && obj[prop]; } function obj() { return Object.create(null); } /** * 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 (hasProp(obj, 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. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !Array.isArray(value) && typeof value !== 'function' && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } // Allow getting a global that expressed in // dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; value.split('.').forEach(function (part) { g = g[part]; }); return g; } function newContext(contextName) { var req, main, makeMap, callDep, handlers, checkingLater, load, context, defined = obj(), waiting = obj(), 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: {} }, mapCache = obj(), requireDeferreds = [], deferreds = obj(), calledDefine = obj(), calledPlugin = obj(), loadCount = 0, startTime = (new Date()).getTime(), errCount = 0, trackedErrors = obj(), urlFetched = obj(), bundlesMap = obj(), asyncResolve = Promise.resolve(); /** * 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, length = ary.length; for (i = 0; i < 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; } } } } /** * 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, baseParts = baseName && baseName.split('/'), normalizedBaseParts = baseParts, 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, ''); } // Starts with a '.' so need the baseName if (name[0].charAt(0) === '.' && baseParts) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = normalizedBaseParts.concat(name); } trimDots(name); name = name.join('/'); } // Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); 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; } } } } // 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 (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function makeShimExports(value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; } function takeQueue(anonId) { var i, id, args, shim; for (i = 0; i < queue.length; i += 1) { // Peek to see if anon if (typeof queue[i][0] !== 'string') { if (anonId) { queue[i].unshift(anonId); anonId = undef; } else { // Not our anon module, stop. break; } } args = queue.shift(); id = args[0]; i -= 1; if (!(id in defined) && !(id in waiting)) { if (id in deferreds) { main.apply(undef, args); } else { waiting[id] = args; } } } // if get to the end and still have anonId, then could be // a shimmed dependency. if (anonId) { shim = getOwn(config.shim, anonId) || {}; main(anonId, shim.deps || [], shim.exportsFn); } } function makeRequire(relName, topLevel) { var req = function (deps, callback, errback, alt) { var name, cfg; if (topLevel) { takeQueue(); } if (typeof deps === "string") { if (handlers[deps]) { return handlers[deps](relName); } // Just return the module wanted. In this scenario, the // deps arg is the module name, and second arg (if passed) // is just the relName. // Normalize module name, if it contains . or .. name = makeMap(deps, relName, true).id; if (!(name in defined)) { throw new Error('Not loaded: ' + name); } return defined[name]; } else if (deps && !Array.isArray(deps)) { // deps is a config object, not an array. cfg = deps; deps = undef; if (Array.isArray(callback)) { // callback is an array, which means it is a dependency list. // Adjust args if there are dependencies deps = callback; callback = errback; errback = alt; } if (topLevel) { // Could be a new context, so call returned require return req.config(cfg)(deps, callback, errback); } } // Support require(['a']) callback = callback || function () { // In case used later as a promise then value, return the // arguments as an array. return slice.call(arguments, 0); }; // Complete async to maintain expected execution semantics. return asyncResolve.then(function () { // Grab any modules that were defined after a require call. takeQueue(); return main(undef, deps || [], callback, errback, relName); }); }; req.isBrowser = typeof document !== 'undefined' && typeof navigator !== 'undefined'; req.nameToUrl = function (moduleName, ext, skipExt) { var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); if (pkgMain) { moduleName = pkgMain; } bundleId = getOwn(bundlesMap, moduleName); if (bundleId) { return req.nameToUrl(bundleId, ext, skipExt); } // If a colon is in the URL, it indicates a protocol is used and it is // just an URL to a file, or if it starts with a slash, contains a query // arg (i.e. ?) 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 (urlRegExp.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 (Array.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\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs && !/^blob\:/.test(url) ? url + config.urlArgs(moduleName, url) : url; }; /** * 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. */ req.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); } return req.nameToUrl(normalize(moduleNamePlusExt, relName), ext, true); }; req.defined = function (id) { return makeMap(id, relName, true).id in defined; }; req.specified = function (id) { id = makeMap(id, relName, true).id; return id in defined || id in deferreds; }; return req; } function resolve(name, d, value) { if (name) { defined[name] = value; if (requirejs.onResourceLoad) { requirejs.onResourceLoad(context, d.map, d.deps); } } d.finished = true; d.resolve(value); } function reject(d, err) { d.finished = true; d.rejected = true; d.reject(err); } function makeNormalize(relName) { return function (name) { return normalize(name, relName, true); }; } function defineModule(d) { d.factoryCalled = true; var ret, name = d.map.id; try { ret = context.execCb(name, d.factory, d.values, defined[name]); } catch(err) { return reject(d, err); } if (name) { // 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 (ret === undef) { if (d.cjsModule) { ret = d.cjsModule.exports; } else if (d.usingExports) { ret = defined[name]; } } } else { // Remove the require deferred from the list to // make cycle searching faster. Do not need to track // it anymore either. requireDeferreds.splice(requireDeferreds.indexOf(d), 1); } resolve(name, d, ret); } // This method is attached to every module deferred, // so the "this" in here is the module deferred object. function depFinished(val, i) { if (!this.rejected && !this.depDefined[i]) { this.depDefined[i] = true; this.depCount += 1; this.values[i] = val; if (!this.depending && this.depCount === this.depMax) { defineModule(this); } } } function makeDefer(name, calculatedMap) { var d = {}; d.promise = new Promise(function (resolve, reject) { d.resolve = resolve; d.reject = function(err) { if (!name) { requireDeferreds.splice(requireDeferreds.indexOf(d), 1); } reject(err); }; }); d.map = name ? (calculatedMap || makeMap(name)) : {}; d.depCount = 0; d.depMax = 0; d.values = []; d.depDefined = []; d.depFinished = depFinished; if (d.map.pr) { // Plugin resource ID, implicitly // depends on plugin. Track it in deps // so cycle breaking can work d.deps = [makeMap(d.map.pr)]; } return d; } function getDefer(name, calculatedMap) { var d; if (name) { d = (name in deferreds) && deferreds[name]; if (!d) { d = deferreds[name] = makeDefer(name, calculatedMap); } } else { d = makeDefer(); requireDeferreds.push(d); } return d; } function makeErrback(d, name) { return function (err) { if (!d.rejected) { if (!err.dynaId) { err.dynaId = 'id' + (errCount += 1); err.requireModules = [name]; } reject(d, err); } }; } function waitForDep(depMap, relName, d, i) { d.depMax += 1; // Do the fail at the end to catch errors // in the then callback execution. callDep(depMap, relName).then(function (val) { d.depFinished(val, i); }, makeErrback(d, depMap.id)).catch(makeErrback(d, d.map.id)); } function makeLoad(id) { var fromTextCalled; function load(value) { // Protect against older plugins that call load after // calling load.fromText if (!fromTextCalled) { resolve(id, getDefer(id), value); } } load.error = function (err) { reject(getDefer(id), err); }; load.fromText = function (text, textAlt) { /*jslint evil: true */ var d = getDefer(id), map = makeMap(makeMap(id).n), plainId = map.id, execError; fromTextCalled = true; // Set up the factory just to be a return of the value from // plainId. d.factory = function (p, val) { return val; }; // As of requirejs 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; } // Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[plainId] = config.config[id]; } try { req.exec(text); } catch (e) { execError = new Error('fromText eval for ' + plainId + ' failed: ' + e); execError.requireType = 'fromtexteval'; reject(d, execError); } // Execute any waiting define created by the plainId takeQueue(plainId); // Mark this as a dependency for the plugin // resource d.deps = [map]; waitForDep(map, null, d, d.deps.length); }; return load; } load = typeof importScripts === 'function' ? function (map) { var url = map.url; if (urlFetched[url]) { return; } urlFetched[url] = true; // Ask for the deferred so loading is triggered. // Do this before loading, since loading is sync. getDefer(map.id); importScripts(url); takeQueue(map.id); } : function (map) { var script, id = map.id, url = map.url; if (urlFetched[url]) { return; } urlFetched[url] = true; script = document.createElement('script'); script.setAttribute('data-requiremodule', id); script.type = config.scriptType || 'text/javascript'; script.charset = 'utf-8'; script.async = true; loadCount += 1; script.addEventListener('load', function () { loadCount -= 1; takeQueue(id); }, false); script.addEventListener('error', function () { loadCount -= 1; var err, pathConfig = getOwn(config.paths, id); if (pathConfig && Array.isArray(pathConfig) && pathConfig.length > 1) { script.parentNode.removeChild(script); // Pop off the first array value, since it failed, and // retry pathConfig.shift(); var d = getDefer(id); d.map = makeMap(id); // mapCache will have returned previous map value, update the // url, which will also update mapCache value. d.map.url = req.nameToUrl(id); load(d.map); } else { err = new Error('Load failed: ' + id + ': ' + script.src); err.requireModules = [id]; err.requireType = 'scripterror'; reject(getDefer(id), err); } }, false); script.src = url; if (config.onNodeCreated) { config.onNodeCreated(script, config, id, url); } // If the script is cached, IE10 executes the script body and the // onload handler synchronously here. That's a spec violation, // so be sure to do this asynchronously. if (document.documentMode === 10) { asap.then(function() { document.head.appendChild(script); }); } else { document.head.appendChild(script); } }; function callPlugin(plugin, map, relName) { plugin.load(map.n, makeRequire(relName), makeLoad(map.id), config); } callDep = function (map, relName) { var args, bundleId, name = map.id, shim = config.shim[name]; if (name in waiting) { args = waiting[name]; delete waiting[name]; main.apply(undef, args); } else if (!(name in deferreds)) { if (map.pr) { // If a bundles config, then just load that file instead to // resolve the plugin, as it is built into that bundle. if ((bundleId = getOwn(bundlesMap, name))) { map.url = req.nameToUrl(bundleId); load(map); } else { return callDep(makeMap(map.pr)).then(function (plugin) { // Redo map now that plugin is known to be loaded var newMap = map.prn ? map : makeMap(name, relName, true), newId = newMap.id, shim = getOwn(config.shim, newId); // Make sure to only call load once per resource. Many // calls could have been queued waiting for plugin to load. if (!(newId in calledPlugin)) { calledPlugin[newId] = true; if (shim && shim.deps) { req(shim.deps, function () { callPlugin(plugin, newMap, relName); }); } else { callPlugin(plugin, newMap, relName); } } return getDefer(newId).promise; }); } } else if (shim && shim.deps) { req(shim.deps, function () { load(map); }); } else { load(map); } } return getDefer(name).promise; }; // 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); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName, applyMap) { if (typeof name !== 'string') { return name; } var plugin, url, parts, prefix, result, prefixNormalized, cacheKey = name + ' & ' + (relName || '') + ' & ' + !!applyMap; parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (!prefix && (cacheKey in mapCache)) { return mapCache[cacheKey]; } if (prefix) { prefix = normalize(prefix, relName, applyMap); plugin = (prefix in defined) && defined[prefix]; } // Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); prefixNormalized = true; } 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 requirejs#1131 name = name.indexOf('!') === -1 ? normalize(name, relName, applyMap) : name; } } else { name = normalize(name, relName, applyMap); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; url = req.nameToUrl(name); } // Using ridiculous property names for space reasons result = { id: prefix ? prefix + '!' + name : name, // fullName n: name, pr: prefix, url: url, prn: prefix && prefixNormalized }; if (!prefix) { mapCache[cacheKey] = result; } return result; }; handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name, url) { return { id: name, uri: url || '', exports: handlers.exports(name), config: function () { return getOwn(config.config, name) || {}; } }; } }; function breakCycle(d, traced, processed) { var id = d.map.id; traced[id] = true; if (!d.finished && d.deps) { d.deps.forEach(function (depMap) { var depId = depMap.id, dep = !hasProp(handlers, depId) && getDefer(depId, depMap); // 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 && !dep.finished && !processed[depId]) { if (hasProp(traced, depId)) { d.deps.forEach(function (depMap, i) { if (depMap.id === depId) { d.depFinished(defined[depId], i); } }); } else { breakCycle(dep, traced, processed); } } }); } processed[id] = true; } function check(d) { var err, mid, dfd, notFinished = [], waitInterval = config.waitSeconds * 1000, // It is possible to disable the wait interval by using waitSeconds 0. expired = waitInterval && (startTime + waitInterval) < (new Date()).getTime(); if (loadCount === 0) { // If passed in a deferred, it is for a specific require call. // Could be a sync case that needs resolution right away. // Otherwise, if no deferred, means it was the last ditch // timeout-based check, so check all waiting require deferreds. if (d) { if (!d.finished) { breakCycle(d, {}, {}); } } else if (requireDeferreds.length) { requireDeferreds.forEach(function (d) { breakCycle(d, {}, {}); }); } } // 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) { // If wait time expired, throw error of unloaded modules. for (mid in deferreds) { dfd = deferreds[mid]; if (!dfd.finished) { notFinished.push(dfd.map.id); } } err = new Error('Timeout for modules: ' + notFinished); err.requireModules = notFinished; err.requireType = 'timeout'; notFinished.forEach(function (id) { reject(getDefer(id), err); }); } else if (loadCount || requireDeferreds.length) { // Something is still waiting to load. Wait for it, but only // if a later check is not already scheduled. Using setTimeout // because want other things in the event loop to happen, // to help in dependency resolution, and this is really a // last ditch check, mostly for detecting timeouts (cycles // should come through the main() use of check()), so it can // wait a bit before doing the final check. if (!checkingLater) { checkingLater = true; setTimeout(function () { checkingLater = false; check(); }, 70); } } } // Used to break out of the promise try/catch chains. function delayedError(e) { setTimeout(function () { if (!e.dynaId || !trackedErrors[e.dynaId]) { trackedErrors[e.dynaId] = true; req.onError(e); } }); return e; } main = function (name, deps, factory, errback, relName) { if (name) { // Only allow main calling once per module. if (name in calledDefine) { return; } calledDefine[name] = true; } var d = getDefer(name); // This module may not have dependencies if (deps && !Array.isArray(deps)) { // deps is not an array, so probably means // an object literal or factory function for // the value. Adjust args. factory = deps; deps = []; } // Create fresh array instead of modifying passed in value. deps = deps ? slice.call(deps, 0) : null; if (!errback) { if (hasProp(config, 'defaultErrback')) { if (config.defaultErrback) { errback = config.defaultErrback; } } else { errback = delayedError; } } if (errback) { d.promise.catch(errback); } // Use name if no relName relName = relName || name; // Call the factory to define the module, if necessary. if (typeof factory === 'function') { if (!deps.length && factory.length) { // Remove comments from the callback string, // look for require calls, and pull them into the dependencies, // but only if there are function args. factory .toString() .replace(commentRegExp, commentReplace) .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 = (factory.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } // Save info for use later. d.factory = factory; d.deps = deps; d.depending = true; deps.forEach(function (depName, i) { var depMap; deps[i] = depMap = makeMap(depName, relName, true); depName = depMap.id; // Fast path CommonJS standard dependencies. if (depName === "require") { d.values[i] = handlers.require(name); } else if (depName === "exports") { // CommonJS module spec 1.1 d.values[i] = handlers.exports(name); d.usingExports = true; } else if (depName === "module") { // CommonJS module spec 1.1 d.values[i] = d.cjsModule = handlers.module(name, d.map.url); } else if (depName === undefined) { d.values[i] = undefined; } else { waitForDep(depMap, relName, d, i); } }); d.depending = false; // Some modules just depend on the require, exports, modules, so // trigger their definition here if so. if (d.depCount === d.depMax) { defineModule(d); } } else if (name) { // May just be an object definition for the module. Only // worry about defining if have a module name. resolve(name, d, factory); } startTime = (new Date()).getTime(); if (!name) { check(d); } return d.promise; }; req = makeRequire(null, true); /* * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { if (cfg.context && cfg.context !== contextName) { var existingContext = getOwn(contexts, cfg.context); if (existingContext) { return existingContext.req.config(cfg); } else { return newContext(cfg.context).config(cfg); } } // Since config changed, mapCache may not be valid any more. mapCache = obj(); // Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } // Convert old style urlArgs string to a function. if (typeof cfg.urlArgs === 'string') { var urlArgs = cfg.urlArgs; cfg.urlArgs = function(id, url) { return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; }; } // Save off the paths and packages since they require special processing, // they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); // Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { value.forEach(function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } // Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { // Normalize the structure if (Array.isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = makeShimExports(value); } shim[id] = value; }); config.shim = shim; } // Adjust packages if necessary. if (cfg.packages) { cfg.packages.forEach(function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } // 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, ''); }); } // 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) { req(cfg.deps, cfg.callback); } return req; }; req.onError = function (err) { throw err; }; context = { id: contextName, defined: defined, waiting: waiting, config: config, deferreds: deferreds, req: req, execCb: function execCb(name, callback, args, exports) { return callback.apply(exports, args); } }; contexts[contextName] = context; return req; } requirejs = topReq = newContext('_'); if (typeof require !== 'function') { require = topReq; } /** * 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. */ topReq.exec = function (text) { /*jslint evil: true */ return eval(text); }; topReq.contexts = contexts; define = function () { queue.push(slice.call(arguments, 0)); }; define.amd = { jQuery: true }; if (bootstrapConfig) { topReq.config(bootstrapConfig); } // data-main support. if (topReq.isBrowser && !contexts._.config.skipDataMain) { dataMain = document.querySelectorAll('script[data-main]')[0]; dataMain = dataMain && dataMain.getAttribute('data-main'); if (dataMain) { // Strip off any trailing .js since dataMain is now // like a module name. dataMain = dataMain.replace(jsSuffixRegExp, ''); // Set final baseUrl if there is not already an explicit one, // but only do so if the data-main value is not a loader plugin // module ID. if ((!bootstrapConfig || !bootstrapConfig.baseUrl) && dataMain.indexOf('!') === -1) { // Pull off the directory of data-main for use as the // baseUrl. src = dataMain.split('/'); dataMain = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; topReq.config({baseUrl: subPath}); } topReq([dataMain]); } } }(this, (typeof Promise !== 'undefined' ? Promise : undefined))); ================================================ FILE: bower.json ================================================ { "name": "alameda", "version": "1.4.0", "ignore": [ ".gitignore", ".npmignore", "node_modules", "package.json", "README.md", "tests", "tests-requirejs", "copyrequirejstests.sh", "testBaseUrl.js" ], "homepage": "https://github.com/requirejs/alameda", "authors": [ "jrburke.com" ], "description": "AMD loader, like requirejs, but with promises and for modern browsers", "main": "alameda.js", "license": [ "MIT" ] } ================================================ FILE: copyrequirejstests.sh ================================================ #!/bin/bash cp -r ../requirejs/testBaseUrl.js ./testBaseUrl.js cp -r ../requirejs/tests ./tests-requirejs ================================================ FILE: package.json ================================================ { "name": "alameda", "description": "AMD loader, like requirejs, but with promises and for modern browsers", "version": "1.4.0", "homepage": "http://github.com/requirejs/alameda", "author": "James Burke (http://github.com/jrburke)", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/requirejs/alameda.git" }, "main": "alameda.js", "volo": { "url": "https://raw.github.com/requirejs/alameda/{version}/alameda.js" }, "engines": { "node": ">=0.4.0" } } ================================================ FILE: shrinktest.sh ================================================ #!/bin/sh rm alameda.min.js.gz ls -la alameda.js uglifyjs -c -m -o alameda.min.js alameda.js ls -la alameda.min.js gzip alameda.min.js ls -la alameda.min.js.gz ================================================ FILE: tests/all.js ================================================ doh.registerUrl("simple", "../simple.html"); doh.registerUrl("defineDouble", "../defineDouble/defineDouble.html"); doh.registerUrl("moduleConfig", "../moduleConfig/moduleConfig.html"); doh.registerUrl("mapConfig", "../mapConfig/mapConfig.html"); doh.registerUrl("mapConfigStar", "../mapConfig/mapConfigStar.html"); doh.registerUrl("mapConfigStarAdapter", "../mapConfig/mapConfigStarAdapter.html"); doh.registerUrl("mapConfigSpecificity", "../mapConfig/mapConfigSpecificity.html"); doh.registerUrl("mapConfigPlugin", "../mapConfig/mapConfigPlugin.html"); doh.registerUrl("onNodeCreated", "../onNodeCreated/onNodeCreated.html"); doh.registerUrl("plugins", "../plugins/plugins.html"); doh.registerUrl("pluginsMapSameName", "../plugins/pluginMapSameName/pluginMapSameName.html"); doh.registerUrl("pluginsConfig", "../plugins/pluginsConfig/pluginsConfig.html"); doh.registerUrl("text", "../plugins/text.html"); doh.registerUrl("coffee", "../plugins/coffee.html"); doh.registerUrl("shim", "../shim/shim.html"); doh.registerUrl("insertRequire", "../insertRequire/insertRequire.html", 4000); doh.registerUrl("context", "../context/context.html"); doh.registerUrl("circular", "../circular/circular.html", 4000); doh.registerUrl("circular414", "../circular/414/414.html", 4000); doh.registerUrl("circularTranspiler", "../circular/transpiler/transpiler.html", 4000); doh.registerUrl("relativePaths", "../relativePaths/relativePaths.html"); doh.registerUrl("errback", "../errback/errback.html"); doh.registerUrl("specialDeps", "../specialDeps/specialDeps.html"); doh.registerUrl("hasOwnPropertyTests", "../hasOwnProperty/hasOwnProperty.html"); doh.registerUrl("dataMainBaseUrl", "../dataMainBaseUrl/dataMainBaseUrl.html"); doh.registerUrl("emptyRequire", "../emptyRequire/emptyRequire.html"); doh.registerUrl("promiseRequire", "../promiseRequire/promiseRequire.html"); doh.registerUrl("preserveDeps", "../preserveDeps/preserveDeps.html"); doh.registerUrl("timeoutErrors", "../timeoutErrors/timeoutErrors.html"); ================================================ FILE: tests/circular/414/414.html ================================================ alameda: requirejs#414: Multi-cycle Bundle Test

alameda: requirejs#414: Multi-cycle Bundle Test

A set of modules have multiple cycles in them, but the require() that uses the top module in that bundle should get a fully constructed module set.More info.

Check console for messages

================================================ FILE: tests/circular/414/414.js ================================================ define('C', [ "exports", "./MyClass", "./A", "./B" ], function (exports, MyClass, A, B) { exports.name = "C"; exports.say = function(){ return [MyClass.name, A.name, B.name, exports.name].join(','); }; } ); define('B', [ "exports", "./MyClass", "./A", "./C" ], function (exports, MyClass, A, C) { exports.name = "B"; exports.say = function(){ return [MyClass.name, A.name, exports.name, C.name].join(','); }; } ); define('A', [ "exports", "./MyClass", "./B", "./C" ], function (exports, MyClass, B, C) { exports.name = "A"; exports.say = function(){ return [MyClass.name, exports.name, B.name, C.name].join(','); }; } ); define('MyClass', [ "exports", "./A", "./B", "./C" ], function (exports, A, B, C) { exports.name = "MyClass"; exports.sayAll = function(){ return [ exports.say(), A.say(), B.say(), C.say() ].join(':'); }; exports.say = function(){ return [exports.name, A.name, B.name, C.name].join(','); }; return exports; } ); require({ baseUrl: requirejs.isBrowser ? './' : './circular/414' }, ["MyClass"], function(MyClass) { doh.register( "circular414", [ function circularComplexPlugin(t) { t.is("MyClass,A,B,C:MyClass,A,B,C:MyClass,A,B,C:MyClass,A,B,C", MyClass.sayAll()); } ] ); doh.run(); } ); define("414-tests", function(){}); ================================================ FILE: tests/circular/circular.html ================================================ alameda: circular Test

alameda: circular Test

Test circular dependencies with alameda. More info: 17.

Check console for messages

================================================ FILE: tests/circular/transpiler/transpiler.html ================================================ alameda: Circular Transpiler Plugin Test

alameda: Circular Transpiler Plugin Test

Test support for transpiled modules with cycles in them More info: 356.

Check console for messages

================================================ FILE: tests/circular/transpiler/transpiler.js ================================================ /*jslint strict: false, plusplus: false */ /*global define: false, require: false, XMLHttpRequest: false, ActiveXObject: false, window: false, Packages: false, java: false, process: false */ (function () { //Load the text plugin, so that the XHR calls can be made. var buildMap = {}, fetchText, fs, progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']; function createXhr() { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else { for (i = 0; i < 3; i++) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } if (!xhr) { throw new Error("require.getXhr(): XMLHttpRequest not available"); } return xhr; } if (typeof window !== "undefined" && window.navigator && window.document) { fetchText = function (url, callback) { var xhr = createXhr(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseText); } }; xhr.send(null); }; } else if (typeof process !== "undefined" && process.versions && !!process.versions.node) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); fetchText = function (url, callback) { callback(fs.readFileSync(url, 'utf8')); }; } else if (typeof Packages !== 'undefined') { //Why Java, why is this so awkward? fetchText = function (url, callback) { var encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), stringBuffer, line, content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } define('refine',[],function () { return { load: function (name, parentRequire, load, config) { var url = parentRequire.toUrl(name + '.refine'); fetchText(url, function (text) { text = text.replace(/refine\s*\(/g, 'define('); if (config.isBuild) { buildMap[name] = text; } //Add in helpful debug line text += "\r\n//@ sourceURL=" + url; load.fromText(text); parentRequire([name], function (value) { load(value); }); }); }, write: function (pluginName, name, write) { if (name in buildMap) { var text = buildMap[name]; write.asModule(pluginName + "!" + name, text); } } }; }); }()); define('refine!c',['refine!a', 'exports'], function (a, exports) { exports.name = 'c'; exports.a = a; }); define('refine!b',['refine!c', 'exports'], function (c, exports) { exports.name = 'b'; exports.c = c; }); define('refine!a',['refine!b', 'exports'], function (b, exports) { exports.name = 'a'; exports.b = b; }); define('refine!e',['refine!d'], function(d) { function e() { return e.name + require('refine!d').name; } e.name = 'e'; return e; }); define('refine!d',['refine!e'], function(e) { function d() { return require('refine!e')(); } d.name = 'd'; return d; }); require({ baseUrl: requirejs.isBrowser ? './' : './circular/transpiler', paths: { 'text': '../../../../text/text', 'refine': '../../plugins/fromText/refine' } }, ["require", "refine!a", "refine!b", "refine!d"], function(require, a, b, d) { doh.register( "circularTranspiler", [ function circularTranspiler(t) { t.is("a", a.name); t.is("b", a.b.name); t.is("c", a.b.c.name); t.is("b", b.name); t.is("c", b.c.name); t.is("ed", d()); } ] ); doh.run(); } ); define("transpiler-tests", function(){}); ================================================ FILE: tests/context/context.html ================================================ alameda: Context Test

alameda: Context Test

Two requirejs.config calls to the same context should operate on the same context. More info

Check console for messages

================================================ FILE: tests/dataMainBaseUrl/dataMainBaseUrl.html ================================================ alameda: dataMain baseUrl Test

alameda: dataMain baseUrl Test

Makes sure alameda sets baseUrl from data-main. More info: 3.

Check console for messages

================================================ FILE: tests/dataMainBaseUrl/js/sub/main.js ================================================ require(['other'], function(other){ doh.register( 'dataMainBaseUrl', [ function dataMainBaseUrl(t){ t.is('other', other.name); } ] ); doh.run(); }); ================================================ FILE: tests/dataMainBaseUrl/js/sub/other.js ================================================ define({ name: 'other' }); ================================================ FILE: tests/defineDouble/defineDouble.html ================================================ alameda: Define Double Test

alameda: Define Double Test

Make sure a double define only uses the first one. More info

Check console for messages

================================================ FILE: tests/doh/LICENSE ================================================ Dojo is available under *either* the terms of the modified BSD license *or* the Academic Free License version 2.1. As a recipient of Dojo, you may choose which license to receive this code under (except as noted in per-module LICENSE files). Some modules may not be the copyright of the Dojo Foundation. These modules contain explicit declarations of copyright in both the LICENSE files in the directories in which they reside and in the code itself. No external contributions are allowed under licenses which are fundamentally incompatible with the AFL or BSD licenses that Dojo is distributed under. The text of the AFL and BSD licenses is reproduced below. ------------------------------------------------------------------------------- The "New" BSD License: ********************** Copyright (c) 2005-2009, The Dojo Foundation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Dojo Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The Academic Free License, v. 2.1: ********************************** This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: Licensed under the Academic Free License version 2.1 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: a) to reproduce the Original Work in copies; b) to prepare derivative works ("Derivative Works") based upon the Original Work; c) to distribute copies of the Original Work and Derivative Works to the public; d) to perform the Original Work publicly; and e) to display the Original Work publicly. 2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. 5) This section intentionally omitted. 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. 12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. ================================================ FILE: tests/doh/README ================================================ DOH may be run standalone by issuing a command like the following: java -jar ../shrinksafe/js.jar runner.js testModule=tests.colors where the testModule argument is optional and shrinksafe/js.jar is just a convenient copy of the Rhino JavaScript engine -- the custom patch is not required. Optional arguments include: * dojoUrl - specifies the location of dojo.js * testUrl - specifies a Javascript file to load with initialization code * testModule - specifies a test module in the dojo package namespace ================================================ FILE: tests/doh/_browserRunner.js ================================================ if(window["dojo"]){ dojo.provide("doh._browserRunner"); } // FIXME: need to add prompting for monkey-do testing (function(){ doh.setTimeout = function (fn, time) { return setTimeout(fn, time); }; try{ var topdog = (window.parent == window) || !Boolean(window.parent.doh); }catch(e){ //can't access window.parent.doh, then consider ourselves as topdog topdog=true; } if(topdog){ // we're the top-dog window. // borrowed from Dojo, etc. var byId = function(id){ return document.getElementById(id); }; var _addOnEvt = function( type, // string refOrName, // function or string scope){ // object, defaults is window if(!scope){ scope = window; } var funcRef = refOrName; if(typeof refOrName == "string"){ funcRef = scope[refOrName]; } var enclosedFunc = function(){ return funcRef.apply(scope, arguments); }; if((window["dojo"])&&(type == "load")){ dojo.addOnLoad(enclosedFunc); }else{ if(window["attachEvent"]){ window.attachEvent("on"+type, enclosedFunc); }else if(window["addEventListener"]){ window.addEventListener(type, enclosedFunc, false); }else if(document["addEventListener"]){ document.addEventListener(type, enclosedFunc, false); } } }; // // Over-ride or implement base runner.js-provided methods // var escapeXml = function(str){ //summary: // Adds escape sequences for special characters in XML: &<>"' // Optionally skips escapes for single quotes return str.replace(/&/gm, "&").replace(//gm, ">").replace(/"/gm, """); // string }; var _logBacklog = [], _loggedMsgLen = 0; var sendToLogPane = function(args, skip){ var msg = ""; for(var x=0; x "); if(!byId("logBody")){ _logBacklog.push(msg); return; }else if(_logBacklog.length && !skip){ var tm; while((tm=_logBacklog.shift())){ sendToLogPane(tm, true); } } var logBody=byId("logBody"); var tn = document.createElement("div"); tn.innerHTML = msg; //tn.id="logmsg_"+logBody.childNodes.length; logBody.appendChild(tn); _loggedMsgLen++; } var findTarget = function(n){ while(n && !n.getAttribute('_target')){ n=n.parentNode; if(!n.getAttribute){ n=null; } } return n; } doh._jumpToLog = function(e){ //console.log(e); var node = findTarget(e?e.target:window.event.srcElement); if(!node){ return; } var _t = Number(node.getAttribute('_target')); var lb = byId("logBody"); if(_t>=lb.childNodes.length){ return; } var t = lb.childNodes[_t]; t.scrollIntoView(); if(window.dojo){ //t.parentNode.parentNode is
, only it has a explicitly set background-color, //all children of it are transparent var bgColor = dojo.style(t.parentNode.parentNode,'backgroundColor'); //node.parentNode is the tr which has background-color set explicitly var hicolor = dojo.style(node.parentNode,'backgroundColor'); var unhilight = dojo.animateProperty({ node: t, duration: 500, properties: { backgroundColor: { start:hicolor, end: bgColor } }, onEnd: function(){ t.style.backgroundColor=""; } }); var hilight = dojo.animateProperty({ node: t, duration: 500, properties: { backgroundColor: { start:bgColor, end: hicolor } }, onEnd: function(){ unhilight.play(); } }); hilight.play(); } }; doh._jumpToSuite = function(e){ var node = findTarget(e ? e.target : window.event.srcElement); if(!node){ return; } var _g = node.getAttribute('_target'); var gn = getGroupNode(_g); if(!gn){ return; } gn.scrollIntoView(); }; doh._init = (function(oi){ return function(){ var lb = byId("logBody"); if(lb){ // clear the console before each run while(lb.firstChild){ lb.removeChild(lb.firstChild); } _loggedMsgLen = 0; } this._totalTime = 0; this._suiteCount = 0; oi.apply(doh, arguments); } })(doh._init); doh._setupGroupForRun = (function(os){ //overload _setupGroupForRun to record which log line to jump to when a suite is clicked return function(groupName){ var tg = doh._groups[groupName]; doh._curTestCount = tg.length; doh._curGroupCount = 1; var gn = getGroupNode(groupName); if(gn){ //two lines will be added, scroll the second line into view gn.getElementsByTagName("td")[2].setAttribute('_target',_loggedMsgLen+1); } os.apply(doh,arguments); } })(doh._setupGroupForRun); doh._report = (function(or){ //overload _report to insert a tfoot return function(){ var tb = byId("testList"); if(tb){ var tfoots=tb.getElementsByTagName('tfoot'); if(tfoots.length){ tb.removeChild(tfoots[0]); } var foot = tb.createTFoot(); var row = foot.insertRow(-1); row.className = 'inProgress'; var cell=row.insertCell(-1); cell.colSpan=2; cell.innerHTML="Result"; cell = row.insertCell(-1); cell.innerHTML=this._testCount+" tests in "+this._groupCount+" groups /"+this._errorCount+" errors, "+this._failureCount+" failures"; cell.setAttribute('_target',_loggedMsgLen+1); row.insertCell(-1).innerHTML=doh._totalTime+"ms"; } //This location can do the final performance rendering for the results //of any performance tests. var plotResults = null; var standby; if(doh.perfTestResults){ if(window.dojo){ //If we have dojo and here are perf tests results, //well, we'll use the dojo charting functions dojo.require("dojox.charting.Chart2D"); dojo.require("dojox.charting.DataChart"); dojo.require("dojox.charting.plot2d.Scatter"); dojo.require("dojox.charting.plot2d.Lines"); dojo.require("dojo.data.ItemFileReadStore"); plotResults = doh._dojoPlotPerfResults; }else{ plotResults = doh._asciiPlotPerfResults; } try{ var g; var pBody = byId("perfTestsBody"); var chartsToRender = []; if(doh.perfTestResults){ doh.showPerfTestsPage(); } for(g in doh.perfTestResults){ var grp = doh.perfTestResults[g]; var hdr = document.createElement("h1"); hdr.appendChild(document.createTextNode("Group: " + g)); pBody.appendChild(hdr); var ind = document.createElement("blockquote"); pBody.appendChild(ind); var f; for(f in grp){ var fResults = grp[f]; if(!fResults){ continue; } var fhdr = document.createElement("h3"); fhdr.appendChild(document.createTextNode("TEST: " + f)); fhdr.style.textDecoration = "underline"; ind.appendChild(fhdr); var div = document.createElement("div"); ind.appendChild(div); //Figure out the basic info var results = "TRIAL SIZE: " + fResults.trials[0].testIterations + " iterations
" + "NUMBER OF TRIALS: " + fResults.trials.length + "
"; //Figure out the average test pass cost. var i; var iAvgArray = []; var tAvgArray = []; for(i = 0; i < fResults.trials.length; i++){ iAvgArray.push(fResults.trials[i].average); tAvgArray.push(fResults.trials[i].executionTime); } results += "AVERAGE TRIAL EXECUTION TIME: " + doh.average(tAvgArray).toFixed(10) + "ms.
"; results += "MAXIMUM TEST ITERATION TIME: " + doh.max(iAvgArray).toFixed(10) + "ms.
"; results += "MINIMUM TEST ITERATION TIME: " + doh.min(iAvgArray).toFixed(10) + "ms.
"; results += "AVERAGE TEST ITERATION TIME: " + doh.average(iAvgArray).toFixed(10) + "ms.
"; results += "MEDIAN TEST ITERATION TIME: " + doh.median(iAvgArray).toFixed(10) + "ms.
"; results += "VARIANCE TEST ITERATION TIME: " + doh.variance(iAvgArray).toFixed(10) + "ms.
"; results += "STANDARD DEVIATION ON TEST ITERATION TIME: " + doh.standardDeviation(iAvgArray).toFixed(10) + "ms.
"; //Okay, attach it all in. div.innerHTML = results; div = document.createElement("div"); div.innerHTML = "

Average Test Execution Time (in milliseconds, with median line)

"; ind.appendChild(div); div = document.createElement("div"); dojo.style(div, "width", "600px"); dojo.style(div, "height", "250px"); ind.appendChild(div); chartsToRender.push({ div: div, title: "Average Test Execution Time", data: iAvgArray }); div = document.createElement("div"); div.innerHTML = "

Average Trial Execution Time (in milliseconds, with median line)

"; ind.appendChild(div); div = document.createElement("div"); dojo.style(div, "width", "600px"); dojo.style(div, "height", "250px"); ind.appendChild(div); chartsToRender.push({ div: div, title: "Average Trial Execution Time", data: tAvgArray }); } } //Lazy-render these to give the browser time and not appear locked. var delayedRenders = function() { if(chartsToRender.length){ var chartData = chartsToRender.shift(); plotResults(chartData.div, chartData.title, chartData.data); } doh.setTimeout(delayedRenders, 50); }; doh.setTimeout(delayedRenders, 150); }catch(e){ doh.debug(e); } } or.apply(doh,arguments); } })(doh._report); if(this["opera"] && opera.postError){ doh.debug = function(){ var msg = ""; for(var x=0; x
 
"; tds[3].innerHTML = ""; tb.appendChild(tg); return tg; } var addFixtureToList = function(group, fixture){ if(!testTemplate){ return; } var cgn = groupNodes[group]; if(!cgn["__items"]){ cgn.__items = []; } var tn = testTemplate.cloneNode(true); var tds = tn.getElementsByTagName("td"); tds[2].innerHTML = fixture.name; tds[3].innerHTML = ""; var nn = (cgn.__lastFixture||cgn.__groupNode).nextSibling; if(nn){ nn.parentNode.insertBefore(tn, nn); }else{ cgn.__groupNode.parentNode.appendChild(tn); } // FIXME: need to make group display toggleable!! tn.style.display = "none"; cgn.__items.push(tn); return (cgn.__lastFixture = tn); } var getFixtureNode = function(group, fixture){ if(groupNodes[group]){ return groupNodes[group][fixture.name]; } return null; } var getGroupNode = function(group){ if(groupNodes[group]){ return groupNodes[group].__groupNode; } return null; } var updateBacklog = []; doh._updateTestList = function(group, fixture, unwindingBacklog){ if(!loaded){ if(group && fixture){ updateBacklog.push([group, fixture]); } return; }else if(updateBacklog.length && !unwindingBacklog){ var tr; while((tr=updateBacklog.shift())){ doh._updateTestList(tr[0], tr[1], true); } } if(group && fixture){ if(!groupNodes[group]){ groupNodes[group] = { "__groupNode": addGroupToList(group) }; } if(!groupNodes[group][fixture.name]){ groupNodes[group][fixture.name] = addFixtureToList(group, fixture) } } } doh._testRegistered = doh._updateTestList; doh._groupStarted = function(group){ if(this._suiteCount == 0){ this._runedSuite = 0; this._currentGlobalProgressBarWidth = 0; this._suiteCount = this._testCount; } // console.debug("_groupStarted", group); if(doh._inGroup != group){ doh._groupTotalTime = 0; doh._runed = 0; doh._inGroup = group; this._runedSuite++; } var gn = getGroupNode(group); if(gn){ gn.className = "inProgress"; } } doh._groupFinished = function(group, success){ // console.debug("_groupFinished", group); var gn = getGroupNode(group); if(gn && doh._inGroup == group){ doh._totalTime += doh._groupTotalTime; gn.getElementsByTagName("td")[3].innerHTML = doh._groupTotalTime+"ms"; gn.getElementsByTagName("td")[2].lastChild.className = ""; doh._inGroup = null; //doh._runedSuite++; var failure = doh._updateGlobalProgressBar(this._runedSuite/this._groupCount,success,group); gn.className = failure ? "failure" : "success"; //doh._runedSuite--; doh._currentGlobalProgressBarWidth = parseInt(this._runedSuite/this._groupCount*10000)/100; //byId("progressOuter").style.width = parseInt(this._runedSuite/this._suiteCount*100)+"%"; } if(doh._inGroup == group){ this.debug("Total time for GROUP \"",group,"\" is ",doh._groupTotalTime,"ms"); } } doh._testStarted = function(group, fixture){ // console.debug("_testStarted", group, fixture.name); var fn = getFixtureNode(group, fixture); if(fn){ fn.className = "inProgress"; } } var _nameTimes = {}; var _playSound = function(name){ if(byId("hiddenAudio") && byId("audio") && byId("audio").checked){ // console.debug("playing:", name); var nt = _nameTimes[name]; // only play sounds once every second or so if((!nt)||(((new Date)-nt) > 700)){ _nameTimes[name] = new Date(); var tc = document.createElement("span"); byId("hiddenAudio").appendChild(tc); tc.innerHTML = ''; } } } doh._updateGlobalProgressBar = function(p,success,group){ var outerContainer=byId("progressOuter"); var gdiv=outerContainer.childNodes[doh._runedSuite-1]; if(!gdiv){ gdiv=document.createElement('div'); outerContainer.appendChild(gdiv); gdiv.className='success'; gdiv.setAttribute('_target',group); } if(!success && !gdiv._failure){ gdiv._failure=true; gdiv.className='failure'; if(group){ gdiv.setAttribute('title','failed group '+group); } } var tp=parseInt(p*10000)/100; gdiv.style.width = (tp-doh._currentGlobalProgressBarWidth)+"%"; return gdiv._failure; } doh._testFinished = function(group, fixture, success){ var fn = getFixtureNode(group, fixture); var elapsed = fixture.endTime-fixture.startTime; if(fn){ fn.getElementsByTagName("td")[3].innerHTML = elapsed+"ms"; fn.className = (success) ? "success" : "failure"; fn.getElementsByTagName("td")[2].setAttribute('_target', _loggedMsgLen); if(!success){ _playSound("doh"); var gn = getGroupNode(group); if(gn){ gn.className = "failure"; _getGroupToggler(group)(null, true); } } } if(doh._inGroup == group){ var gn = getGroupNode(group); doh._runed++; if(gn && doh._curTestCount){ var p = doh._runed/doh._curTestCount; var groupfail = this._updateGlobalProgressBar((doh._runedSuite+p-1)/doh._groupCount,success,group); var pbar = gn.getElementsByTagName("td")[2].lastChild; pbar.className = groupfail?"failure":"success"; pbar.style.width = parseInt(p*100)+"%"; gn.getElementsByTagName("td")[3].innerHTML = parseInt(p*10000)/100+"%"; } } this._groupTotalTime += elapsed; this.debug((success ? "PASSED" : "FAILED"), "test:", fixture.name, elapsed, 'ms'); } // FIXME: move implementation to _browserRunner? doh.registerUrl = function( /*String*/ group, /*String*/ url, /*Integer*/ timeout){ var tg = new String(group); this.register(group, { name: url, setUp: function(){ doh.currentGroupName = tg; doh.currentGroup = this; doh.currentUrl = url; this.d = new doh.Deferred(); doh.currentTestDeferred = this.d; doh.showTestPage(); byId("testBody").src = url; }, timeout: timeout||10000, // 10s // timeout: timeout||1000, // 10s runTest: function(){ // FIXME: implement calling into the url's groups here!! return this.d; }, tearDown: function(){ doh.currentGroupName = null; doh.currentGroup = null; doh.currentTestDeferred = null; doh.currentUrl = null; // this.d.errback(false); // byId("testBody").src = "about:blank"; doh.showLogPage(); } }); } // // Utility code for runner.html // // var isSafari = navigator.appVersion.indexOf("Safari") >= 0; var tabzidx = 1; var _showTab = function(toShow, toHide){ // FIXME: I don't like hiding things this way. var i; for(i = 0; i < toHide.length; i++){ var node = byId(toHide[i]); if(node){ node.style.display="none"; } } toShow = byId(toShow); if(toShow){ with(toShow.style){ display = ""; zIndex = ++tabzidx; } } } doh.showTestPage = function(){ _showTab("testBody", ["logBody", "perfTestsBody"]); } doh.showLogPage = function(){ _showTab("logBody", ["testBody", "perfTestsBody"]); } doh.showPerfTestsPage = function(){ _showTab("perfTestsBody", ["testBody", "logBody"]); } var runAll = true; doh.toggleRunAll = function(){ // would be easier w/ query...sigh runAll = !runAll; if(!byId("testList")){ return; } var tb = byId("testList").tBodies[0]; var inputs = tb.getElementsByTagName("input"); var x=0; var tn; while((tn=inputs[x++])){ tn.checked = runAll; doh._groups[tn.group].skip = (!runAll); } } var listHeightTimer = null; var setListHeight = function(){ if(listHeightTimer){ clearTimeout(listHeightTimer); } var tl = byId("testList"); if(!tl){ return; } listHeightTimer = doh.setTimeout(function(){ tl.style.display = "none"; tl.style.display = ""; }, 10); } _addOnEvt("resize", setListHeight); _addOnEvt("load", setListHeight); _addOnEvt("load", function(){ if(loaded){ return; } loaded = true; groupTemplate = byId("groupTemplate"); if(!groupTemplate){ // make sure we've got an ammenable DOM structure return; } groupTemplate.parentNode.removeChild(groupTemplate); groupTemplate.style.display = ""; testTemplate = byId("testTemplate"); testTemplate.parentNode.removeChild(testTemplate); testTemplate.style.display = ""; doh._updateTestList(); }); _addOnEvt("load", function(){ // let robot code run if it gets to this first var __onEnd = doh._onEnd; doh._onEnd = function(){ __onEnd.apply(doh, arguments); if(doh._failureCount == 0){ doh.debug("WOOHOO!!"); _playSound("woohoo"); }else{ console.debug("doh._failureCount:", doh._failureCount); } if(byId("play")){ toggleRunning(); } } if(!byId("play")){ // make sure we've got an amenable DOM structure return; } var isRunning = false; var toggleRunning = function(){ // ugg, this would be so much better w/ dojo.query() if(isRunning){ byId("play").style.display = byId("pausedMsg").style.display = ""; byId("playingMsg").style.display = byId("pause").style.display = "none"; isRunning = false; }else{ byId("play").style.display = byId("pausedMsg").style.display = "none"; byId("playingMsg").style.display = byId("pause").style.display = ""; isRunning = true; } } doh.run = (function(oldRun){ return function(){ if(!doh._currentGroup){ toggleRunning(); } return oldRun.apply(doh, arguments); } })(doh.run); var btns = byId("toggleButtons").getElementsByTagName("span"); var node; var idx=0; while((node=btns[idx++])){ node.onclick = toggleRunning; } //Performance report generating functions! doh._dojoPlotPerfResults = function(div, name, dataArray) { var median = doh.median(dataArray); var medarray = []; var i; for(i = 0; i < dataArray.length; i++){ medarray.push(median); } var data = { label: "name", items: [ {name: name, trials: dataArray}, {name: "Median", trials: medarray} ] }; var ifs = new dojo.data.ItemFileReadStore({data: data}); var min = Math.floor(doh.min(dataArray)); var max = Math.ceil(doh.max(dataArray)); var step = (max - min)/10; //Lets try to pad out the bottom and top a bit //Then recalc the step. if(min > 0){ min = min - step; if(min < 0){ min = 0; } min = Math.floor(min); } if(max > 0){ max = max + step; max = Math.ceil(max); } step = (max - min)/10; var chart = new dojox.charting.DataChart(div, { type: dojox.charting.plot2d.Lines, displayRange:dataArray.length, xaxis: {min: 1, max: dataArray.length, majorTickStep: Math.ceil((dataArray.length - 1)/10), htmlLabels: false}, yaxis: {min: min, max: max, majorTickStep: step, vertical: true, htmlLabels: false} }); chart.setStore(ifs, {name:"*"}, "trials"); }; doh._asciiPlotPerfResults = function(){ //TODO: Implement! }; } ); }else{ // we're in an iframe environment. Time to mix it up a bit. _doh = window.parent.doh; var _thisGroup = _doh.currentGroupName; var _thisUrl = _doh.currentUrl; if(_thisGroup){ doh._testRegistered = function(group, tObj){ _doh._updateTestList(_thisGroup, tObj); } doh._onEnd = function(){ _doh._errorCount += doh._errorCount; _doh._failureCount += doh._failureCount; _doh._testCount += doh._testCount; // should we be really adding raw group counts? //_doh._groupCount += doh._groupCount; _doh.currentTestDeferred.callback(true); } var otr = doh._getTestObj; doh._getTestObj = function(){ var tObj = otr.apply(doh, arguments); tObj.name = _thisUrl+"::"+arguments[0]+"::"+tObj.name; return tObj; } doh.debug = doh.hitch(_doh, "debug"); doh.registerUrl = doh.hitch(_doh, "registerUrl"); doh._testStarted = function(group, fixture){ _doh._testStarted(_thisGroup, fixture); } doh._testFinished = function(g, f, s){ _doh._testFinished(_thisGroup, f, s); //Okay, there may be performance info we need to filter back //to the parent, so do that here. if(doh.perfTestResults){ try{ gName = g.toString(); var localFName = f.name; while(localFName.indexOf("::") >= 0){ localFName = localFName.substring(localFName.indexOf("::") + 2, localFName.length); } if(!_doh.perfTestResults){ _doh.perfTestResults = {}; } if(!_doh.perfTestResults[gName]){ _doh.perfTestResults[gName] = {}; } _doh.perfTestResults[gName][f.name] = doh.perfTestResults[gName][localFName]; }catch (e){ doh.debug(e); } } } doh._groupStarted = function(g){ if(!this._setParent){ _doh._curTestCount = this._testCount; _doh._curGroupCount = this._groupCount; this._setParent = true; } } doh._report = function(){ }; } } })(); ================================================ FILE: tests/doh/_nodeRunner.js ================================================ /*global doh: false, process: false */ var aps = Array.prototype.slice; doh.debug = function () { //Could have multiple args, join them all together. var msg = aps.call(arguments, 0).join(' '); console.log(msg); }; // Override the doh._report method to make it quit with an // appropriate exit code in case of test failures. var oldReport = doh._report; doh._report = function () { oldReport.apply(doh, arguments); if (this._failureCount > 0 || this._errorCount > 0) { process.exit(1); } }; ================================================ FILE: tests/doh/_rhinoRunner.js ================================================ if(this["dojo"]){ dojo.provide("doh._rhinoRunner"); } doh.debug = print; // Override the doh._report method to make it quit with an // appropriate exit code in case of test failures. (function(){ var oldReport = doh._report; doh._report = function(){ oldReport.apply(doh, arguments); if(this._failureCount > 0 || this._errorCount > 0){ quit(1); } } })(); ================================================ FILE: tests/doh/_sounds/LICENSE ================================================ License Disclaimer: All contents of this directory are Copyright (c) the Dojo Foundation, with the following exceptions: ------------------------------------------------------------------------------- woohoo.wav, doh.wav, dohaaa.wav: * Copyright original authors. Copied from: http://simpson-homer.com/homer-simpson-soundboard.html ================================================ FILE: tests/doh/runner.html ================================================ alameda Tests Via The Dojo Unit Test Harness, $Rev: 20149 $

alameda Tests Via D.O.H.: The Dojo Objective Harness

Stopped
  test time

							
================================================ FILE: tests/doh/runner.js ================================================ // package system gunk. //try{ // dojo.provide("doh.runner"); //}catch(e){ if(!this["doh"]){ doh = {}; } //} // // Utility Functions and Classes // doh.selfTest = false; doh.global = this; doh.hitch = function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){ var args = []; for(var x=2; x= 0)) { this._fire(); } }, _continue: function(res){ this._resback(res); this._unpause(); }, _resback: function(res){ this.fired = ((res instanceof Error) ? 1 : 0); this.results[this.fired] = res; this._fire(); }, _check: function(){ if(this.fired != -1){ if(!this.silentlyCancelled){ throw new Error("already called!"); } this.silentlyCancelled = false; return; } }, callback: function(res){ this._check(); this._resback(res); }, errback: function(res){ this._check(); if(!(res instanceof Error)){ res = new Error(res); } this._resback(res); }, addBoth: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ enclosed = doh.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(enclosed, enclosed); }, addCallback: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ enclosed = doh.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(enclosed, null); }, addErrback: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ enclosed = doh.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(null, enclosed); }, addCallbacks: function(cb, eb){ this.chain.push([cb, eb]); if(this.fired >= 0){ this._fire(); } return this; }, _fire: function(){ var chain = this.chain; var fired = this.fired; var res = this.results[fired]; var self = this; var cb = null; while(chain.length > 0 && this.paused == 0){ // Array var pair = chain.shift(); var f = pair[fired]; if(f == null){ continue; } try { res = f(res); fired = ((res instanceof Error) ? 1 : 0); if(res instanceof doh.Deferred){ cb = function(res){ self._continue(res); }; this._pause(); } }catch(err){ fired = 1; res = err; } } this.fired = fired; this.results[fired] = res; if((cb)&&(this.paused)){ res.addBoth(cb); } } }); // // State Keeping and Reporting // doh._testCount = 0; doh._groupCount = 0; doh._errorCount = 0; doh._failureCount = 0; doh._currentGroup = null; doh._currentTest = null; doh._paused = true; doh._init = function(){ this._currentGroup = null; this._currentTest = null; this._errorCount = 0; this._failureCount = 0; this.debug(this._testCount, "tests to run in", this._groupCount, "groups"); } // doh._urls = []; doh._groups = {}; // // Test Registration // doh.registerTestNs = function(/*String*/ group, /*Object*/ ns){ // summary: // adds the passed namespace object to the list of objects to be // searched for test groups. Only "public" functions (not prefixed // with "_") will be added as tests to be run. If you'd like to use // fixtures (setUp(), tearDown(), and runTest()), please use // registerTest() or registerTests(). for(var x in ns){ if( (x.charAt(0) != "_") && (typeof ns[x] == "function") ){ this.registerTest(group, ns[x]); } } } doh._testRegistered = function(group, fixture){ // slot to be filled in } doh._groupStarted = function(group){ // slot to be filled in } doh._groupFinished = function(group, success){ // slot to be filled in } doh._testStarted = function(group, fixture){ // slot to be filled in } doh._testFinished = function(group, fixture, success){ // slot to be filled in } doh.registerGroup = function( /*String*/ group, /*Array||Function||Object*/ tests, /*Function*/ setUp, /*Function*/ tearDown, /*String*/ type){ // summary: // registers an entire group of tests at once and provides a setUp and // tearDown facility for groups. If you call this method with only // setUp and tearDown parameters, they will replace previously // installed setUp or tearDown functions for the group with the new // methods. // group: // string name of the group // tests: // either a function or an object or an array of functions/objects. If // an object, it must contain at *least* a "runTest" method, and may // also contain "setUp" and "tearDown" methods. These will be invoked // on either side of the "runTest" method (respectively) when the test // is run. If an array, it must contain objects matching the above // description or test functions. // setUp: a function for initializing the test group // tearDown: a function for initializing the test group // type: The type of tests these are, such as a group of performance tests // null/undefied are standard DOH tests, the valye 'perf' enables // registering them as performance tests. if(tests){ this.register(group, tests, type); } if(setUp){ this._groups[group].setUp = setUp; } if(tearDown){ this._groups[group].tearDown = tearDown; } } doh._getTestObj = function(group, test, type){ var tObj = test; if(typeof test == "string"){ if(test.substr(0, 4)=="url:"){ return this.registerUrl(group, test); }else{ tObj = { name: test.replace("/\s/g", "_") // FIXME: bad escapement }; tObj.runTest = new Function("t", test); } }else if(typeof test == "function"){ // if we didn't get a fixture, wrap the function tObj = { "runTest": test }; if(test["name"]){ tObj.name = test.name; }else{ try{ var fStr = "function "; var ts = tObj.runTest+""; if(0 <= ts.indexOf(fStr)){ tObj.name = ts.split(fStr)[1].split("(", 1)[0]; } // doh.debug(tObj.runTest.toSource()); }catch(e){ } } // FIXME: try harder to get the test name here } //Augment the test with some specific options to make it identifiable as a //particular type of test so it can be executed properly. if(type === "perf" || tObj.testType === "perf"){ tObj.testType = "perf"; //Build an object on the root DOH class to contain all the test results. //Cache it on the test object for quick lookup later for results storage. if(!doh.perfTestResults){ doh.perfTestResults = {}; doh.perfTestResults[group] = {}; } if(!doh.perfTestResults[group]){ doh.perfTestResults[group] = {}; } if(!doh.perfTestResults[group][tObj.name]){ doh.perfTestResults[group][tObj.name] = {}; } tObj.results = doh.perfTestResults[group][tObj.name]; //If it's not set, then set the trial duration //default to 100ms. if(!("trialDuration" in tObj)){ tObj.trialDuration = 100; } //If it's not set, then set the delay between trial runs to 100ms //default to 100ms to allow for GC and to make IE happy. if(!("trialDelay" in tObj)){ tObj.trialDelay = 100; } //If it's not set, then set number of times a trial is run to 10. if(!("trialIterations" in tObj)){ tObj.trialIterations = 10; } } return tObj; } doh.registerTest = function(/*String*/ group, /*Function||Object*/ test, /*String*/ type){ // summary: // add the provided test function or fixture object to the specified // test group. // group: // string name of the group to add the test to // test: // either a function or an object. If an object, it must contain at // *least* a "runTest" method, and may also contain "setUp" and // "tearDown" methods. These will be invoked on either side of the // "runTest" method (respectively) when the test is run. // type: // An identifier denoting the type of testing that the test performs, such // as a performance test. If null, defaults to regular DOH test. if(!this._groups[group]){ this._groupCount++; this._groups[group] = []; this._groups[group].inFlight = 0; } var tObj = this._getTestObj(group, test, type); if(!tObj){ return null; } this._groups[group].push(tObj); this._testCount++; this._testRegistered(group, tObj); return tObj; } doh.registerTests = function(/*String*/ group, /*Array*/ testArr, /*String*/ type){ // summary: // registers a group of tests, treating each element of testArr as // though it were being (along with group) passed to the registerTest // method. It also uses the type to decide how the tests should // behave, by defining the type of tests these are, such as performance tests for(var x=0; x 1) ? "s" : "")+" to run"); } doh._handleFailure = function(groupName, fixture, e){ // this.debug("FAILED test:", fixture.name); // mostly borrowed from JUM this._groups[groupName].failures++; var out = ""; if(e instanceof this._AssertFailure){ this._failureCount++; if(e["fileName"]){ out += e.fileName + ':'; } if(e["lineNumber"]){ out += e.lineNumber + ' '; } out += e+": "+e.message; this.debug("\t_AssertFailure:", out); }else{ this._errorCount++; } this.debug(e); if(fixture.runTest["toSource"]){ var ss = fixture.runTest.toSource(); this.debug("\tERROR IN:\n\t\t", ss); }else{ this.debug("\tERROR IN:\n\t\t", fixture.runTest); } if(e.rhinoException){ e.rhinoException.printStackTrace(); }else if(e.javaException){ e.javaException.printStackTrace(); } } //Assume a setTimeout implementation that is synchronous, so that //the Node and Rhino envs work similar to each other. Node defines //a setTimeout, so testing for setTimeout is not enough, each environment //adapter should set this value accordingly. doh.setTimeout = function(func){ return func(); }; doh._runPerfFixture = function(/*String*/groupName, /*Object*/fixture){ // summary: // This function handles how to execute a 'performance' test // which is different from a straight UT style test. These // will often do numerous iterations of the same operation and // gather execution statistics about it, like max, min, average, // etc. It makes use of the already in place DOH deferred test // handling since it is a good idea to put a pause inbetween each // iteration to allow for GC cleanup and the like. // // groupName: // The test group that contains this performance test. // fixture: // The performance test fixture. var tg = this._groups[groupName]; fixture.startTime = new Date(); //Perf tests always need to act in an async manner as there is a //number of iterations to flow through. var def = new doh.Deferred(); tg.inFlight++; def.groupName = groupName; def.fixture = fixture; def.addErrback(function(err){ doh._handleFailure(groupName, fixture, err); }); //Set up the finalizer. var retEnd = function(){ if(fixture["tearDown"]){ fixture.tearDown(doh); } tg.inFlight--; if((!tg.inFlight)&&(tg.iterated)){ doh._groupFinished(groupName, !tg.failures); } doh._testFinished(groupName, fixture, def.results[0]); if(doh._paused){ doh.run(); } }; //Since these can take who knows how long, we don't want to timeout //unless explicitly set var timer; var to = fixture.timeout; if(to > 0) { timer = doh.setTimeout(function(){ // ret.cancel(); // retEnd(); def.errback(new Error("test timeout in "+fixture.name.toString())); }, to); } //Set up the end calls to the test into the deferred we'll return. def.addBoth(function(arg){ if(timer){ clearTimeout(timer); } retEnd(); }); //Okay, now set up the timing loop for the actual test. //This is down as an async type test where there is a delay //between each execution to allow for GC time, etc, so the GC //has less impact on the tests. var res = fixture.results; res.trials = []; //Try to figure out how many calls are needed to hit a particular threshold. var itrDef = doh._calcTrialIterations(groupName, fixture); itrDef.addErrback(function(err){ fixture.endTime = new Date(); def.errback(err); }); //Blah, since tests can be deferred, the actual run has to be deferred until after //we know how many iterations to run. This is just plain ugly. itrDef.addCallback(function(iterations){ if(iterations){ var countdown = fixture.trialIterations; doh.debug("TIMING TEST: [" + fixture.name + "]\n\t\tITERATIONS PER TRIAL: " + iterations + "\n\tTRIALS: " + countdown); //Figure out how many times we want to run our 'trial'. //Where each trial consists of 'iterations' of the test. var trialRunner = function() { //Set up our function to execute a block of tests var start = new Date(); var tTimer = new doh.Deferred(); var tCountdown = iterations; var tState = { countdown: iterations }; var testRunner = function(state){ while(state){ try{ state.countdown--; if(state.countdown){ var ret = fixture.runTest(doh); if(ret instanceof doh.Deferred){ //Deferreds have to be handled async, //otherwise we just keep looping. var atState = { countdown: state.countdown }; ret.addCallback(function(){ testRunner(atState); }); ret.addErrback(function(err) { doh._handleFailure(groupName, fixture, err); fixture.endTime = new Date(); def.errback(err); }); state = null; } }else{ tTimer.callback(new Date()); state = null; } }catch(err){ fixture.endTime = new Date(); tTimer.errback(err); } } }; tTimer.addCallback(function(end){ //Figure out the results and try to factor out function call costs. var tResults = { trial: (fixture.trialIterations - countdown), testIterations: iterations, executionTime: (end.getTime() - start.getTime()), average: (end.getTime() - start.getTime())/iterations }; res.trials.push(tResults); doh.debug("\n\t\tTRIAL #: " + tResults.trial + "\n\tTIME: " + tResults.executionTime + "ms.\n\tAVG TEST TIME: " + (tResults.executionTime/tResults.testIterations) + "ms."); //Okay, have we run all the trials yet? countdown--; if(countdown){ doh.setTimeout(trialRunner, fixture.trialDelay); }else{ //Okay, we're done, lets compute some final performance results. var t = res.trials; //We're done. fixture.endTime = new Date(); def.callback(true); } }); tTimer.addErrback(function(err){ fixture.endTime = new Date(); def.errback(err); }); testRunner(tState); }; trialRunner(); } }); //Set for a pause, returned the deferred. if(def.fired < 0){ doh.pause(); } return def; }; doh._calcTrialIterations = function(/*String*/ groupName, /*Object*/ fixture){ // summary: // This function determines the rough number of iterations to // use to reach a particular MS threshold. This returns a deferred // since tests can theoretically by async. Async tests aren't going to // give great perf #s, though. // The callback is passed the # of iterations to hit the requested // threshold. // // fixture: // The test fixture we want to calculate iterations for. var def = new doh.Deferred(); var calibrate = function () { var testFunc = fixture.runTest; //Set the initial state. We have to do this as a loop instead //of a recursive function. Otherwise, it blows the call stack //on some browsers. var iState = { start: new Date(), curIter: 0, iterations: 5 }; var handleIteration = function(state){ while(state){ if(state.curIter < state.iterations){ try{ var ret = testFunc(doh); if(ret instanceof doh.Deferred){ var aState = { start: state.start, curIter: state.curIter + 1, iterations: state.iterations }; ret.addCallback(function(){ handleIteration(aState); }); ret.addErrback(function(err) { fixture.endTime = new Date(); def.errback(err); }); state = null; }else{ state.curIter++; } }catch(err){ fixture.endTime = new Date(); def.errback(err); return; } }else{ var end = new Date(); var totalTime = (end.getTime() - state.start.getTime()); if(totalTime < fixture.trialDuration){ var nState = { iterations: state.iterations * 2, curIter: 0 } state = null; doh.setTimeout(function(){ nState.start = new Date(); handleIteration(nState); }, 50); }else{ var itrs = state.iterations; doh.setTimeout(function(){def.callback(itrs)}, 50); state = null; } } } }; handleIteration(iState); }; doh.setTimeout(calibrate, 10); return def; }; doh._runRegFixture = function(/*String*/groupName, /*Object*/fixture){ // summary: // Function to run a generic doh test. These are not // specialized tests, like performance groups and such. // // groupName: // The groupName of the test. // fixture: // The test fixture to execute. var tg = this._groups[groupName]; fixture.startTime = new Date(); var ret = fixture.runTest(this); fixture.endTime = new Date(); // if we get a deferred back from the test runner, we know we're // gonna wait for an async result. It's up to the test code to trap // errors and give us an errback or callback. if(ret instanceof doh.Deferred){ tg.inFlight++; ret.groupName = groupName; ret.fixture = fixture; ret.addErrback(function(err){ doh._handleFailure(groupName, fixture, err); }); var retEnd = function(){ if(fixture["tearDown"]){ fixture.tearDown(doh); } tg.inFlight--; if((!tg.inFlight)&&(tg.iterated)){ doh._groupFinished(groupName, !tg.failures); } doh._testFinished(groupName, fixture, ret.results[0]); if(doh._paused){ doh.run(); } } var timer = doh.setTimeout(function(){ // ret.cancel(); // retEnd(); ret.errback(new Error("test timeout in "+fixture.name.toString())); }, fixture["timeout"]||1000); ret.addBoth(function(arg){ clearTimeout(timer); retEnd(); }); if(ret.fired < 0){ doh.pause(); } return ret; } }; doh._runFixture = function(groupName, fixture){ var tg = this._groups[groupName]; this._testStarted(groupName, fixture); var threw = false; var err = null; // run it, catching exceptions and reporting them try{ // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function fixture.group = tg; // only execute the parts of the fixture we've got if(fixture["setUp"]){ fixture.setUp(this); } if(fixture["runTest"]){ // should we error out of a fixture doesn't have a runTest? if(fixture.testType === "perf"){ //Always async deferred, so return it. return doh._runPerfFixture(groupName, fixture); }else{ //May or may not by async. var ret = doh._runRegFixture(groupName, fixture); if(ret){ return ret; } } } if(fixture["tearDown"]){ fixture.tearDown(this); } }catch(e){ threw = true; err = e; if(!fixture.endTime){ fixture.endTime = new Date(); } } var d = new doh.Deferred(); doh.setTimeout(this.hitch(this, function(){ if(threw){ this._handleFailure(groupName, fixture, err); } this._testFinished(groupName, fixture, !threw); if((!tg.inFlight)&&(tg.iterated)){ doh._groupFinished(groupName, !tg.failures); }else if(tg.inFlight > 0){ doh.setTimeout(this.hitch(this, function(){ doh.runGroup(groupName); // , idx); }), 100); this._paused = true; } if(doh._paused){ doh.run(); } }), 30); doh.pause(); return d; } doh._testId = 0; doh.runGroup = function(/*String*/ groupName, /*Integer*/ idx){ // summary: // runs the specified test group // the general structure of the algorithm is to run through the group's // list of doh, checking before and after each of them to see if we're in // a paused state. This can be caused by the test returning a deferred or // the user hitting the pause button. In either case, we want to halt // execution of the test until something external to us restarts it. This // means we need to pickle off enough state to pick up where we left off. // FIXME: need to make fixture execution async!! var tg = this._groups[groupName]; if(tg.skip === true){ return; } if(this._isArray(tg)){ if(idx<=tg.length){ if((!tg.inFlight)&&(tg.iterated == true)){ if(tg["tearDown"]){ tg.tearDown(this); } doh._groupFinished(groupName, !tg.failures); return; } } if(!idx){ tg.inFlight = 0; tg.iterated = false; tg.failures = 0; } doh._groupStarted(groupName); if(!idx){ this._setupGroupForRun(groupName, idx); if(tg["setUp"]){ tg.setUp(this); } } for(var y=(idx||0); y"); } */ } } }catch(e){ print("\n"+doh._line); print("The Dojo Unit Test Harness, $Rev: 20389 $"); print("Copyright (c) 2009, The Dojo Foundation, All Rights Reserved"); print(doh._line, "\n"); try{ var dojoUrl = "../../dojo/dojo.js"; var testUrl = ""; var testModule = "dojo.tests.module"; var dohBase = ""; for(x=0; x alameda: Empty Require Test

alameda: Empty Require Test

Empty require array should still call callback. More info

Check console for messages

================================================ FILE: tests/errback/errback.html ================================================ alameda: errback Test

alameda: errback Test

Test the use of errbacks in a require call. While alameda does not support calling an errback (all modules should be built in and usable), alameda should not throw any errors if they are used.

Check console for messages

================================================ FILE: tests/hasOwnProperty/hasOwnProperty.html ================================================ alameda: hasOwnProperty Test

alameda: hasOwnProperty Test

Check console for messages

================================================ FILE: tests/index.html ================================================ alameda tests

alameda tests

  1. All Automated Tests
================================================ FILE: tests/insertRequire/insertRequire.html ================================================ alameda: insertRequire Test

alameda: insertRequire Test

Make sure alameda can handle juse a plain require(['a']) used by r.js's insertRequire build option. More info: 27.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfig.html ================================================ alameda: Map Config Test

alameda: Map Config Test

Test using the map config.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfig.js ================================================ define('c1',{ name: 'c1' }); define('c1/sub',{ name: 'c1/sub' }); define('a',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('c',{ name: 'c' }); define('c/sub',{ name: 'c/sub' }); define('b',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('c2',{ name: 'c2' }); define('c2/sub',{ name: 'c2/sub' }); define('a/sub/one',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); require({ baseUrl: './', paths: { a: 'a1' }, map: { 'a': { c: 'c1' }, 'a/sub/one': { 'c': 'c2' } } }, ['a', 'b', 'c', 'a/sub/one'], function(a, b, c, one) { doh.register( 'mapConfig', [ function mapConfig(t){ t.is('c1', a.c.name); t.is('c1/sub', a.csub.name); t.is('c2', one.c.name); t.is('c2/sub', one.csub.name); t.is('c', b.c.name); t.is('c/sub', b.csub.name); t.is('c', c.name); } ] ); doh.run(); } ); define("mapConfig-tests", function(){}); ================================================ FILE: tests/mapConfig/mapConfigPlugin.html ================================================ alameda: Map Config Plugin Built Test

alameda: Map Config Plugin Built Test

Test using the map config with plugin value after a build.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfigPlugin.js ================================================ define('plug',{ load: function (name, require, load, config) { if (!name) { name = 'main'; } else if (name.charAt(0) === '/') { name = 'main' + name; } //Only grab the first segment of the name. //This is just to be different, nothing //that is required behavior. name = name.split('/').shift(); name = 'plug/' + name; require([name], load); } }); define('plug/c1',{ name: 'plug!c1' }); define('a',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('plug/main',{ name: 'plug!main' }); define('b',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('plug/c2',{ name: 'plug!c2' }); define('a/sub/one',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); require({ baseUrl: './', paths: { a: 'a1' }, map: { '*': { c: 'plug!' }, 'a': { c: 'plug!c1' }, 'a/sub/one': { 'c': 'plug!c2' } } }, ['a', 'b', 'c', 'a/sub/one'], function(a, b, c, one) { doh.register( 'mapConfigPlugin', [ function mapConfigPlugin(t){ t.is('plug!c1', a.c.name); t.is('plug!c1', a.csub.name); t.is('plug!c2', one.c.name); t.is('plug!c2', one.csub.name); t.is('plug!main', b.c.name); t.is('plug!main', b.csub.name); t.is('plug!main', c.name); } ] ); doh.run(); } ); define("mapConfigPlugin-tests", function(){}); ================================================ FILE: tests/mapConfig/mapConfigSpecificity.html ================================================ alameda: Map Config Specificity Test

alameda: Map Config Specificity Test

Test map config specificity. More info.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfigSpecificity.js ================================================ /*jslint sloppy: true */ /*global define, require, doh */ define('foo-1.0/bar/baz', [], function () { return '1.0'; }); define('foo-1.2/bar/baz', [], function () { return '1.2'; }); define('oldmodule', ['foo/bar/baz'], function (baz) { return { name: 'oldmodule', baz: baz }; }); require({ baseUrl: './', map: { 'oldmodule': { //This one should be favored over the * value. 'foo' : 'foo-1.0' }, '*': { 'foo/bar' : 'foo-1.2/bar' } } }, ['oldmodule'], function (oldmodule) { doh.register( 'mapConfigSpecificity', [ function mapConfigSpecificity(t) { t.is('oldmodule', oldmodule.name); t.is('1.0', oldmodule.baz); } ] ); doh.run(); }); ================================================ FILE: tests/mapConfig/mapConfigStar.html ================================================ alameda: Map Config Star Test

alameda: Map Config Star Test

Test using '*' in the map config.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfigStar.js ================================================ define('c1',{ name: 'c1' }); define('c1/sub',{ name: 'c1/sub' }); define('a',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('another/minor',{ name: 'another/minor' }); define('another/c',['./minor'], function (minor) { return { name: 'another/c', minorName: minor.name }; }); define('another/c/dim',{ name: 'another/c/dim' }); define('another/c/sub',['./dim'], function (dim) { return { name: 'another/c/sub', dimName: dim.name }; }); define('b',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); define('c2',{ name: 'c2' }); define('a/sub/one',['c', 'c/sub'], function (c, csub) { return { c: c, csub: csub }; }); require({ baseUrl: './', paths: { a: 'a1' }, map: { '*': { 'c': 'another/c' }, 'a': { c: 'c1' }, 'a/sub/one': { 'c': 'c2', 'c/sub': 'another/c/sub' } } }, ['a', 'b', 'c', 'a/sub/one'], function(a, b, c, one) { doh.register( 'mapConfigStar', [ function mapConfigStar(t){ t.is('c1', a.c.name); t.is('c1/sub', a.csub.name); t.is('c2', one.c.name); t.is('another/c/sub', one.csub.name); t.is('another/c/dim', one.csub.dimName); t.is('another/c', b.c.name); t.is('another/minor', b.c.minorName); t.is('another/c/sub', b.csub.name); t.is('another/c', c.name); t.is('another/minor', c.minorName); } ] ); doh.run(); } ); define("mapConfigStar-tests", function(){}); ================================================ FILE: tests/mapConfig/mapConfigStarAdapter.html ================================================ alameda: Map Config Star Adapter Built Test

alameda: Map Config Star Adapter Built Test

Test using '*' with an adapter in the built map config.

Check console for messages

================================================ FILE: tests/mapConfig/mapConfigStarAdapter.js ================================================ define('d',{ name: 'd' }); define('adapter/d',['d'], function(d) { d.adapted = true; return d; }); define('e',['d'], function (d) { return { name: 'e', d: d }; }); /*global doh */ require({ baseUrl: './', map: { '*': { 'd': 'adapter/d' }, 'adapter/d': { d: 'd' } } }, ['e', 'adapter/d'], function(e, adapterD) { doh.register( 'mapConfigStarAdapter', [ function mapConfigStarAdapter(t){ t.is('e', e.name); t.is('d', e.d.name); t.is(true, e.d.adapted); t.is(true, adapterD.adapted); t.is('d', adapterD.name); } ] ); doh.run(); } ); define("mapConfigStarAdapter-tests", function(){}); ================================================ FILE: tests/moduleConfig/moduleConfig.html ================================================ alameda: moduleConfig Test

alameda: moduleConfig Test

Check console for messages

================================================ FILE: tests/moduleConfig/moduleConfig.js ================================================ define('foo', function (require, exports, module) { return { locale: module.config().locale }; }); define('bar', ['module'], function (module) { return { color: module.config().color }; }); define('baz', ['module'], function (module) { return { doesNotExist: module.config().doesNotExist }; }); ================================================ FILE: tests/onNodeCreated/a.js ================================================ define(['b'], function (b) { return { name: 'a', b: b }; }); ================================================ FILE: tests/onNodeCreated/b.js ================================================ define({ name: 'b' }); ================================================ FILE: tests/onNodeCreated/onNodeCreated.html ================================================ alameda: Simple Test

alameda: onNodeCreated Test

Check console for messages

================================================ FILE: tests/plugins/coffee.html ================================================ alameda: Coffee Test

alameda: Coffee Test

Check console for messages

================================================ FILE: tests/plugins/coffee.js ================================================ /** * @license cs 0.2.1 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/require-cs for details * * CoffeeScript is Copyright (c) 2011 Jeremy Ashkenas * http://jashkenas.github.com/coffee-script/ * CoffeeScriptVersion: '1.1.1' */ /* Yes, deliciously evil. */ /*jslint evil: true, strict: false, plusplus: false, regexp: false */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, process: false, window: false */ (function () { define('cs',{ version: '0.2.1', load: function (name, parentRequire, load, config) { } }); }()); (function() { define('cs!controller',{ attach: function(view) { //return require.ready(function() { return view.render(); //}); } }); }).call(this); (function() { define('cs!util',{ toDom: function(text) { return 'dom:' + text; } }); }).call(this); (function() { define('cs!view',['cs!util'], function(util) { return { render: function(body) { return util.toDom('This is a rendered view'); } }; }); }).call(this); (function() { define('cs!csmain',['cs!controller', 'cs!view'], function(controller, view) { return controller.attach(view); }); }).call(this); require({ paths: { cs: '../../cs' } }, ['cs!csmain']); define("main", function(){}); ================================================ FILE: tests/plugins/pluginMapSameName/pluginMapSameName.html ================================================ alameda: Plugin Map Same Name Test

alameda: Plugin Map Same Name Test

Test using the map config with plugins. but include a map value that contains the original name of the plugin, to confirm the map translation is only done once: 484

Check console for messages

================================================ FILE: tests/plugins/pluginMapSameName/pluginMapSameName.js ================================================ define('plugin/plugin',{ load: function (id, require, load, config) { load(id); } }); require({ map: { '*': { 'plugin': 'plugin/plugin' } } }, ['plugin!foo'], function (value) { doh.register( 'pluginMapSameName', [ function pluginMapSameName(t){ t.is('foo', value); } ] ); doh.run(); }); define("pluginMapSameName-tests", function(){}); ================================================ FILE: tests/plugins/plugins.html ================================================ alameda: Simple Test

alameda: Simple Test

Check console for messages

================================================ FILE: tests/plugins/plugins.js ================================================ (function () { function parse(name) { var parts = name.split('?'), index = parseInt(parts[0], 10), choices = parts[1].split(':'), choice = choices[index]; return { index: index, choices: choices, choice: choice }; } define('index',{ pluginBuilder: './indexBuilder', normalize: function (name, normalize) { var parsed = parse(name), choices = parsed.choices; //Normalize each path choice. for (i = 0; i < choices.length; i++) { choices[i] = normalize(choices[i]); } return parsed.index + '?' + choices.join(':'); }, load: function (name, req, load, config) { req([parse(name).choice], function (value) { load(value); }); } }); }()); define('a',{ name: 'a' }); define('c',{ name: "c" }); define('b',[],function () { return { name: "b" }; }); define('earth',['require','./index!0?./a:./b:./c','./index!2?./a:./b:./c','./index!1?./a:./b:./c'],function (require) { return { getA: function () { return require("./index!0?./a:./b:./c"); }, getC: function () { return require("./index!2?./a:./b:./c"); }, getB: function () { return require("./index!1?./a:./b:./c"); } }; }); define('prime/a',{ name: 'aPrime' }); define('prime/c',{ name: "cPrime" }); define('prime/b',[],function () { return { name: "bPrime" }; }); define('prime/earth',['require','../index!0?./a:./b:./c','../index!2?./a:./b:./c','../index!1?./a:./b:./c'],function (require) { return { getA: function () { return require("../index!0?./a:./b:./c"); }, getC: function () { return require("../index!2?./a:./b:./c"); }, getB: function () { return require("../index!1?./a:./b:./c"); } }; }); ================================================ FILE: tests/plugins/pluginsConfig/pluginsConfig.html ================================================ alameda: Plugin Load Config Test

alameda: Plugin Load Config Test

Test passing the loader config to the .load() method on the plugin, to match the behavior of requirejs.

More info.

Check console for messages

================================================ FILE: tests/plugins/pluginsConfig/pluginsConfig.js ================================================ var expectedConfig; define('plugin/plugin',{ load: function (id, require, load, config) { expectedConfig = config; load(id); } }); require({ foo: 'bar', map: { '*': { 'plugin': 'plugin/plugin' } } }, ['plugin!foo'], function (value) { doh.register( 'pluginsConfig', [ function pluginsConfig(t){ t.is('bar', expectedConfig.foo); } ] ); doh.run(); }); ================================================ FILE: tests/plugins/text.html ================================================ alameda: Text Test

alameda: Text Test

Check console for messages

================================================ FILE: tests/plugins/text.js ================================================ /** * @license RequireJS text 0.26.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /*jslint regexp: false, nomen: false, plusplus: false, strict: false */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, window: false, process: false, Packages: false, java: false, location: false */ (function () { var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, buildMap = []; define('text',[],function () { var text, get, fs; if (typeof window !== "undefined" && window.navigator && window.document) { get = function (url, callback) { var xhr = text.createXhr(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseText); } }; xhr.send(null); }; } else if (typeof process !== "undefined" && process.versions && !!process.versions.node) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); get = function (url, callback) { callback(fs.readFileSync(url, 'utf8')); }; } else if (typeof Packages !== 'undefined') { //Why Java, why is this so awkward? get = function (url, callback) { var encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), stringBuffer, line, content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } text = { version: '0.26.0', strip: function (content) { //Strips declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, jsEscape: function (content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r"); }, createXhr: function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else { for (i = 0; i < 3; i++) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } if (!xhr) { throw new Error("createXhr(): XMLHttpRequest not available"); } return xhr; }, get: get, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var strip = false, index = name.indexOf("."), modName = name.substring(0, index), ext = name.substring(index + 1, name.length); index = ext.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = ext.substring(index + 1, ext.length); strip = strip === "strip"; ext = ext.substring(0, index); } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ canUseXhr: function (url, protocol, hostname, port) { var match = text.xdRegExp.exec(url), uProtocol, uHostName, uPort; if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName === hostname) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad, config) { content = strip ? text.strip(content) : content; if (config.isBuild && config.inlineText) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the declarations so the content can be inserted //into the current doc without problems. var parsed = text.parseName(name), nonStripName = parsed.moduleName + '.' + parsed.ext, url = req.toUrl(nonStripName); //Load the text. Use XHR if possible and in a browser. if (!hasLocation || text.canUseXhr(url)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad, config); }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad, config); }); } }, write: function (pluginName, moduleName, write, config) { if (moduleName in buildMap) { var content = text.jsEscape(buildMap[moduleName]); write("define('" + pluginName + "!" + moduleName + "', function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), nonStripName = parsed.moduleName + '.' + parsed.ext, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + '.' + parsed.ext) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. text.write(pluginName, nonStripName, function (contents) { write(fileName, contents); }, config); }, config); } }; return text; }); }()); define('text!subwidget.html!strip', function () { return '

This is a subwidget

';}); define('text!subwidget2.html', function () { return 'This! is template2';}); define("subwidget", ["text!subwidget.html!strip", "text!subwidget2.html"], function(template, template2) { return { name: "subwidget", template: template, template2: template2 }; } ); define('text!widget.html', function () { return '

This is a widget!

I am in a widget

';}); define("widget", ["subwidget", "text!widget.html"], function(subwidget, template) { return { subWidgetName: subwidget.name, subWidgetTemplate: subwidget.template, subWidgetTemplate2: subwidget.template2, template: template }; } ); ================================================ FILE: tests/preserveDeps/preserveDeps.html ================================================ alameda: preserveDeps Test

alameda: preserveDeps Test

alameda should not mutate deps passed to it. More info: 35.

Check console for messages

================================================ FILE: tests/promiseRequire/app.js ================================================ define(['bar'], function (bar) { return { name: 'app', bar: bar }; }); ================================================ FILE: tests/promiseRequire/bar.js ================================================ // bar.js define('bar', function(require) { return { name: 'bar' }; }); ================================================ FILE: tests/promiseRequire/promiseRequire.html ================================================ alameda: promise from require

alameda: promise from require

Test require([]) returning a promise. More info.

Check console for messages

================================================ FILE: tests/relativePaths/relativePaths.html ================================================ alameda: relativePaths Test

alameda: Relative Paths Test

Test relative dependency paths with alameda. More info: 28.

Check console for messages

================================================ FILE: tests/runner.js ================================================ var page = require('webpage').create(); page.onAlert = function () { if (page.evaluate(function () { return doh._doneForPhantom; })) { var problems = page.evaluate(function () { return doh._errorCount + doh._failureCount; }); phantom.exit(problems ? 1 : 0); } }; var first = true; page.onLoadFinished = function (status) { if (first) { first = false; page.evaluate(function () { var oldReport = doh._report; doh._report = function () { oldReport.apply(doh, arguments); this._doneForPhantom = true; alert(); }; doh.run(); }); } }; page.onConsoleMessage = function () { console.log.apply(console, arguments); }; page.open('http://localhost:1986/tests/doh/runner.html?testUrl=../all'); ================================================ FILE: tests/server.js ================================================ var connect = require('connect'); connect.createServer(connect.static(__dirname + '/..')).listen(1986); require('fs').writeFileSync(__dirname + '/pid.txt', process.pid); ================================================ FILE: tests/shim/shim.html ================================================ alameda: Shim Test

alameda: moduleConfig Test

Check console for messages

================================================ FILE: tests/shim/shim.js ================================================ //Taken from requirejs/tests/shim/built/basic-tests.js (function (root) { root.A = { name: 'a' }; }(this)); define("a", (function (global) { return function () { var ret = global.A.name; var fn = function () { window.globalA = this.A.name; }; fn.apply(global, arguments); return ret; }; }(this))); function D() { this.name = 'd'; }; define("d", function(){}); var B = { name: 'b', aValue: A.name, dValue: new D() }; define("b", function(){}); var C = { name: 'c', a: A, b: B }; define("c", ["a","b"], (function (global) { return function () { var ret = global.C; return ret; }; }(this))); var e = { nested: { e: { name: 'e' } } }; define("e", (function (global) { return function () { var ret = global.e.nested.e; return ret; }; }(this))); ================================================ FILE: tests/simple.html ================================================ alameda: Simple Test

alameda: Simple Test

Check console for messages

================================================ FILE: tests/simple.js ================================================ define('foo', { name: 'foo' }); define('bar', [], function() { return { name: 'bar' } }); define('baz', ['require', 'exports', 'module', './bar'], function (require, exports, module) { var bar = require('./bar'); exports.name = 'baz'; exports.barName = bar.name; exports.callIt = function (callback) { require(['./bar'], function (bar) { callback(bar); }); } }); ================================================ FILE: tests/specialDeps/specialDeps-tests.js ================================================ define('foo', function(require, exports, module) { require('exports').name = 'foo'; require('require')('exports').related = require('module').config().related; require('require')('exports').uri = module.uri; }); require.config({ config: { foo: { related: 'bar' } } }); require(["foo"], function (foo) { doh.register( "specialDeps", [ function specialDeps(t) { t.is("foo", foo.name); t.is("bar", foo.related); t.is("./foo.js", foo.uri); } ] ); doh.run(); }); ================================================ FILE: tests/specialDeps/specialDeps.html ================================================ alameda: Special Dependencies Test

alameda: Special Dependencies Test

Tests for require("require"|"exports"|"module") inside a module. More info.

Check console for messages

================================================ FILE: tests/timeoutErrors/timeoutErrors.html ================================================ alameda: Errors Test

alameda: Errors Test

Tests that timeouts trigger errbacks if appropriate, require.onError if no errback is provided.

Check console for messages