cesiumWorkerBootstrapper.js 71 KB

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