require.js 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  1. /** vim: et:ts=4:sw=4:sts=4
  2. * @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/requirejs for details
  5. */
  6. //Not using strict: uneven strict support in browsers, #392, and causes
  7. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  8. /*jslint regexp: true, nomen: true, sloppy: true */
  9. /*global window, navigator, document, importScripts, setTimeout, opera */
  10. var requirejs, require, define;
  11. (function (global) {
  12. var req, s, head, baseElement, dataMain, src,
  13. interactiveScript, currentlyAddingScript, mainScript, subPath,
  14. version = '2.1.5',
  15. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  16. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  17. jsSuffixRegExp = /\.js$/,
  18. currDirRegExp = /^\.\//,
  19. op = Object.prototype,
  20. ostring = op.toString,
  21. hasOwn = op.hasOwnProperty,
  22. ap = Array.prototype,
  23. apsp = ap.splice,
  24. isBrowser = !!(typeof window !== 'undefined' && navigator && document),
  25. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  26. //PS3 indicates loaded and complete, but need to wait for complete
  27. //specifically. Sequence is 'loading', 'loaded', execution,
  28. // then 'complete'. The UA check is unfortunate, but not sure how
  29. //to feature test w/o causing perf issues.
  30. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  31. /^complete$/ : /^(complete|loaded)$/,
  32. defContextName = '_',
  33. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  34. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  35. contexts = {},
  36. cfg = {},
  37. globalDefQueue = [],
  38. useInteractive = false;
  39. function isFunction(it) {
  40. return ostring.call(it) === '[object Function]';
  41. }
  42. function isArray(it) {
  43. return ostring.call(it) === '[object Array]';
  44. }
  45. /**
  46. * Helper function for iterating over an array. If the func returns
  47. * a true value, it will break out of the loop.
  48. */
  49. function each(ary, func) {
  50. if (ary) {
  51. var i;
  52. for (i = 0; i < ary.length; i += 1) {
  53. if (ary[i] && func(ary[i], i, ary)) {
  54. break;
  55. }
  56. }
  57. }
  58. }
  59. /**
  60. * Helper function for iterating over an array backwards. If the func
  61. * returns a true value, it will break out of the loop.
  62. */
  63. function eachReverse(ary, func) {
  64. if (ary) {
  65. var i;
  66. for (i = ary.length - 1; i > -1; i -= 1) {
  67. if (ary[i] && func(ary[i], i, ary)) {
  68. break;
  69. }
  70. }
  71. }
  72. }
  73. function hasProp(obj, prop) {
  74. return hasOwn.call(obj, prop);
  75. }
  76. function getOwn(obj, prop) {
  77. return hasProp(obj, prop) && obj[prop];
  78. }
  79. /**
  80. * Cycles over properties in an object and calls a function for each
  81. * property value. If the function returns a truthy value, then the
  82. * iteration is stopped.
  83. */
  84. function eachProp(obj, func) {
  85. var prop;
  86. for (prop in obj) {
  87. if (hasProp(obj, prop)) {
  88. if (func(obj[prop], prop)) {
  89. break;
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. * Simple function to mix in properties from source into target,
  96. * but only if target does not already have a property of the same name.
  97. */
  98. function mixin(target, source, force, deepStringMixin) {
  99. if (source) {
  100. eachProp(source, function (value, prop) {
  101. if (force || !hasProp(target, prop)) {
  102. if (deepStringMixin && typeof value !== 'string') {
  103. if (!target[prop]) {
  104. target[prop] = {};
  105. }
  106. mixin(target[prop], value, force, deepStringMixin);
  107. } else {
  108. target[prop] = value;
  109. }
  110. }
  111. });
  112. }
  113. return target;
  114. }
  115. //Similar to Function.prototype.bind, but the 'this' object is specified
  116. //first, since it is easier to read/figure out what 'this' will be.
  117. function bind(obj, fn) {
  118. return function () {
  119. return fn.apply(obj, arguments);
  120. };
  121. }
  122. function scripts() {
  123. return document.getElementsByTagName('script');
  124. }
  125. //Allow getting a global that expressed in
  126. //dot notation, like 'a.b.c'.
  127. function getGlobal(value) {
  128. if (!value) {
  129. return value;
  130. }
  131. var g = global;
  132. each(value.split('.'), function (part) {
  133. g = g[part];
  134. });
  135. return g;
  136. }
  137. /**
  138. * Constructs an error with a pointer to an URL with more information.
  139. * @param {String} id the error ID that maps to an ID on a web page.
  140. * @param {String} message human readable error.
  141. * @param {Error} [err] the original error, if there is one.
  142. *
  143. * @returns {Error}
  144. */
  145. function makeError(id, msg, err, requireModules) {
  146. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  147. e.requireType = id;
  148. e.requireModules = requireModules;
  149. if (err) {
  150. e.originalError = err;
  151. }
  152. return e;
  153. }
  154. if (typeof define !== 'undefined') {
  155. //If a define is already in play via another AMD loader,
  156. //do not overwrite.
  157. return;
  158. }
  159. if (typeof requirejs !== 'undefined') {
  160. if (isFunction(requirejs)) {
  161. //Do not overwrite and existing requirejs instance.
  162. return;
  163. }
  164. cfg = requirejs;
  165. requirejs = undefined;
  166. }
  167. //Allow for a require config object
  168. if (typeof require !== 'undefined' && !isFunction(require)) {
  169. //assume it is a config object.
  170. cfg = require;
  171. require = undefined;
  172. }
  173. function newContext(contextName) {
  174. var inCheckLoaded, Module, context, handlers,
  175. checkLoadedTimeoutId,
  176. config = {
  177. //Defaults. Do not set a default for map
  178. //config to speed up normalize(), which
  179. //will run faster if there is no default.
  180. waitSeconds: 7,
  181. baseUrl: './',
  182. paths: {},
  183. pkgs: {},
  184. shim: {},
  185. config: {}
  186. },
  187. registry = {},
  188. //registry of just enabled modules, to speed
  189. //cycle breaking code when lots of modules
  190. //are registered, but not activated.
  191. enabledRegistry = {},
  192. undefEvents = {},
  193. defQueue = [],
  194. defined = {},
  195. urlFetched = {},
  196. requireCounter = 1,
  197. unnormalizedCounter = 1;
  198. /**
  199. * Trims the . and .. from an array of path segments.
  200. * It will keep a leading path segment if a .. will become
  201. * the first path segment, to help with module name lookups,
  202. * which act like paths, but can be remapped. But the end result,
  203. * all paths that use this function should look normalized.
  204. * NOTE: this method MODIFIES the input array.
  205. * @param {Array} ary the array of path segments.
  206. */
  207. function trimDots(ary) {
  208. var i, part;
  209. for (i = 0; ary[i]; i += 1) {
  210. part = ary[i];
  211. if (part === '.') {
  212. ary.splice(i, 1);
  213. i -= 1;
  214. } else if (part === '..') {
  215. if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
  216. //End of the line. Keep at least one non-dot
  217. //path segment at the front so it can be mapped
  218. //correctly to disk. Otherwise, there is likely
  219. //no path mapping for a path starting with '..'.
  220. //This can still fail, but catches the most reasonable
  221. //uses of ..
  222. break;
  223. } else if (i > 0) {
  224. ary.splice(i - 1, 2);
  225. i -= 2;
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * Given a relative module name, like ./something, normalize it to
  232. * a real name that can be mapped to a path.
  233. * @param {String} name the relative name
  234. * @param {String} baseName a real name that the name arg is relative
  235. * to.
  236. * @param {Boolean} applyMap apply the map config to the value. Should
  237. * only be done if this normalization is for a dependency ID.
  238. * @returns {String} normalized name
  239. */
  240. function normalize(name, baseName, applyMap) {
  241. var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
  242. foundMap, foundI, foundStarMap, starI,
  243. baseParts = baseName && baseName.split('/'),
  244. normalizedBaseParts = baseParts,
  245. map = config.map,
  246. starMap = map && map['*'];
  247. //Adjust any relative paths.
  248. if (name && name.charAt(0) === '.') {
  249. //If have a base name, try to normalize against it,
  250. //otherwise, assume it is a top-level require that will
  251. //be relative to baseUrl in the end.
  252. if (baseName) {
  253. if (getOwn(config.pkgs, baseName)) {
  254. //If the baseName is a package name, then just treat it as one
  255. //name to concat the name with.
  256. normalizedBaseParts = baseParts = [baseName];
  257. } else {
  258. //Convert baseName to array, and lop off the last part,
  259. //so that . matches that 'directory' and not name of the baseName's
  260. //module. For instance, baseName of 'one/two/three', maps to
  261. //'one/two/three.js', but we want the directory, 'one/two' for
  262. //this normalization.
  263. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  264. }
  265. name = normalizedBaseParts.concat(name.split('/'));
  266. trimDots(name);
  267. //Some use of packages may use a . path to reference the
  268. //'main' module name, so normalize for that.
  269. pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
  270. name = name.join('/');
  271. if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
  272. name = pkgName;
  273. }
  274. } else if (name.indexOf('./') === 0) {
  275. // No baseName, so this is ID is resolved relative
  276. // to baseUrl, pull off the leading dot.
  277. name = name.substring(2);
  278. }
  279. }
  280. //Apply map config if available.
  281. if (applyMap && map && (baseParts || starMap)) {
  282. nameParts = name.split('/');
  283. for (i = nameParts.length; i > 0; i -= 1) {
  284. nameSegment = nameParts.slice(0, i).join('/');
  285. if (baseParts) {
  286. //Find the longest baseName segment match in the config.
  287. //So, do joins on the biggest to smallest lengths of baseParts.
  288. for (j = baseParts.length; j > 0; j -= 1) {
  289. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  290. //baseName segment has config, find if it has one for
  291. //this name.
  292. if (mapValue) {
  293. mapValue = getOwn(mapValue, nameSegment);
  294. if (mapValue) {
  295. //Match, update name to the new value.
  296. foundMap = mapValue;
  297. foundI = i;
  298. break;
  299. }
  300. }
  301. }
  302. }
  303. if (foundMap) {
  304. break;
  305. }
  306. //Check for a star map match, but just hold on to it,
  307. //if there is a shorter segment match later in a matching
  308. //config, then favor over this star map.
  309. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  310. foundStarMap = getOwn(starMap, nameSegment);
  311. starI = i;
  312. }
  313. }
  314. if (!foundMap && foundStarMap) {
  315. foundMap = foundStarMap;
  316. foundI = starI;
  317. }
  318. if (foundMap) {
  319. nameParts.splice(0, foundI, foundMap);
  320. name = nameParts.join('/');
  321. }
  322. }
  323. return name;
  324. }
  325. function removeScript(name) {
  326. if (isBrowser) {
  327. each(scripts(), function (scriptNode) {
  328. if (scriptNode.getAttribute('data-requiremodule') === name &&
  329. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  330. scriptNode.parentNode.removeChild(scriptNode);
  331. return true;
  332. }
  333. });
  334. }
  335. }
  336. function hasPathFallback(id) {
  337. var pathConfig = getOwn(config.paths, id);
  338. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  339. removeScript(id);
  340. //Pop off the first array value, since it failed, and
  341. //retry
  342. pathConfig.shift();
  343. context.require.undef(id);
  344. context.require([id]);
  345. return true;
  346. }
  347. }
  348. //Turns a plugin!resource to [plugin, resource]
  349. //with the plugin being undefined if the name
  350. //did not have a plugin prefix.
  351. function splitPrefix(name) {
  352. var prefix,
  353. index = name ? name.indexOf('!') : -1;
  354. if (index > -1) {
  355. prefix = name.substring(0, index);
  356. name = name.substring(index + 1, name.length);
  357. }
  358. return [prefix, name];
  359. }
  360. /**
  361. * Creates a module mapping that includes plugin prefix, module
  362. * name, and path. If parentModuleMap is provided it will
  363. * also normalize the name via require.normalize()
  364. *
  365. * @param {String} name the module name
  366. * @param {String} [parentModuleMap] parent module map
  367. * for the module name, used to resolve relative names.
  368. * @param {Boolean} isNormalized: is the ID already normalized.
  369. * This is true if this call is done for a define() module ID.
  370. * @param {Boolean} applyMap: apply the map config to the ID.
  371. * Should only be true if this map is for a dependency.
  372. *
  373. * @returns {Object}
  374. */
  375. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  376. var url, pluginModule, suffix, nameParts,
  377. prefix = null,
  378. parentName = parentModuleMap ? parentModuleMap.name : null,
  379. originalName = name,
  380. isDefine = true,
  381. normalizedName = '';
  382. //If no name, then it means it is a require call, generate an
  383. //internal name.
  384. if (!name) {
  385. isDefine = false;
  386. name = '_@r' + (requireCounter += 1);
  387. }
  388. nameParts = splitPrefix(name);
  389. prefix = nameParts[0];
  390. name = nameParts[1];
  391. if (prefix) {
  392. prefix = normalize(prefix, parentName, applyMap);
  393. pluginModule = getOwn(defined, prefix);
  394. }
  395. //Account for relative paths if there is a base name.
  396. if (name) {
  397. if (prefix) {
  398. if (pluginModule && pluginModule.normalize) {
  399. //Plugin is loaded, use its normalize method.
  400. normalizedName = pluginModule.normalize(name, function (name) {
  401. return normalize(name, parentName, applyMap);
  402. });
  403. } else {
  404. normalizedName = normalize(name, parentName, applyMap);
  405. }
  406. } else {
  407. //A regular module.
  408. normalizedName = normalize(name, parentName, applyMap);
  409. //Normalized name may be a plugin ID due to map config
  410. //application in normalize. The map config values must
  411. //already be normalized, so do not need to redo that part.
  412. nameParts = splitPrefix(normalizedName);
  413. prefix = nameParts[0];
  414. normalizedName = nameParts[1];
  415. isNormalized = true;
  416. url = context.nameToUrl(normalizedName);
  417. }
  418. }
  419. //If the id is a plugin id that cannot be determined if it needs
  420. //normalization, stamp it with a unique ID so two matching relative
  421. //ids that may conflict can be separate.
  422. suffix = prefix && !pluginModule && !isNormalized ?
  423. '_unnormalized' + (unnormalizedCounter += 1) :
  424. '';
  425. return {
  426. prefix: prefix,
  427. name: normalizedName,
  428. parentMap: parentModuleMap,
  429. unnormalized: !!suffix,
  430. url: url,
  431. originalName: originalName,
  432. isDefine: isDefine,
  433. id: (prefix ?
  434. prefix + '!' + normalizedName :
  435. normalizedName) + suffix
  436. };
  437. }
  438. function getModule(depMap) {
  439. var id = depMap.id,
  440. mod = getOwn(registry, id);
  441. if (!mod) {
  442. mod = registry[id] = new context.Module(depMap);
  443. }
  444. return mod;
  445. }
  446. function on(depMap, name, fn) {
  447. var id = depMap.id,
  448. mod = getOwn(registry, id);
  449. if (hasProp(defined, id) &&
  450. (!mod || mod.defineEmitComplete)) {
  451. if (name === 'defined') {
  452. fn(defined[id]);
  453. }
  454. } else {
  455. getModule(depMap).on(name, fn);
  456. }
  457. }
  458. function onError(err, errback) {
  459. var ids = err.requireModules,
  460. notified = false;
  461. if (errback) {
  462. errback(err);
  463. } else {
  464. each(ids, function (id) {
  465. var mod = getOwn(registry, id);
  466. if (mod) {
  467. //Set error on module, so it skips timeout checks.
  468. mod.error = err;
  469. if (mod.events.error) {
  470. notified = true;
  471. mod.emit('error', err);
  472. }
  473. }
  474. });
  475. if (!notified) {
  476. req.onError(err);
  477. }
  478. }
  479. }
  480. /**
  481. * Internal method to transfer globalQueue items to this context's
  482. * defQueue.
  483. */
  484. function takeGlobalQueue() {
  485. //Push all the globalDefQueue items into the context's defQueue
  486. if (globalDefQueue.length) {
  487. //Array splice in the values since the context code has a
  488. //local var ref to defQueue, so cannot just reassign the one
  489. //on context.
  490. apsp.apply(defQueue,
  491. [defQueue.length - 1, 0].concat(globalDefQueue));
  492. globalDefQueue = [];
  493. }
  494. }
  495. handlers = {
  496. 'require': function (mod) {
  497. if (mod.require) {
  498. return mod.require;
  499. } else {
  500. return (mod.require = context.makeRequire(mod.map));
  501. }
  502. },
  503. 'exports': function (mod) {
  504. mod.usingExports = true;
  505. if (mod.map.isDefine) {
  506. if (mod.exports) {
  507. return mod.exports;
  508. } else {
  509. return (mod.exports = defined[mod.map.id] = {});
  510. }
  511. }
  512. },
  513. 'module': function (mod) {
  514. if (mod.module) {
  515. return mod.module;
  516. } else {
  517. return (mod.module = {
  518. id: mod.map.id,
  519. uri: mod.map.url,
  520. config: function () {
  521. return (config.config && getOwn(config.config, mod.map.id)) || {};
  522. },
  523. exports: defined[mod.map.id]
  524. });
  525. }
  526. }
  527. };
  528. function cleanRegistry(id) {
  529. //Clean up machinery used for waiting modules.
  530. delete registry[id];
  531. delete enabledRegistry[id];
  532. }
  533. function breakCycle(mod, traced, processed) {
  534. var id = mod.map.id;
  535. if (mod.error) {
  536. mod.emit('error', mod.error);
  537. } else {
  538. traced[id] = true;
  539. each(mod.depMaps, function (depMap, i) {
  540. var depId = depMap.id,
  541. dep = getOwn(registry, depId);
  542. //Only force things that have not completed
  543. //being defined, so still in the registry,
  544. //and only if it has not been matched up
  545. //in the module already.
  546. if (dep && !mod.depMatched[i] && !processed[depId]) {
  547. if (getOwn(traced, depId)) {
  548. mod.defineDep(i, defined[depId]);
  549. mod.check(); //pass false?
  550. } else {
  551. breakCycle(dep, traced, processed);
  552. }
  553. }
  554. });
  555. processed[id] = true;
  556. }
  557. }
  558. function checkLoaded() {
  559. var map, modId, err, usingPathFallback,
  560. waitInterval = config.waitSeconds * 1000,
  561. //It is possible to disable the wait interval by using waitSeconds of 0.
  562. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  563. noLoads = [],
  564. reqCalls = [],
  565. stillLoading = false,
  566. needCycleCheck = true;
  567. //Do not bother if this call was a result of a cycle break.
  568. if (inCheckLoaded) {
  569. return;
  570. }
  571. inCheckLoaded = true;
  572. //Figure out the state of all the modules.
  573. eachProp(enabledRegistry, function (mod) {
  574. map = mod.map;
  575. modId = map.id;
  576. //Skip things that are not enabled or in error state.
  577. if (!mod.enabled) {
  578. return;
  579. }
  580. if (!map.isDefine) {
  581. reqCalls.push(mod);
  582. }
  583. if (!mod.error) {
  584. //If the module should be executed, and it has not
  585. //been inited and time is up, remember it.
  586. if (!mod.inited && expired) {
  587. if (hasPathFallback(modId)) {
  588. usingPathFallback = true;
  589. stillLoading = true;
  590. } else {
  591. noLoads.push(modId);
  592. removeScript(modId);
  593. }
  594. } else if (!mod.inited && mod.fetched && map.isDefine) {
  595. stillLoading = true;
  596. if (!map.prefix) {
  597. //No reason to keep looking for unfinished
  598. //loading. If the only stillLoading is a
  599. //plugin resource though, keep going,
  600. //because it may be that a plugin resource
  601. //is waiting on a non-plugin cycle.
  602. return (needCycleCheck = false);
  603. }
  604. }
  605. }
  606. });
  607. if (expired && noLoads.length) {
  608. //If wait time expired, throw error of unloaded modules.
  609. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  610. err.contextName = context.contextName;
  611. return onError(err);
  612. }
  613. //Not expired, check for a cycle.
  614. if (needCycleCheck) {
  615. each(reqCalls, function (mod) {
  616. breakCycle(mod, {}, {});
  617. });
  618. }
  619. //If still waiting on loads, and the waiting load is something
  620. //other than a plugin resource, or there are still outstanding
  621. //scripts, then just try back later.
  622. if ((!expired || usingPathFallback) && stillLoading) {
  623. //Something is still waiting to load. Wait for it, but only
  624. //if a timeout is not already in effect.
  625. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  626. checkLoadedTimeoutId = setTimeout(function () {
  627. checkLoadedTimeoutId = 0;
  628. checkLoaded();
  629. }, 50);
  630. }
  631. }
  632. inCheckLoaded = false;
  633. }
  634. Module = function (map) {
  635. this.events = getOwn(undefEvents, map.id) || {};
  636. this.map = map;
  637. this.shim = getOwn(config.shim, map.id);
  638. this.depExports = [];
  639. this.depMaps = [];
  640. this.depMatched = [];
  641. this.pluginMaps = {};
  642. this.depCount = 0;
  643. /* this.exports this.factory
  644. this.depMaps = [],
  645. this.enabled, this.fetched
  646. */
  647. };
  648. Module.prototype = {
  649. init: function (depMaps, factory, errback, options) {
  650. options = options || {};
  651. //Do not do more inits if already done. Can happen if there
  652. //are multiple define calls for the same module. That is not
  653. //a normal, common case, but it is also not unexpected.
  654. if (this.inited) {
  655. return;
  656. }
  657. this.factory = factory;
  658. if (errback) {
  659. //Register for errors on this module.
  660. this.on('error', errback);
  661. } else if (this.events.error) {
  662. //If no errback already, but there are error listeners
  663. //on this module, set up an errback to pass to the deps.
  664. errback = bind(this, function (err) {
  665. this.emit('error', err);
  666. });
  667. }
  668. //Do a copy of the dependency array, so that
  669. //source inputs are not modified. For example
  670. //"shim" deps are passed in here directly, and
  671. //doing a direct modification of the depMaps array
  672. //would affect that config.
  673. this.depMaps = depMaps && depMaps.slice(0);
  674. this.errback = errback;
  675. //Indicate this module has be initialized
  676. this.inited = true;
  677. this.ignore = options.ignore;
  678. //Could have option to init this module in enabled mode,
  679. //or could have been previously marked as enabled. However,
  680. //the dependencies are not known until init is called. So
  681. //if enabled previously, now trigger dependencies as enabled.
  682. if (options.enabled || this.enabled) {
  683. //Enable this module and dependencies.
  684. //Will call this.check()
  685. this.enable();
  686. } else {
  687. this.check();
  688. }
  689. },
  690. defineDep: function (i, depExports) {
  691. //Because of cycles, defined callback for a given
  692. //export can be called more than once.
  693. if (!this.depMatched[i]) {
  694. this.depMatched[i] = true;
  695. this.depCount -= 1;
  696. this.depExports[i] = depExports;
  697. }
  698. },
  699. fetch: function () {
  700. if (this.fetched) {
  701. return;
  702. }
  703. this.fetched = true;
  704. context.startTime = (new Date()).getTime();
  705. var map = this.map;
  706. //If the manager is for a plugin managed resource,
  707. //ask the plugin to load it now.
  708. if (this.shim) {
  709. context.makeRequire(this.map, {
  710. enableBuildCallback: true
  711. })(this.shim.deps || [], bind(this, function () {
  712. return map.prefix ? this.callPlugin() : this.load();
  713. }));
  714. } else {
  715. //Regular dependency.
  716. return map.prefix ? this.callPlugin() : this.load();
  717. }
  718. },
  719. load: function () {
  720. var url = this.map.url;
  721. //Regular dependency.
  722. if (!urlFetched[url]) {
  723. urlFetched[url] = true;
  724. context.load(this.map.id, url);
  725. }
  726. },
  727. /**
  728. * Checks if the module is ready to define itself, and if so,
  729. * define it.
  730. */
  731. check: function () {
  732. if (!this.enabled || this.enabling) {
  733. return;
  734. }
  735. var err, cjsModule,
  736. id = this.map.id,
  737. depExports = this.depExports,
  738. exports = this.exports,
  739. factory = this.factory;
  740. if (!this.inited) {
  741. this.fetch();
  742. } else if (this.error) {
  743. this.emit('error', this.error);
  744. } else if (!this.defining) {
  745. //The factory could trigger another require call
  746. //that would result in checking this module to
  747. //define itself again. If already in the process
  748. //of doing that, skip this work.
  749. this.defining = true;
  750. if (this.depCount < 1 && !this.defined) {
  751. if (isFunction(factory)) {
  752. //If there is an error listener, favor passing
  753. //to that instead of throwing an error.
  754. if (this.events.error) {
  755. try {
  756. exports = context.execCb(id, factory, depExports, exports);
  757. } catch (e) {
  758. err = e;
  759. }
  760. } else {
  761. exports = context.execCb(id, factory, depExports, exports);
  762. }
  763. if (this.map.isDefine) {
  764. //If setting exports via 'module' is in play,
  765. //favor that over return value and exports. After that,
  766. //favor a non-undefined return value over exports use.
  767. cjsModule = this.module;
  768. if (cjsModule &&
  769. cjsModule.exports !== undefined &&
  770. //Make sure it is not already the exports value
  771. cjsModule.exports !== this.exports) {
  772. exports = cjsModule.exports;
  773. } else if (exports === undefined && this.usingExports) {
  774. //exports already set the defined value.
  775. exports = this.exports;
  776. }
  777. }
  778. if (err) {
  779. err.requireMap = this.map;
  780. err.requireModules = [this.map.id];
  781. err.requireType = 'define';
  782. return onError((this.error = err));
  783. }
  784. } else {
  785. //Just a literal value
  786. exports = factory;
  787. }
  788. this.exports = exports;
  789. if (this.map.isDefine && !this.ignore) {
  790. defined[id] = exports;
  791. if (req.onResourceLoad) {
  792. req.onResourceLoad(context, this.map, this.depMaps);
  793. }
  794. }
  795. //Clean up
  796. cleanRegistry(id);
  797. this.defined = true;
  798. }
  799. //Finished the define stage. Allow calling check again
  800. //to allow define notifications below in the case of a
  801. //cycle.
  802. this.defining = false;
  803. if (this.defined && !this.defineEmitted) {
  804. this.defineEmitted = true;
  805. this.emit('defined', this.exports);
  806. this.defineEmitComplete = true;
  807. }
  808. }
  809. },
  810. callPlugin: function () {
  811. var map = this.map,
  812. id = map.id,
  813. //Map already normalized the prefix.
  814. pluginMap = makeModuleMap(map.prefix);
  815. //Mark this as a dependency for this plugin, so it
  816. //can be traced for cycles.
  817. this.depMaps.push(pluginMap);
  818. on(pluginMap, 'defined', bind(this, function (plugin) {
  819. var load, normalizedMap, normalizedMod,
  820. name = this.map.name,
  821. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  822. localRequire = context.makeRequire(map.parentMap, {
  823. enableBuildCallback: true
  824. });
  825. //If current map is not normalized, wait for that
  826. //normalized name to load instead of continuing.
  827. if (this.map.unnormalized) {
  828. //Normalize the ID if the plugin allows it.
  829. if (plugin.normalize) {
  830. name = plugin.normalize(name, function (name) {
  831. return normalize(name, parentName, true);
  832. }) || '';
  833. }
  834. //prefix and name should already be normalized, no need
  835. //for applying map config again either.
  836. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  837. this.map.parentMap);
  838. on(normalizedMap,
  839. 'defined', bind(this, function (value) {
  840. this.init([], function () { return value; }, null, {
  841. enabled: true,
  842. ignore: true
  843. });
  844. }));
  845. normalizedMod = getOwn(registry, normalizedMap.id);
  846. if (normalizedMod) {
  847. //Mark this as a dependency for this plugin, so it
  848. //can be traced for cycles.
  849. this.depMaps.push(normalizedMap);
  850. if (this.events.error) {
  851. normalizedMod.on('error', bind(this, function (err) {
  852. this.emit('error', err);
  853. }));
  854. }
  855. normalizedMod.enable();
  856. }
  857. return;
  858. }
  859. load = bind(this, function (value) {
  860. this.init([], function () { return value; }, null, {
  861. enabled: true
  862. });
  863. });
  864. load.error = bind(this, function (err) {
  865. this.inited = true;
  866. this.error = err;
  867. err.requireModules = [id];
  868. //Remove temp unnormalized modules for this module,
  869. //since they will never be resolved otherwise now.
  870. eachProp(registry, function (mod) {
  871. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  872. cleanRegistry(mod.map.id);
  873. }
  874. });
  875. onError(err);
  876. });
  877. //Allow plugins to load other code without having to know the
  878. //context or how to 'complete' the load.
  879. load.fromText = bind(this, function (text, textAlt) {
  880. /*jslint evil: true */
  881. var moduleName = map.name,
  882. moduleMap = makeModuleMap(moduleName),
  883. hasInteractive = useInteractive;
  884. //As of 2.1.0, support just passing the text, to reinforce
  885. //fromText only being called once per resource. Still
  886. //support old style of passing moduleName but discard
  887. //that moduleName in favor of the internal ref.
  888. if (textAlt) {
  889. text = textAlt;
  890. }
  891. //Turn off interactive script matching for IE for any define
  892. //calls in the text, then turn it back on at the end.
  893. if (hasInteractive) {
  894. useInteractive = false;
  895. }
  896. //Prime the system by creating a module instance for
  897. //it.
  898. getModule(moduleMap);
  899. //Transfer any config to this other module.
  900. if (hasProp(config.config, id)) {
  901. config.config[moduleName] = config.config[id];
  902. }
  903. try {
  904. req.exec(text);
  905. } catch (e) {
  906. return onError(makeError('fromtexteval',
  907. 'fromText eval for ' + id +
  908. ' failed: ' + e,
  909. e,
  910. [id]));
  911. }
  912. if (hasInteractive) {
  913. useInteractive = true;
  914. }
  915. //Mark this as a dependency for the plugin
  916. //resource
  917. this.depMaps.push(moduleMap);
  918. //Support anonymous modules.
  919. context.completeLoad(moduleName);
  920. //Bind the value of that module to the value for this
  921. //resource ID.
  922. localRequire([moduleName], load);
  923. });
  924. //Use parentName here since the plugin's name is not reliable,
  925. //could be some weird string with no path that actually wants to
  926. //reference the parentName's path.
  927. plugin.load(map.name, localRequire, load, config);
  928. }));
  929. context.enable(pluginMap, this);
  930. this.pluginMaps[pluginMap.id] = pluginMap;
  931. },
  932. enable: function () {
  933. enabledRegistry[this.map.id] = this;
  934. this.enabled = true;
  935. //Set flag mentioning that the module is enabling,
  936. //so that immediate calls to the defined callbacks
  937. //for dependencies do not trigger inadvertent load
  938. //with the depCount still being zero.
  939. this.enabling = true;
  940. //Enable each dependency
  941. each(this.depMaps, bind(this, function (depMap, i) {
  942. var id, mod, handler;
  943. if (typeof depMap === 'string') {
  944. //Dependency needs to be converted to a depMap
  945. //and wired up to this module.
  946. depMap = makeModuleMap(depMap,
  947. (this.map.isDefine ? this.map : this.map.parentMap),
  948. false,
  949. !this.skipMap);
  950. this.depMaps[i] = depMap;
  951. handler = getOwn(handlers, depMap.id);
  952. if (handler) {
  953. this.depExports[i] = handler(this);
  954. return;
  955. }
  956. this.depCount += 1;
  957. on(depMap, 'defined', bind(this, function (depExports) {
  958. this.defineDep(i, depExports);
  959. this.check();
  960. }));
  961. if (this.errback) {
  962. on(depMap, 'error', this.errback);
  963. }
  964. }
  965. id = depMap.id;
  966. mod = registry[id];
  967. //Skip special modules like 'require', 'exports', 'module'
  968. //Also, don't call enable if it is already enabled,
  969. //important in circular dependency cases.
  970. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  971. context.enable(depMap, this);
  972. }
  973. }));
  974. //Enable each plugin that is used in
  975. //a dependency
  976. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  977. var mod = getOwn(registry, pluginMap.id);
  978. if (mod && !mod.enabled) {
  979. context.enable(pluginMap, this);
  980. }
  981. }));
  982. this.enabling = false;
  983. this.check();
  984. },
  985. on: function (name, cb) {
  986. var cbs = this.events[name];
  987. if (!cbs) {
  988. cbs = this.events[name] = [];
  989. }
  990. cbs.push(cb);
  991. },
  992. emit: function (name, evt) {
  993. each(this.events[name], function (cb) {
  994. cb(evt);
  995. });
  996. if (name === 'error') {
  997. //Now that the error handler was triggered, remove
  998. //the listeners, since this broken Module instance
  999. //can stay around for a while in the registry.
  1000. delete this.events[name];
  1001. }
  1002. }
  1003. };
  1004. function callGetModule(args) {
  1005. //Skip modules already defined.
  1006. if (!hasProp(defined, args[0])) {
  1007. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1008. }
  1009. }
  1010. function removeListener(node, func, name, ieName) {
  1011. //Favor detachEvent because of IE9
  1012. //issue, see attachEvent/addEventListener comment elsewhere
  1013. //in this file.
  1014. if (node.detachEvent && !isOpera) {
  1015. //Probably IE. If not it will throw an error, which will be
  1016. //useful to know.
  1017. if (ieName) {
  1018. node.detachEvent(ieName, func);
  1019. }
  1020. } else {
  1021. node.removeEventListener(name, func, false);
  1022. }
  1023. }
  1024. /**
  1025. * Given an event from a script node, get the requirejs info from it,
  1026. * and then removes the event listeners on the node.
  1027. * @param {Event} evt
  1028. * @returns {Object}
  1029. */
  1030. function getScriptData(evt) {
  1031. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1032. //all old browsers will be supported, but this one was easy enough
  1033. //to support and still makes sense.
  1034. var node = evt.currentTarget || evt.srcElement;
  1035. //Remove the listeners once here.
  1036. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1037. removeListener(node, context.onScriptError, 'error');
  1038. return {
  1039. node: node,
  1040. id: node && node.getAttribute('data-requiremodule')
  1041. };
  1042. }
  1043. function intakeDefines() {
  1044. var args;
  1045. //Any defined modules in the global queue, intake them now.
  1046. takeGlobalQueue();
  1047. //Make sure any remaining defQueue items get properly processed.
  1048. while (defQueue.length) {
  1049. args = defQueue.shift();
  1050. if (args[0] === null) {
  1051. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  1052. } else {
  1053. //args are id, deps, factory. Should be normalized by the
  1054. //define() function.
  1055. callGetModule(args);
  1056. }
  1057. }
  1058. }
  1059. context = {
  1060. config: config,
  1061. contextName: contextName,
  1062. registry: registry,
  1063. defined: defined,
  1064. urlFetched: urlFetched,
  1065. defQueue: defQueue,
  1066. Module: Module,
  1067. makeModuleMap: makeModuleMap,
  1068. nextTick: req.nextTick,
  1069. onError: onError,
  1070. /**
  1071. * Set a configuration for the context.
  1072. * @param {Object} cfg config object to integrate.
  1073. */
  1074. configure: function (cfg) {
  1075. //Make sure the baseUrl ends in a slash.
  1076. if (cfg.baseUrl) {
  1077. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1078. cfg.baseUrl += '/';
  1079. }
  1080. }
  1081. //Save off the paths and packages since they require special processing,
  1082. //they are additive.
  1083. var pkgs = config.pkgs,
  1084. shim = config.shim,
  1085. objs = {
  1086. paths: true,
  1087. config: true,
  1088. map: true
  1089. };
  1090. eachProp(cfg, function (value, prop) {
  1091. if (objs[prop]) {
  1092. if (prop === 'map') {
  1093. if (!config.map) {
  1094. config.map = {};
  1095. }
  1096. mixin(config[prop], value, true, true);
  1097. } else {
  1098. mixin(config[prop], value, true);
  1099. }
  1100. } else {
  1101. config[prop] = value;
  1102. }
  1103. });
  1104. //Merge shim
  1105. if (cfg.shim) {
  1106. eachProp(cfg.shim, function (value, id) {
  1107. //Normalize the structure
  1108. if (isArray(value)) {
  1109. value = {
  1110. deps: value
  1111. };
  1112. }
  1113. if ((value.exports || value.init) && !value.exportsFn) {
  1114. value.exportsFn = context.makeShimExports(value);
  1115. }
  1116. shim[id] = value;
  1117. });
  1118. config.shim = shim;
  1119. }
  1120. //Adjust packages if necessary.
  1121. if (cfg.packages) {
  1122. each(cfg.packages, function (pkgObj) {
  1123. var location;
  1124. pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  1125. location = pkgObj.location;
  1126. //Create a brand new object on pkgs, since currentPackages can
  1127. //be passed in again, and config.pkgs is the internal transformed
  1128. //state for all package configs.
  1129. pkgs[pkgObj.name] = {
  1130. name: pkgObj.name,
  1131. location: location || pkgObj.name,
  1132. //Remove leading dot in main, so main paths are normalized,
  1133. //and remove any trailing .js, since different package
  1134. //envs have different conventions: some use a module name,
  1135. //some use a file name.
  1136. main: (pkgObj.main || 'main')
  1137. .replace(currDirRegExp, '')
  1138. .replace(jsSuffixRegExp, '')
  1139. };
  1140. });
  1141. //Done with modifications, assing packages back to context config
  1142. config.pkgs = pkgs;
  1143. }
  1144. //If there are any "waiting to execute" modules in the registry,
  1145. //update the maps for them, since their info, like URLs to load,
  1146. //may have changed.
  1147. eachProp(registry, function (mod, id) {
  1148. //If module already has init called, since it is too
  1149. //late to modify them, and ignore unnormalized ones
  1150. //since they are transient.
  1151. if (!mod.inited && !mod.map.unnormalized) {
  1152. mod.map = makeModuleMap(id);
  1153. }
  1154. });
  1155. //If a deps array or a config callback is specified, then call
  1156. //require with those args. This is useful when require is defined as a
  1157. //config object before require.js is loaded.
  1158. if (cfg.deps || cfg.callback) {
  1159. context.require(cfg.deps || [], cfg.callback);
  1160. }
  1161. },
  1162. makeShimExports: function (value) {
  1163. function fn() {
  1164. var ret;
  1165. if (value.init) {
  1166. ret = value.init.apply(global, arguments);
  1167. }
  1168. return ret || (value.exports && getGlobal(value.exports));
  1169. }
  1170. return fn;
  1171. },
  1172. makeRequire: function (relMap, options) {
  1173. options = options || {};
  1174. function localRequire(deps, callback, errback) {
  1175. var id, map, requireMod;
  1176. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1177. callback.__requireJsBuild = true;
  1178. }
  1179. if (typeof deps === 'string') {
  1180. if (isFunction(callback)) {
  1181. //Invalid call
  1182. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1183. }
  1184. //If require|exports|module are requested, get the
  1185. //value for them from the special handlers. Caveat:
  1186. //this only works while module is being defined.
  1187. if (relMap && hasProp(handlers, deps)) {
  1188. return handlers[deps](registry[relMap.id]);
  1189. }
  1190. //Synchronous access to one module. If require.get is
  1191. //available (as in the Node adapter), prefer that.
  1192. if (req.get) {
  1193. return req.get(context, deps, relMap, localRequire);
  1194. }
  1195. //Normalize module name, if it contains . or ..
  1196. map = makeModuleMap(deps, relMap, false, true);
  1197. id = map.id;
  1198. if (!hasProp(defined, id)) {
  1199. return onError(makeError('notloaded', 'Module name "' +
  1200. id +
  1201. '" has not been loaded yet for context: ' +
  1202. contextName +
  1203. (relMap ? '' : '. Use require([])')));
  1204. }
  1205. return defined[id];
  1206. }
  1207. //Grab defines waiting in the global queue.
  1208. intakeDefines();
  1209. //Mark all the dependencies as needing to be loaded.
  1210. context.nextTick(function () {
  1211. //Some defines could have been added since the
  1212. //require call, collect them.
  1213. intakeDefines();
  1214. requireMod = getModule(makeModuleMap(null, relMap));
  1215. //Store if map config should be applied to this require
  1216. //call for dependencies.
  1217. requireMod.skipMap = options.skipMap;
  1218. requireMod.init(deps, callback, errback, {
  1219. enabled: true
  1220. });
  1221. checkLoaded();
  1222. });
  1223. return localRequire;
  1224. }
  1225. mixin(localRequire, {
  1226. isBrowser: isBrowser,
  1227. /**
  1228. * Converts a module name + .extension into an URL path.
  1229. * *Requires* the use of a module name. It does not support using
  1230. * plain URLs like nameToUrl.
  1231. */
  1232. toUrl: function (moduleNamePlusExt) {
  1233. var ext,
  1234. index = moduleNamePlusExt.lastIndexOf('.'),
  1235. segment = moduleNamePlusExt.split('/')[0],
  1236. isRelative = segment === '.' || segment === '..';
  1237. //Have a file extension alias, and it is not the
  1238. //dots from a relative path.
  1239. if (index !== -1 && (!isRelative || index > 1)) {
  1240. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1241. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1242. }
  1243. return context.nameToUrl(normalize(moduleNamePlusExt,
  1244. relMap && relMap.id, true), ext, true);
  1245. },
  1246. defined: function (id) {
  1247. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1248. },
  1249. specified: function (id) {
  1250. id = makeModuleMap(id, relMap, false, true).id;
  1251. return hasProp(defined, id) || hasProp(registry, id);
  1252. }
  1253. });
  1254. //Only allow undef on top level require calls
  1255. if (!relMap) {
  1256. localRequire.undef = function (id) {
  1257. //Bind any waiting define() calls to this context,
  1258. //fix for #408
  1259. takeGlobalQueue();
  1260. var map = makeModuleMap(id, relMap, true),
  1261. mod = getOwn(registry, id);
  1262. delete defined[id];
  1263. delete urlFetched[map.url];
  1264. delete undefEvents[id];
  1265. if (mod) {
  1266. //Hold on to listeners in case the
  1267. //module will be attempted to be reloaded
  1268. //using a different config.
  1269. if (mod.events.defined) {
  1270. undefEvents[id] = mod.events;
  1271. }
  1272. cleanRegistry(id);
  1273. }
  1274. };
  1275. }
  1276. return localRequire;
  1277. },
  1278. /**
  1279. * Called to enable a module if it is still in the registry
  1280. * awaiting enablement. A second arg, parent, the parent module,
  1281. * is passed in for context, when this method is overriden by
  1282. * the optimizer. Not shown here to keep code compact.
  1283. */
  1284. enable: function (depMap) {
  1285. var mod = getOwn(registry, depMap.id);
  1286. if (mod) {
  1287. getModule(depMap).enable();
  1288. }
  1289. },
  1290. /**
  1291. * Internal method used by environment adapters to complete a load event.
  1292. * A load event could be a script load or just a load pass from a synchronous
  1293. * load call.
  1294. * @param {String} moduleName the name of the module to potentially complete.
  1295. */
  1296. completeLoad: function (moduleName) {
  1297. var found, args, mod,
  1298. shim = getOwn(config.shim, moduleName) || {},
  1299. shExports = shim.exports;
  1300. takeGlobalQueue();
  1301. while (defQueue.length) {
  1302. args = defQueue.shift();
  1303. if (args[0] === null) {
  1304. args[0] = moduleName;
  1305. //If already found an anonymous module and bound it
  1306. //to this name, then this is some other anon module
  1307. //waiting for its completeLoad to fire.
  1308. if (found) {
  1309. break;
  1310. }
  1311. found = true;
  1312. } else if (args[0] === moduleName) {
  1313. //Found matching define call for this script!
  1314. found = true;
  1315. }
  1316. callGetModule(args);
  1317. }
  1318. //Do this after the cycle of callGetModule in case the result
  1319. //of those calls/init calls changes the registry.
  1320. mod = getOwn(registry, moduleName);
  1321. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1322. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1323. if (hasPathFallback(moduleName)) {
  1324. return;
  1325. } else {
  1326. return onError(makeError('nodefine',
  1327. 'No define call for ' + moduleName,
  1328. null,
  1329. [moduleName]));
  1330. }
  1331. } else {
  1332. //A script that does not call define(), so just simulate
  1333. //the call for it.
  1334. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1335. }
  1336. }
  1337. checkLoaded();
  1338. },
  1339. /**
  1340. * Converts a module name to a file path. Supports cases where
  1341. * moduleName may actually be just an URL.
  1342. * Note that it **does not** call normalize on the moduleName,
  1343. * it is assumed to have already been normalized. This is an
  1344. * internal API, not a public one. Use toUrl for the public API.
  1345. */
  1346. nameToUrl: function (moduleName, ext, skipExt) {
  1347. var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
  1348. parentPath;
  1349. //If a colon is in the URL, it indicates a protocol is used and it is just
  1350. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1351. //or ends with .js, then assume the user meant to use an url and not a module id.
  1352. //The slash is important for protocol-less URLs as well as full paths.
  1353. if (req.jsExtRegExp.test(moduleName)) {
  1354. //Just a plain path, not module name lookup, so just return it.
  1355. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1356. //an extension, this method probably needs to be reworked.
  1357. url = moduleName + (ext || '');
  1358. } else {
  1359. //A module that needs to be converted to a path.
  1360. paths = config.paths;
  1361. pkgs = config.pkgs;
  1362. syms = moduleName.split('/');
  1363. //For each module name segment, see if there is a path
  1364. //registered for it. Start with most specific name
  1365. //and work up from it.
  1366. for (i = syms.length; i > 0; i -= 1) {
  1367. parentModule = syms.slice(0, i).join('/');
  1368. pkg = getOwn(pkgs, parentModule);
  1369. parentPath = getOwn(paths, parentModule);
  1370. if (parentPath) {
  1371. //If an array, it means there are a few choices,
  1372. //Choose the one that is desired
  1373. if (isArray(parentPath)) {
  1374. parentPath = parentPath[0];
  1375. }
  1376. syms.splice(0, i, parentPath);
  1377. break;
  1378. } else if (pkg) {
  1379. //If module name is just the package name, then looking
  1380. //for the main module.
  1381. if (moduleName === pkg.name) {
  1382. pkgPath = pkg.location + '/' + pkg.main;
  1383. } else {
  1384. pkgPath = pkg.location;
  1385. }
  1386. syms.splice(0, i, pkgPath);
  1387. break;
  1388. }
  1389. }
  1390. //Join the path parts together, then figure out if baseUrl is needed.
  1391. url = syms.join('/');
  1392. url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
  1393. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1394. }
  1395. return config.urlArgs ? url +
  1396. ((url.indexOf('?') === -1 ? '?' : '&') +
  1397. config.urlArgs) : url;
  1398. },
  1399. //Delegates to req.load. Broken out as a separate function to
  1400. //allow overriding in the optimizer.
  1401. load: function (id, url) {
  1402. req.load(context, id, url);
  1403. },
  1404. /**
  1405. * Executes a module callack function. Broken out as a separate function
  1406. * solely to allow the build system to sequence the files in the built
  1407. * layer in the right sequence.
  1408. *
  1409. * @private
  1410. */
  1411. execCb: function (name, callback, args, exports) {
  1412. return callback.apply(exports, args);
  1413. },
  1414. /**
  1415. * callback for script loads, used to check status of loading.
  1416. *
  1417. * @param {Event} evt the event from the browser for the script
  1418. * that was loaded.
  1419. */
  1420. onScriptLoad: function (evt) {
  1421. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1422. //all old browsers will be supported, but this one was easy enough
  1423. //to support and still makes sense.
  1424. if (evt.type === 'load' ||
  1425. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1426. //Reset interactive script so a script node is not held onto for
  1427. //to long.
  1428. interactiveScript = null;
  1429. //Pull out the name of the module and the context.
  1430. var data = getScriptData(evt);
  1431. context.completeLoad(data.id);
  1432. }
  1433. },
  1434. /**
  1435. * Callback for script errors.
  1436. */
  1437. onScriptError: function (evt) {
  1438. var data = getScriptData(evt);
  1439. if (!hasPathFallback(data.id)) {
  1440. return onError(makeError('scripterror', 'Script error', evt, [data.id]));
  1441. }
  1442. }
  1443. };
  1444. context.require = context.makeRequire();
  1445. return context;
  1446. }
  1447. /**
  1448. * Main entry point.
  1449. *
  1450. * If the only argument to require is a string, then the module that
  1451. * is represented by that string is fetched for the appropriate context.
  1452. *
  1453. * If the first argument is an array, then it will be treated as an array
  1454. * of dependency string names to fetch. An optional function callback can
  1455. * be specified to execute when all of those dependencies are available.
  1456. *
  1457. * Make a local req variable to help Caja compliance (it assumes things
  1458. * on a require that are not standardized), and to give a short
  1459. * name for minification/local scope use.
  1460. */
  1461. req = requirejs = function (deps, callback, errback, optional) {
  1462. //Find the right context, use default
  1463. var context, config,
  1464. contextName = defContextName;
  1465. // Determine if have config object in the call.
  1466. if (!isArray(deps) && typeof deps !== 'string') {
  1467. // deps is a config object
  1468. config = deps;
  1469. if (isArray(callback)) {
  1470. // Adjust args if there are dependencies
  1471. deps = callback;
  1472. callback = errback;
  1473. errback = optional;
  1474. } else {
  1475. deps = [];
  1476. }
  1477. }
  1478. if (config && config.context) {
  1479. contextName = config.context;
  1480. }
  1481. context = getOwn(contexts, contextName);
  1482. if (!context) {
  1483. context = contexts[contextName] = req.s.newContext(contextName);
  1484. }
  1485. if (config) {
  1486. context.configure(config);
  1487. }
  1488. return context.require(deps, callback, errback);
  1489. };
  1490. /**
  1491. * Support require.config() to make it easier to cooperate with other
  1492. * AMD loaders on globally agreed names.
  1493. */
  1494. req.config = function (config) {
  1495. return req(config);
  1496. };
  1497. /**
  1498. * Execute something after the current tick
  1499. * of the event loop. Override for other envs
  1500. * that have a better solution than setTimeout.
  1501. * @param {Function} fn function to execute later.
  1502. */
  1503. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1504. setTimeout(fn, 4);
  1505. } : function (fn) { fn(); };
  1506. /**
  1507. * Export require as a global, but only if it does not already exist.
  1508. */
  1509. if (!require) {
  1510. require = req;
  1511. }
  1512. req.version = version;
  1513. //Used to filter out dependencies that are already paths.
  1514. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1515. req.isBrowser = isBrowser;
  1516. s = req.s = {
  1517. contexts: contexts,
  1518. newContext: newContext
  1519. };
  1520. //Create default context.
  1521. req({});
  1522. //Exports some context-sensitive methods on global require.
  1523. each([
  1524. 'toUrl',
  1525. 'undef',
  1526. 'defined',
  1527. 'specified'
  1528. ], function (prop) {
  1529. //Reference from contexts instead of early binding to default context,
  1530. //so that during builds, the latest instance of the default context
  1531. //with its config gets used.
  1532. req[prop] = function () {
  1533. var ctx = contexts[defContextName];
  1534. return ctx.require[prop].apply(ctx, arguments);
  1535. };
  1536. });
  1537. if (isBrowser) {
  1538. head = s.head = document.getElementsByTagName('head')[0];
  1539. //If BASE tag is in play, using appendChild is a problem for IE6.
  1540. //When that browser dies, this can be removed. Details in this jQuery bug:
  1541. //http://dev.jquery.com/ticket/2709
  1542. baseElement = document.getElementsByTagName('base')[0];
  1543. if (baseElement) {
  1544. head = s.head = baseElement.parentNode;
  1545. }
  1546. }
  1547. /**
  1548. * Any errors that require explicitly generates will be passed to this
  1549. * function. Intercept/override it if you want custom error handling.
  1550. * @param {Error} err the error object.
  1551. */
  1552. req.onError = function (err) {
  1553. throw err;
  1554. };
  1555. /**
  1556. * Does the request to load a module for the browser case.
  1557. * Make this a separate function to allow other environments
  1558. * to override it.
  1559. *
  1560. * @param {Object} context the require context to find state.
  1561. * @param {String} moduleName the name of the module.
  1562. * @param {Object} url the URL to the module.
  1563. */
  1564. req.load = function (context, moduleName, url) {
  1565. var config = (context && context.config) || {},
  1566. node;
  1567. if (isBrowser) {
  1568. //In the browser so use a script tag
  1569. node = config.xhtml ?
  1570. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1571. document.createElement('script');
  1572. node.type = config.scriptType || 'text/javascript';
  1573. node.charset = 'utf-8';
  1574. node.async = true;
  1575. node.setAttribute('data-requirecontext', context.contextName);
  1576. node.setAttribute('data-requiremodule', moduleName);
  1577. //Set up load listener. Test attachEvent first because IE9 has
  1578. //a subtle issue in its addEventListener and script onload firings
  1579. //that do not match the behavior of all other browsers with
  1580. //addEventListener support, which fire the onload event for a
  1581. //script right after the script execution. See:
  1582. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1583. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1584. //script execution mode.
  1585. if (node.attachEvent &&
  1586. //Check if node.attachEvent is artificially added by custom script or
  1587. //natively supported by browser
  1588. //read https://github.com/jrburke/requirejs/issues/187
  1589. //if we can NOT find [native code] then it must NOT natively supported.
  1590. //in IE8, node.attachEvent does not have toString()
  1591. //Note the test for "[native code" with no closing brace, see:
  1592. //https://github.com/jrburke/requirejs/issues/273
  1593. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1594. !isOpera) {
  1595. //Probably IE. IE (at least 6-8) do not fire
  1596. //script onload right after executing the script, so
  1597. //we cannot tie the anonymous define call to a name.
  1598. //However, IE reports the script as being in 'interactive'
  1599. //readyState at the time of the define call.
  1600. useInteractive = true;
  1601. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1602. //It would be great to add an error handler here to catch
  1603. //404s in IE9+. However, onreadystatechange will fire before
  1604. //the error handler, so that does not help. If addEventListener
  1605. //is used, then IE will fire error before load, but we cannot
  1606. //use that pathway given the connect.microsoft.com issue
  1607. //mentioned above about not doing the 'script execute,
  1608. //then fire the script load event listener before execute
  1609. //next script' that other browsers do.
  1610. //Best hope: IE10 fixes the issues,
  1611. //and then destroys all installs of IE 6-9.
  1612. //node.attachEvent('onerror', context.onScriptError);
  1613. } else {
  1614. node.addEventListener('load', context.onScriptLoad, false);
  1615. node.addEventListener('error', context.onScriptError, false);
  1616. }
  1617. node.src = url;
  1618. //For some cache cases in IE 6-8, the script executes before the end
  1619. //of the appendChild execution, so to tie an anonymous define
  1620. //call to the module name (which is stored on the node), hold on
  1621. //to a reference to this node, but clear after the DOM insertion.
  1622. currentlyAddingScript = node;
  1623. if (baseElement) {
  1624. head.insertBefore(node, baseElement);
  1625. } else {
  1626. head.appendChild(node);
  1627. }
  1628. currentlyAddingScript = null;
  1629. return node;
  1630. } else if (isWebWorker) {
  1631. try {
  1632. //In a web worker, use importScripts. This is not a very
  1633. //efficient use of importScripts, importScripts will block until
  1634. //its script is downloaded and evaluated. However, if web workers
  1635. //are in play, the expectation that a build has been done so that
  1636. //only one script needs to be loaded anyway. This may need to be
  1637. //reevaluated if other use cases become common.
  1638. importScripts(url);
  1639. //Account for anonymous modules
  1640. context.completeLoad(moduleName);
  1641. } catch (e) {
  1642. context.onError(makeError('importscripts',
  1643. 'importScripts failed for ' +
  1644. moduleName + ' at ' + url,
  1645. e,
  1646. [moduleName]));
  1647. }
  1648. }
  1649. };
  1650. function getInteractiveScript() {
  1651. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1652. return interactiveScript;
  1653. }
  1654. eachReverse(scripts(), function (script) {
  1655. if (script.readyState === 'interactive') {
  1656. return (interactiveScript = script);
  1657. }
  1658. });
  1659. return interactiveScript;
  1660. }
  1661. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1662. if (isBrowser) {
  1663. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1664. eachReverse(scripts(), function (script) {
  1665. //Set the 'head' where we can append children by
  1666. //using the script's parent.
  1667. if (!head) {
  1668. head = script.parentNode;
  1669. }
  1670. //Look for a data-main attribute to set main script for the page
  1671. //to load. If it is there, the path to data main becomes the
  1672. //baseUrl, if it is not already set.
  1673. dataMain = script.getAttribute('data-main');
  1674. if (dataMain) {
  1675. //Set final baseUrl if there is not already an explicit one.
  1676. if (!cfg.baseUrl) {
  1677. //Pull off the directory of data-main for use as the
  1678. //baseUrl.
  1679. src = dataMain.split('/');
  1680. mainScript = src.pop();
  1681. subPath = src.length ? src.join('/') + '/' : './';
  1682. cfg.baseUrl = subPath;
  1683. dataMain = mainScript;
  1684. }
  1685. //Strip off any trailing .js since dataMain is now
  1686. //like a module name.
  1687. dataMain = dataMain.replace(jsSuffixRegExp, '');
  1688. //Put the data-main script in the files to load.
  1689. cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
  1690. return true;
  1691. }
  1692. });
  1693. }
  1694. /**
  1695. * The function that handles definitions of modules. Differs from
  1696. * require() in that a string for the module should be the first argument,
  1697. * and the function to execute after dependencies are loaded should
  1698. * return a value to define the module corresponding to the first argument's
  1699. * name.
  1700. */
  1701. define = function (name, deps, callback) {
  1702. var node, context;
  1703. //Allow for anonymous modules
  1704. if (typeof name !== 'string') {
  1705. //Adjust args appropriately
  1706. callback = deps;
  1707. deps = name;
  1708. name = null;
  1709. }
  1710. //This module may not have dependencies
  1711. if (!isArray(deps)) {
  1712. callback = deps;
  1713. deps = [];
  1714. }
  1715. //If no name, and callback is a function, then figure out if it a
  1716. //CommonJS thing with dependencies.
  1717. if (!deps.length && isFunction(callback)) {
  1718. //Remove comments from the callback string,
  1719. //look for require calls, and pull them into the dependencies,
  1720. //but only if there are function args.
  1721. if (callback.length) {
  1722. callback
  1723. .toString()
  1724. .replace(commentRegExp, '')
  1725. .replace(cjsRequireRegExp, function (match, dep) {
  1726. deps.push(dep);
  1727. });
  1728. //May be a CommonJS thing even without require calls, but still
  1729. //could use exports, and module. Avoid doing exports and module
  1730. //work though if it just needs require.
  1731. //REQUIRES the function to expect the CommonJS variables in the
  1732. //order listed below.
  1733. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  1734. }
  1735. }
  1736. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  1737. //work.
  1738. if (useInteractive) {
  1739. node = currentlyAddingScript || getInteractiveScript();
  1740. if (node) {
  1741. if (!name) {
  1742. name = node.getAttribute('data-requiremodule');
  1743. }
  1744. context = contexts[node.getAttribute('data-requirecontext')];
  1745. }
  1746. }
  1747. //Always save off evaluating the def call until the script onload handler.
  1748. //This allows multiple modules to be in a file without prematurely
  1749. //tracing dependencies, and allows for anonymous module support,
  1750. //where the module name is not known until the script onload event
  1751. //occurs. If no context, use the global queue, and get it processed
  1752. //in the onscript load callback.
  1753. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
  1754. };
  1755. define.amd = {
  1756. jQuery: true
  1757. };
  1758. /**
  1759. * Executes the text. Normally just uses eval, but can be modified
  1760. * to use a better, environment-specific call. Only used for transpiling
  1761. * loader plugins, not for plain JS modules.
  1762. * @param {String} text the text to execute/evaluate.
  1763. */
  1764. req.exec = function (text) {
  1765. /*jslint evil: true */
  1766. return eval(text);
  1767. };
  1768. //Set up with config info.
  1769. req(cfg);
  1770. }(this));