loader.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958
  1. /*!-----------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Version: 0.31.1(5a1b4999493d49c857497ad481d73a737439f305)
  4. * Released under the MIT license
  5. * https://github.com/microsoft/vscode/blob/main/LICENSE.txt
  6. *-----------------------------------------------------------*/
  7. /*---------------------------------------------------------------------------------------------
  8. * Copyright (c) Microsoft Corporation. All rights reserved.
  9. * Licensed under the MIT License. See License.txt in the project root for license information.
  10. *--------------------------------------------------------------------------------------------*/
  11. 'use strict';
  12. /*---------------------------------------------------------------------------------------------
  13. * Copyright (c) Microsoft Corporation. All rights reserved.
  14. * Licensed under the MIT License. See License.txt in the project root for license information.
  15. *--------------------------------------------------------------------------------------------*/
  16. /*---------------------------------------------------------------------------------------------
  17. *---------------------------------------------------------------------------------------------
  18. *---------------------------------------------------------------------------------------------
  19. *---------------------------------------------------------------------------------------------
  20. *---------------------------------------------------------------------------------------------
  21. * Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/
  22. *---------------------------------------------------------------------------------------------
  23. *---------------------------------------------------------------------------------------------
  24. *---------------------------------------------------------------------------------------------
  25. *---------------------------------------------------------------------------------------------
  26. *--------------------------------------------------------------------------------------------*/
  27. var _amdLoaderGlobal = this;
  28. var _commonjsGlobal = typeof global === 'object' ? global : {};
  29. var AMDLoader;
  30. (function (AMDLoader) {
  31. AMDLoader.global = _amdLoaderGlobal;
  32. var Environment = /** @class */ (function () {
  33. function Environment() {
  34. this._detected = false;
  35. this._isWindows = false;
  36. this._isNode = false;
  37. this._isElectronRenderer = false;
  38. this._isWebWorker = false;
  39. this._isElectronNodeIntegrationWebWorker = false;
  40. }
  41. Object.defineProperty(Environment.prototype, "isWindows", {
  42. get: function () {
  43. this._detect();
  44. return this._isWindows;
  45. },
  46. enumerable: false,
  47. configurable: true
  48. });
  49. Object.defineProperty(Environment.prototype, "isNode", {
  50. get: function () {
  51. this._detect();
  52. return this._isNode;
  53. },
  54. enumerable: false,
  55. configurable: true
  56. });
  57. Object.defineProperty(Environment.prototype, "isElectronRenderer", {
  58. get: function () {
  59. this._detect();
  60. return this._isElectronRenderer;
  61. },
  62. enumerable: false,
  63. configurable: true
  64. });
  65. Object.defineProperty(Environment.prototype, "isWebWorker", {
  66. get: function () {
  67. this._detect();
  68. return this._isWebWorker;
  69. },
  70. enumerable: false,
  71. configurable: true
  72. });
  73. Object.defineProperty(Environment.prototype, "isElectronNodeIntegrationWebWorker", {
  74. get: function () {
  75. this._detect();
  76. return this._isElectronNodeIntegrationWebWorker;
  77. },
  78. enumerable: false,
  79. configurable: true
  80. });
  81. Environment.prototype._detect = function () {
  82. if (this._detected) {
  83. return;
  84. }
  85. this._detected = true;
  86. this._isWindows = Environment._isWindows();
  87. this._isNode = (typeof module !== 'undefined' && !!module.exports);
  88. this._isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer');
  89. this._isWebWorker = (typeof AMDLoader.global.importScripts === 'function');
  90. this._isElectronNodeIntegrationWebWorker = this._isWebWorker && (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'worker');
  91. };
  92. Environment._isWindows = function () {
  93. if (typeof navigator !== 'undefined') {
  94. if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) {
  95. return true;
  96. }
  97. }
  98. if (typeof process !== 'undefined') {
  99. return (process.platform === 'win32');
  100. }
  101. return false;
  102. };
  103. return Environment;
  104. }());
  105. AMDLoader.Environment = Environment;
  106. })(AMDLoader || (AMDLoader = {}));
  107. /*---------------------------------------------------------------------------------------------
  108. * Copyright (c) Microsoft Corporation. All rights reserved.
  109. * Licensed under the MIT License. See License.txt in the project root for license information.
  110. *--------------------------------------------------------------------------------------------*/
  111. var AMDLoader;
  112. (function (AMDLoader) {
  113. var LoaderEvent = /** @class */ (function () {
  114. function LoaderEvent(type, detail, timestamp) {
  115. this.type = type;
  116. this.detail = detail;
  117. this.timestamp = timestamp;
  118. }
  119. return LoaderEvent;
  120. }());
  121. AMDLoader.LoaderEvent = LoaderEvent;
  122. var LoaderEventRecorder = /** @class */ (function () {
  123. function LoaderEventRecorder(loaderAvailableTimestamp) {
  124. this._events = [new LoaderEvent(1 /* LoaderAvailable */, '', loaderAvailableTimestamp)];
  125. }
  126. LoaderEventRecorder.prototype.record = function (type, detail) {
  127. this._events.push(new LoaderEvent(type, detail, AMDLoader.Utilities.getHighPerformanceTimestamp()));
  128. };
  129. LoaderEventRecorder.prototype.getEvents = function () {
  130. return this._events;
  131. };
  132. return LoaderEventRecorder;
  133. }());
  134. AMDLoader.LoaderEventRecorder = LoaderEventRecorder;
  135. var NullLoaderEventRecorder = /** @class */ (function () {
  136. function NullLoaderEventRecorder() {
  137. }
  138. NullLoaderEventRecorder.prototype.record = function (type, detail) {
  139. // Nothing to do
  140. };
  141. NullLoaderEventRecorder.prototype.getEvents = function () {
  142. return [];
  143. };
  144. NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder();
  145. return NullLoaderEventRecorder;
  146. }());
  147. AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder;
  148. })(AMDLoader || (AMDLoader = {}));
  149. /*---------------------------------------------------------------------------------------------
  150. * Copyright (c) Microsoft Corporation. All rights reserved.
  151. * Licensed under the MIT License. See License.txt in the project root for license information.
  152. *--------------------------------------------------------------------------------------------*/
  153. var AMDLoader;
  154. (function (AMDLoader) {
  155. var Utilities = /** @class */ (function () {
  156. function Utilities() {
  157. }
  158. /**
  159. * This method does not take care of / vs \
  160. */
  161. Utilities.fileUriToFilePath = function (isWindows, uri) {
  162. uri = decodeURI(uri).replace(/%23/g, '#');
  163. if (isWindows) {
  164. if (/^file:\/\/\//.test(uri)) {
  165. // This is a URI without a hostname => return only the path segment
  166. return uri.substr(8);
  167. }
  168. if (/^file:\/\//.test(uri)) {
  169. return uri.substr(5);
  170. }
  171. }
  172. else {
  173. if (/^file:\/\//.test(uri)) {
  174. return uri.substr(7);
  175. }
  176. }
  177. // Not sure...
  178. return uri;
  179. };
  180. Utilities.startsWith = function (haystack, needle) {
  181. return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
  182. };
  183. Utilities.endsWith = function (haystack, needle) {
  184. return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle;
  185. };
  186. // only check for "?" before "#" to ensure that there is a real Query-String
  187. Utilities.containsQueryString = function (url) {
  188. return /^[^\#]*\?/gi.test(url);
  189. };
  190. /**
  191. * Does `url` start with http:// or https:// or file:// or / ?
  192. */
  193. Utilities.isAbsolutePath = function (url) {
  194. return /^((http:\/\/)|(https:\/\/)|(file:\/\/)|(\/))/.test(url);
  195. };
  196. Utilities.forEachProperty = function (obj, callback) {
  197. if (obj) {
  198. var key = void 0;
  199. for (key in obj) {
  200. if (obj.hasOwnProperty(key)) {
  201. callback(key, obj[key]);
  202. }
  203. }
  204. }
  205. };
  206. Utilities.isEmpty = function (obj) {
  207. var isEmpty = true;
  208. Utilities.forEachProperty(obj, function () {
  209. isEmpty = false;
  210. });
  211. return isEmpty;
  212. };
  213. Utilities.recursiveClone = function (obj) {
  214. if (!obj || typeof obj !== 'object' || obj instanceof RegExp) {
  215. return obj;
  216. }
  217. if (!Array.isArray(obj) && Object.getPrototypeOf(obj) !== Object.prototype) {
  218. // only clone "simple" objects
  219. return obj;
  220. }
  221. var result = Array.isArray(obj) ? [] : {};
  222. Utilities.forEachProperty(obj, function (key, value) {
  223. if (value && typeof value === 'object') {
  224. result[key] = Utilities.recursiveClone(value);
  225. }
  226. else {
  227. result[key] = value;
  228. }
  229. });
  230. return result;
  231. };
  232. Utilities.generateAnonymousModule = function () {
  233. return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '===';
  234. };
  235. Utilities.isAnonymousModule = function (id) {
  236. return Utilities.startsWith(id, '===anonymous');
  237. };
  238. Utilities.getHighPerformanceTimestamp = function () {
  239. if (!this.PERFORMANCE_NOW_PROBED) {
  240. this.PERFORMANCE_NOW_PROBED = true;
  241. this.HAS_PERFORMANCE_NOW = (AMDLoader.global.performance && typeof AMDLoader.global.performance.now === 'function');
  242. }
  243. return (this.HAS_PERFORMANCE_NOW ? AMDLoader.global.performance.now() : Date.now());
  244. };
  245. Utilities.NEXT_ANONYMOUS_ID = 1;
  246. Utilities.PERFORMANCE_NOW_PROBED = false;
  247. Utilities.HAS_PERFORMANCE_NOW = false;
  248. return Utilities;
  249. }());
  250. AMDLoader.Utilities = Utilities;
  251. })(AMDLoader || (AMDLoader = {}));
  252. /*---------------------------------------------------------------------------------------------
  253. * Copyright (c) Microsoft Corporation. All rights reserved.
  254. * Licensed under the MIT License. See License.txt in the project root for license information.
  255. *--------------------------------------------------------------------------------------------*/
  256. var AMDLoader;
  257. (function (AMDLoader) {
  258. function ensureError(err) {
  259. if (err instanceof Error) {
  260. return err;
  261. }
  262. var result = new Error(err.message || String(err) || 'Unknown Error');
  263. if (err.stack) {
  264. result.stack = err.stack;
  265. }
  266. return result;
  267. }
  268. AMDLoader.ensureError = ensureError;
  269. ;
  270. var ConfigurationOptionsUtil = /** @class */ (function () {
  271. function ConfigurationOptionsUtil() {
  272. }
  273. /**
  274. * Ensure configuration options make sense
  275. */
  276. ConfigurationOptionsUtil.validateConfigurationOptions = function (options) {
  277. function defaultOnError(err) {
  278. if (err.phase === 'loading') {
  279. console.error('Loading "' + err.moduleId + '" failed');
  280. console.error(err);
  281. console.error('Here are the modules that depend on it:');
  282. console.error(err.neededBy);
  283. return;
  284. }
  285. if (err.phase === 'factory') {
  286. console.error('The factory method of "' + err.moduleId + '" has thrown an exception');
  287. console.error(err);
  288. return;
  289. }
  290. }
  291. options = options || {};
  292. if (typeof options.baseUrl !== 'string') {
  293. options.baseUrl = '';
  294. }
  295. if (typeof options.isBuild !== 'boolean') {
  296. options.isBuild = false;
  297. }
  298. if (typeof options.paths !== 'object') {
  299. options.paths = {};
  300. }
  301. if (typeof options.config !== 'object') {
  302. options.config = {};
  303. }
  304. if (typeof options.catchError === 'undefined') {
  305. options.catchError = false;
  306. }
  307. if (typeof options.recordStats === 'undefined') {
  308. options.recordStats = false;
  309. }
  310. if (typeof options.urlArgs !== 'string') {
  311. options.urlArgs = '';
  312. }
  313. if (typeof options.onError !== 'function') {
  314. options.onError = defaultOnError;
  315. }
  316. if (!Array.isArray(options.ignoreDuplicateModules)) {
  317. options.ignoreDuplicateModules = [];
  318. }
  319. if (options.baseUrl.length > 0) {
  320. if (!AMDLoader.Utilities.endsWith(options.baseUrl, '/')) {
  321. options.baseUrl += '/';
  322. }
  323. }
  324. if (typeof options.cspNonce !== 'string') {
  325. options.cspNonce = '';
  326. }
  327. if (typeof options.preferScriptTags === 'undefined') {
  328. options.preferScriptTags = false;
  329. }
  330. if (!Array.isArray(options.nodeModules)) {
  331. options.nodeModules = [];
  332. }
  333. if (options.nodeCachedData && typeof options.nodeCachedData === 'object') {
  334. if (typeof options.nodeCachedData.seed !== 'string') {
  335. options.nodeCachedData.seed = 'seed';
  336. }
  337. if (typeof options.nodeCachedData.writeDelay !== 'number' || options.nodeCachedData.writeDelay < 0) {
  338. options.nodeCachedData.writeDelay = 1000 * 7;
  339. }
  340. if (!options.nodeCachedData.path || typeof options.nodeCachedData.path !== 'string') {
  341. var err = ensureError(new Error('INVALID cached data configuration, \'path\' MUST be set'));
  342. err.phase = 'configuration';
  343. options.onError(err);
  344. options.nodeCachedData = undefined;
  345. }
  346. }
  347. return options;
  348. };
  349. ConfigurationOptionsUtil.mergeConfigurationOptions = function (overwrite, base) {
  350. if (overwrite === void 0) { overwrite = null; }
  351. if (base === void 0) { base = null; }
  352. var result = AMDLoader.Utilities.recursiveClone(base || {});
  353. // Merge known properties and overwrite the unknown ones
  354. AMDLoader.Utilities.forEachProperty(overwrite, function (key, value) {
  355. if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') {
  356. result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value);
  357. }
  358. else if (key === 'paths' && typeof result.paths !== 'undefined') {
  359. AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.paths[key2] = value2; });
  360. }
  361. else if (key === 'config' && typeof result.config !== 'undefined') {
  362. AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.config[key2] = value2; });
  363. }
  364. else {
  365. result[key] = AMDLoader.Utilities.recursiveClone(value);
  366. }
  367. });
  368. return ConfigurationOptionsUtil.validateConfigurationOptions(result);
  369. };
  370. return ConfigurationOptionsUtil;
  371. }());
  372. AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil;
  373. var Configuration = /** @class */ (function () {
  374. function Configuration(env, options) {
  375. this._env = env;
  376. this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options);
  377. this._createIgnoreDuplicateModulesMap();
  378. this._createNodeModulesMap();
  379. this._createSortedPathsRules();
  380. if (this.options.baseUrl === '') {
  381. if (this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename && this._env.isNode) {
  382. var nodeMain = this.options.nodeRequire.main.filename;
  383. var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
  384. this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
  385. }
  386. if (this.options.nodeMain && this._env.isNode) {
  387. var nodeMain = this.options.nodeMain;
  388. var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
  389. this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
  390. }
  391. }
  392. }
  393. Configuration.prototype._createIgnoreDuplicateModulesMap = function () {
  394. // Build a map out of the ignoreDuplicateModules array
  395. this.ignoreDuplicateModulesMap = {};
  396. for (var i = 0; i < this.options.ignoreDuplicateModules.length; i++) {
  397. this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true;
  398. }
  399. };
  400. Configuration.prototype._createNodeModulesMap = function () {
  401. // Build a map out of nodeModules array
  402. this.nodeModulesMap = Object.create(null);
  403. for (var _i = 0, _a = this.options.nodeModules; _i < _a.length; _i++) {
  404. var nodeModule = _a[_i];
  405. this.nodeModulesMap[nodeModule] = true;
  406. }
  407. };
  408. Configuration.prototype._createSortedPathsRules = function () {
  409. var _this = this;
  410. // Create an array our of the paths rules, sorted descending by length to
  411. // result in a more specific -> less specific order
  412. this.sortedPathsRules = [];
  413. AMDLoader.Utilities.forEachProperty(this.options.paths, function (from, to) {
  414. if (!Array.isArray(to)) {
  415. _this.sortedPathsRules.push({
  416. from: from,
  417. to: [to]
  418. });
  419. }
  420. else {
  421. _this.sortedPathsRules.push({
  422. from: from,
  423. to: to
  424. });
  425. }
  426. });
  427. this.sortedPathsRules.sort(function (a, b) {
  428. return b.from.length - a.from.length;
  429. });
  430. };
  431. /**
  432. * Clone current configuration and overwrite options selectively.
  433. * @param options The selective options to overwrite with.
  434. * @result A new configuration
  435. */
  436. Configuration.prototype.cloneAndMerge = function (options) {
  437. return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options));
  438. };
  439. /**
  440. * Get current options bag. Useful for passing it forward to plugins.
  441. */
  442. Configuration.prototype.getOptionsLiteral = function () {
  443. return this.options;
  444. };
  445. Configuration.prototype._applyPaths = function (moduleId) {
  446. var pathRule;
  447. for (var i = 0, len = this.sortedPathsRules.length; i < len; i++) {
  448. pathRule = this.sortedPathsRules[i];
  449. if (AMDLoader.Utilities.startsWith(moduleId, pathRule.from)) {
  450. var result = [];
  451. for (var j = 0, lenJ = pathRule.to.length; j < lenJ; j++) {
  452. result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length));
  453. }
  454. return result;
  455. }
  456. }
  457. return [moduleId];
  458. };
  459. Configuration.prototype._addUrlArgsToUrl = function (url) {
  460. if (AMDLoader.Utilities.containsQueryString(url)) {
  461. return url + '&' + this.options.urlArgs;
  462. }
  463. else {
  464. return url + '?' + this.options.urlArgs;
  465. }
  466. };
  467. Configuration.prototype._addUrlArgsIfNecessaryToUrl = function (url) {
  468. if (this.options.urlArgs) {
  469. return this._addUrlArgsToUrl(url);
  470. }
  471. return url;
  472. };
  473. Configuration.prototype._addUrlArgsIfNecessaryToUrls = function (urls) {
  474. if (this.options.urlArgs) {
  475. for (var i = 0, len = urls.length; i < len; i++) {
  476. urls[i] = this._addUrlArgsToUrl(urls[i]);
  477. }
  478. }
  479. return urls;
  480. };
  481. /**
  482. * Transform a module id to a location. Appends .js to module ids
  483. */
  484. Configuration.prototype.moduleIdToPaths = function (moduleId) {
  485. if (this._env.isNode) {
  486. var isNodeModule = ((this.nodeModulesMap[moduleId] === true)
  487. || (this.options.amdModulesPattern instanceof RegExp && !this.options.amdModulesPattern.test(moduleId)));
  488. if (isNodeModule) {
  489. // This is a node module...
  490. if (this.isBuild()) {
  491. // ...and we are at build time, drop it
  492. return ['empty:'];
  493. }
  494. else {
  495. // ...and at runtime we create a `shortcut`-path
  496. return ['node|' + moduleId];
  497. }
  498. }
  499. }
  500. var result = moduleId;
  501. var results;
  502. if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.isAbsolutePath(result)) {
  503. results = this._applyPaths(result);
  504. for (var i = 0, len = results.length; i < len; i++) {
  505. if (this.isBuild() && results[i] === 'empty:') {
  506. continue;
  507. }
  508. if (!AMDLoader.Utilities.isAbsolutePath(results[i])) {
  509. results[i] = this.options.baseUrl + results[i];
  510. }
  511. if (!AMDLoader.Utilities.endsWith(results[i], '.js') && !AMDLoader.Utilities.containsQueryString(results[i])) {
  512. results[i] = results[i] + '.js';
  513. }
  514. }
  515. }
  516. else {
  517. if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.containsQueryString(result)) {
  518. result = result + '.js';
  519. }
  520. results = [result];
  521. }
  522. return this._addUrlArgsIfNecessaryToUrls(results);
  523. };
  524. /**
  525. * Transform a module id or url to a location.
  526. */
  527. Configuration.prototype.requireToUrl = function (url) {
  528. var result = url;
  529. if (!AMDLoader.Utilities.isAbsolutePath(result)) {
  530. result = this._applyPaths(result)[0];
  531. if (!AMDLoader.Utilities.isAbsolutePath(result)) {
  532. result = this.options.baseUrl + result;
  533. }
  534. }
  535. return this._addUrlArgsIfNecessaryToUrl(result);
  536. };
  537. /**
  538. * Flag to indicate if current execution is as part of a build.
  539. */
  540. Configuration.prototype.isBuild = function () {
  541. return this.options.isBuild;
  542. };
  543. /**
  544. * Test if module `moduleId` is expected to be defined multiple times
  545. */
  546. Configuration.prototype.isDuplicateMessageIgnoredFor = function (moduleId) {
  547. return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId);
  548. };
  549. /**
  550. * Get the configuration settings for the provided module id
  551. */
  552. Configuration.prototype.getConfigForModule = function (moduleId) {
  553. if (this.options.config) {
  554. return this.options.config[moduleId];
  555. }
  556. };
  557. /**
  558. * Should errors be caught when executing module factories?
  559. */
  560. Configuration.prototype.shouldCatchError = function () {
  561. return this.options.catchError;
  562. };
  563. /**
  564. * Should statistics be recorded?
  565. */
  566. Configuration.prototype.shouldRecordStats = function () {
  567. return this.options.recordStats;
  568. };
  569. /**
  570. * Forward an error to the error handler.
  571. */
  572. Configuration.prototype.onError = function (err) {
  573. this.options.onError(err);
  574. };
  575. return Configuration;
  576. }());
  577. AMDLoader.Configuration = Configuration;
  578. })(AMDLoader || (AMDLoader = {}));
  579. /*---------------------------------------------------------------------------------------------
  580. * Copyright (c) Microsoft Corporation. All rights reserved.
  581. * Licensed under the MIT License. See License.txt in the project root for license information.
  582. *--------------------------------------------------------------------------------------------*/
  583. var AMDLoader;
  584. (function (AMDLoader) {
  585. /**
  586. * Load `scriptSrc` only once (avoid multiple <script> tags)
  587. */
  588. var OnlyOnceScriptLoader = /** @class */ (function () {
  589. function OnlyOnceScriptLoader(env) {
  590. this._env = env;
  591. this._scriptLoader = null;
  592. this._callbackMap = {};
  593. }
  594. OnlyOnceScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
  595. var _this = this;
  596. if (!this._scriptLoader) {
  597. if (this._env.isWebWorker) {
  598. this._scriptLoader = new WorkerScriptLoader();
  599. }
  600. else if (this._env.isElectronRenderer) {
  601. var preferScriptTags = moduleManager.getConfig().getOptionsLiteral().preferScriptTags;
  602. if (preferScriptTags) {
  603. this._scriptLoader = new BrowserScriptLoader();
  604. }
  605. else {
  606. this._scriptLoader = new NodeScriptLoader(this._env);
  607. }
  608. }
  609. else if (this._env.isNode) {
  610. this._scriptLoader = new NodeScriptLoader(this._env);
  611. }
  612. else {
  613. this._scriptLoader = new BrowserScriptLoader();
  614. }
  615. }
  616. var scriptCallbacks = {
  617. callback: callback,
  618. errorback: errorback
  619. };
  620. if (this._callbackMap.hasOwnProperty(scriptSrc)) {
  621. this._callbackMap[scriptSrc].push(scriptCallbacks);
  622. return;
  623. }
  624. this._callbackMap[scriptSrc] = [scriptCallbacks];
  625. this._scriptLoader.load(moduleManager, scriptSrc, function () { return _this.triggerCallback(scriptSrc); }, function (err) { return _this.triggerErrorback(scriptSrc, err); });
  626. };
  627. OnlyOnceScriptLoader.prototype.triggerCallback = function (scriptSrc) {
  628. var scriptCallbacks = this._callbackMap[scriptSrc];
  629. delete this._callbackMap[scriptSrc];
  630. for (var i = 0; i < scriptCallbacks.length; i++) {
  631. scriptCallbacks[i].callback();
  632. }
  633. };
  634. OnlyOnceScriptLoader.prototype.triggerErrorback = function (scriptSrc, err) {
  635. var scriptCallbacks = this._callbackMap[scriptSrc];
  636. delete this._callbackMap[scriptSrc];
  637. for (var i = 0; i < scriptCallbacks.length; i++) {
  638. scriptCallbacks[i].errorback(err);
  639. }
  640. };
  641. return OnlyOnceScriptLoader;
  642. }());
  643. var BrowserScriptLoader = /** @class */ (function () {
  644. function BrowserScriptLoader() {
  645. }
  646. /**
  647. * Attach load / error listeners to a script element and remove them when either one has fired.
  648. * Implemented for browsers supporting HTML5 standard 'load' and 'error' events.
  649. */
  650. BrowserScriptLoader.prototype.attachListeners = function (script, callback, errorback) {
  651. var unbind = function () {
  652. script.removeEventListener('load', loadEventListener);
  653. script.removeEventListener('error', errorEventListener);
  654. };
  655. var loadEventListener = function (e) {
  656. unbind();
  657. callback();
  658. };
  659. var errorEventListener = function (e) {
  660. unbind();
  661. errorback(e);
  662. };
  663. script.addEventListener('load', loadEventListener);
  664. script.addEventListener('error', errorEventListener);
  665. };
  666. BrowserScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
  667. if (/^node\|/.test(scriptSrc)) {
  668. var opts = moduleManager.getConfig().getOptionsLiteral();
  669. var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
  670. var pieces = scriptSrc.split('|');
  671. var moduleExports_1 = null;
  672. try {
  673. moduleExports_1 = nodeRequire(pieces[1]);
  674. }
  675. catch (err) {
  676. errorback(err);
  677. return;
  678. }
  679. moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_1; });
  680. callback();
  681. }
  682. else {
  683. var script = document.createElement('script');
  684. script.setAttribute('async', 'async');
  685. script.setAttribute('type', 'text/javascript');
  686. this.attachListeners(script, callback, errorback);
  687. var trustedTypesPolicy = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy;
  688. if (trustedTypesPolicy) {
  689. scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc);
  690. }
  691. script.setAttribute('src', scriptSrc);
  692. // Propagate CSP nonce to dynamically created script tag.
  693. var cspNonce = moduleManager.getConfig().getOptionsLiteral().cspNonce;
  694. if (cspNonce) {
  695. script.setAttribute('nonce', cspNonce);
  696. }
  697. document.getElementsByTagName('head')[0].appendChild(script);
  698. }
  699. };
  700. return BrowserScriptLoader;
  701. }());
  702. function canUseEval(moduleManager) {
  703. var trustedTypesPolicy = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy;
  704. try {
  705. var func = (trustedTypesPolicy
  706. ? self.eval(trustedTypesPolicy.createScript('', 'true'))
  707. : new Function('true'));
  708. func.call(self);
  709. return true;
  710. }
  711. catch (err) {
  712. return false;
  713. }
  714. }
  715. var WorkerScriptLoader = /** @class */ (function () {
  716. function WorkerScriptLoader() {
  717. this._cachedCanUseEval = null;
  718. }
  719. WorkerScriptLoader.prototype._canUseEval = function (moduleManager) {
  720. if (this._cachedCanUseEval === null) {
  721. this._cachedCanUseEval = canUseEval(moduleManager);
  722. }
  723. return this._cachedCanUseEval;
  724. };
  725. WorkerScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
  726. if (/^node\|/.test(scriptSrc)) {
  727. var opts = moduleManager.getConfig().getOptionsLiteral();
  728. var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
  729. var pieces = scriptSrc.split('|');
  730. var moduleExports_2 = null;
  731. try {
  732. moduleExports_2 = nodeRequire(pieces[1]);
  733. }
  734. catch (err) {
  735. errorback(err);
  736. return;
  737. }
  738. moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_2; });
  739. callback();
  740. }
  741. else {
  742. var trustedTypesPolicy_1 = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy;
  743. var isCrossOrigin = (/^((http:)|(https:)|(file:))/.test(scriptSrc) && scriptSrc.substring(0, self.origin.length) !== self.origin);
  744. if (!isCrossOrigin && this._canUseEval(moduleManager)) {
  745. // use `fetch` if possible because `importScripts`
  746. // is synchronous and can lead to deadlocks on Safari
  747. fetch(scriptSrc).then(function (response) {
  748. if (response.status !== 200) {
  749. throw new Error(response.statusText);
  750. }
  751. return response.text();
  752. }).then(function (text) {
  753. text = text + "\n//# sourceURL=" + scriptSrc;
  754. var func = (trustedTypesPolicy_1
  755. ? self.eval(trustedTypesPolicy_1.createScript('', text))
  756. : new Function(text));
  757. func.call(self);
  758. callback();
  759. }).then(undefined, errorback);
  760. return;
  761. }
  762. try {
  763. if (trustedTypesPolicy_1) {
  764. scriptSrc = trustedTypesPolicy_1.createScriptURL(scriptSrc);
  765. }
  766. importScripts(scriptSrc);
  767. callback();
  768. }
  769. catch (e) {
  770. errorback(e);
  771. }
  772. }
  773. };
  774. return WorkerScriptLoader;
  775. }());
  776. var NodeScriptLoader = /** @class */ (function () {
  777. function NodeScriptLoader(env) {
  778. this._env = env;
  779. this._didInitialize = false;
  780. this._didPatchNodeRequire = false;
  781. }
  782. NodeScriptLoader.prototype._init = function (nodeRequire) {
  783. if (this._didInitialize) {
  784. return;
  785. }
  786. this._didInitialize = true;
  787. // capture node modules
  788. this._fs = nodeRequire('fs');
  789. this._vm = nodeRequire('vm');
  790. this._path = nodeRequire('path');
  791. this._crypto = nodeRequire('crypto');
  792. };
  793. // patch require-function of nodejs such that we can manually create a script
  794. // from cached data. this is done by overriding the `Module._compile` function
  795. NodeScriptLoader.prototype._initNodeRequire = function (nodeRequire, moduleManager) {
  796. // It is important to check for `nodeCachedData` first and then set `_didPatchNodeRequire`.
  797. // That's because `nodeCachedData` is set _after_ calling this for the first time...
  798. var nodeCachedData = moduleManager.getConfig().getOptionsLiteral().nodeCachedData;
  799. if (!nodeCachedData) {
  800. return;
  801. }
  802. if (this._didPatchNodeRequire) {
  803. return;
  804. }
  805. this._didPatchNodeRequire = true;
  806. var that = this;
  807. var Module = nodeRequire('module');
  808. function makeRequireFunction(mod) {
  809. var Module = mod.constructor;
  810. var require = function require(path) {
  811. try {
  812. return mod.require(path);
  813. }
  814. finally {
  815. // nothing
  816. }
  817. };
  818. require.resolve = function resolve(request, options) {
  819. return Module._resolveFilename(request, mod, false, options);
  820. };
  821. require.resolve.paths = function paths(request) {
  822. return Module._resolveLookupPaths(request, mod);
  823. };
  824. require.main = process.mainModule;
  825. require.extensions = Module._extensions;
  826. require.cache = Module._cache;
  827. return require;
  828. }
  829. Module.prototype._compile = function (content, filename) {
  830. // remove shebang and create wrapper function
  831. var scriptSource = Module.wrap(content.replace(/^#!.*/, ''));
  832. // create script
  833. var recorder = moduleManager.getRecorder();
  834. var cachedDataPath = that._getCachedDataPath(nodeCachedData, filename);
  835. var options = { filename: filename };
  836. var hashData;
  837. try {
  838. var data = that._fs.readFileSync(cachedDataPath);
  839. hashData = data.slice(0, 16);
  840. options.cachedData = data.slice(16);
  841. recorder.record(60 /* CachedDataFound */, cachedDataPath);
  842. }
  843. catch (_e) {
  844. recorder.record(61 /* CachedDataMissed */, cachedDataPath);
  845. }
  846. var script = new that._vm.Script(scriptSource, options);
  847. var compileWrapper = script.runInThisContext(options);
  848. // run script
  849. var dirname = that._path.dirname(filename);
  850. var require = makeRequireFunction(this);
  851. var args = [this.exports, require, this, filename, dirname, process, _commonjsGlobal, Buffer];
  852. var result = compileWrapper.apply(this.exports, args);
  853. // cached data aftermath
  854. that._handleCachedData(script, scriptSource, cachedDataPath, !options.cachedData, moduleManager);
  855. that._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager);
  856. return result;
  857. };
  858. };
  859. NodeScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
  860. var _this = this;
  861. var opts = moduleManager.getConfig().getOptionsLiteral();
  862. var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire));
  863. var nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; });
  864. this._init(nodeRequire);
  865. this._initNodeRequire(nodeRequire, moduleManager);
  866. var recorder = moduleManager.getRecorder();
  867. if (/^node\|/.test(scriptSrc)) {
  868. var pieces = scriptSrc.split('|');
  869. var moduleExports_3 = null;
  870. try {
  871. moduleExports_3 = nodeRequire(pieces[1]);
  872. }
  873. catch (err) {
  874. errorback(err);
  875. return;
  876. }
  877. moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_3; });
  878. callback();
  879. }
  880. else {
  881. scriptSrc = AMDLoader.Utilities.fileUriToFilePath(this._env.isWindows, scriptSrc);
  882. var normalizedScriptSrc_1 = this._path.normalize(scriptSrc);
  883. var vmScriptPathOrUri_1 = this._getElectronRendererScriptPathOrUri(normalizedScriptSrc_1);
  884. var wantsCachedData_1 = Boolean(opts.nodeCachedData);
  885. var cachedDataPath_1 = wantsCachedData_1 ? this._getCachedDataPath(opts.nodeCachedData, scriptSrc) : undefined;
  886. this._readSourceAndCachedData(normalizedScriptSrc_1, cachedDataPath_1, recorder, function (err, data, cachedData, hashData) {
  887. if (err) {
  888. errorback(err);
  889. return;
  890. }
  891. var scriptSource;
  892. if (data.charCodeAt(0) === NodeScriptLoader._BOM) {
  893. scriptSource = NodeScriptLoader._PREFIX + data.substring(1) + NodeScriptLoader._SUFFIX;
  894. }
  895. else {
  896. scriptSource = NodeScriptLoader._PREFIX + data + NodeScriptLoader._SUFFIX;
  897. }
  898. scriptSource = nodeInstrumenter(scriptSource, normalizedScriptSrc_1);
  899. var scriptOpts = { filename: vmScriptPathOrUri_1, cachedData: cachedData };
  900. var script = _this._createAndEvalScript(moduleManager, scriptSource, scriptOpts, callback, errorback);
  901. _this._handleCachedData(script, scriptSource, cachedDataPath_1, wantsCachedData_1 && !cachedData, moduleManager);
  902. _this._verifyCachedData(script, scriptSource, cachedDataPath_1, hashData, moduleManager);
  903. });
  904. }
  905. };
  906. NodeScriptLoader.prototype._createAndEvalScript = function (moduleManager, contents, options, callback, errorback) {
  907. var recorder = moduleManager.getRecorder();
  908. recorder.record(31 /* NodeBeginEvaluatingScript */, options.filename);
  909. var script = new this._vm.Script(contents, options);
  910. var ret = script.runInThisContext(options);
  911. var globalDefineFunc = moduleManager.getGlobalAMDDefineFunc();
  912. var receivedDefineCall = false;
  913. var localDefineFunc = function () {
  914. receivedDefineCall = true;
  915. return globalDefineFunc.apply(null, arguments);
  916. };
  917. localDefineFunc.amd = globalDefineFunc.amd;
  918. ret.call(AMDLoader.global, moduleManager.getGlobalAMDRequireFunc(), localDefineFunc, options.filename, this._path.dirname(options.filename));
  919. recorder.record(32 /* NodeEndEvaluatingScript */, options.filename);
  920. if (receivedDefineCall) {
  921. callback();
  922. }
  923. else {
  924. errorback(new Error("Didn't receive define call in " + options.filename + "!"));
  925. }
  926. return script;
  927. };
  928. NodeScriptLoader.prototype._getElectronRendererScriptPathOrUri = function (path) {
  929. if (!this._env.isElectronRenderer) {
  930. return path;
  931. }
  932. var driveLetterMatch = path.match(/^([a-z])\:(.*)/i);
  933. if (driveLetterMatch) {
  934. // windows
  935. return "file:///" + (driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2]).replace(/\\/g, '/');
  936. }
  937. else {
  938. // nix
  939. return "file://" + path;
  940. }
  941. };
  942. NodeScriptLoader.prototype._getCachedDataPath = function (config, filename) {
  943. var hash = this._crypto.createHash('md5').update(filename, 'utf8').update(config.seed, 'utf8').update(process.arch, '').digest('hex');
  944. var basename = this._path.basename(filename).replace(/\.js$/, '');
  945. return this._path.join(config.path, basename + "-" + hash + ".code");
  946. };
  947. NodeScriptLoader.prototype._handleCachedData = function (script, scriptSource, cachedDataPath, createCachedData, moduleManager) {
  948. var _this = this;
  949. if (script.cachedDataRejected) {
  950. // cached data got rejected -> delete and re-create
  951. this._fs.unlink(cachedDataPath, function (err) {
  952. moduleManager.getRecorder().record(62 /* CachedDataRejected */, cachedDataPath);
  953. _this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
  954. if (err) {
  955. moduleManager.getConfig().onError(err);
  956. }
  957. });
  958. }
  959. else if (createCachedData) {
  960. // no cached data, but wanted
  961. this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager);
  962. }
  963. };
  964. // Cached data format: | SOURCE_HASH | V8_CACHED_DATA |
  965. // -SOURCE_HASH is the md5 hash of the JS source (always 16 bytes)
  966. // -V8_CACHED_DATA is what v8 produces
  967. NodeScriptLoader.prototype._createAndWriteCachedData = function (script, scriptSource, cachedDataPath, moduleManager) {
  968. var _this = this;
  969. var timeout = Math.ceil(moduleManager.getConfig().getOptionsLiteral().nodeCachedData.writeDelay * (1 + Math.random()));
  970. var lastSize = -1;
  971. var iteration = 0;
  972. var hashData = undefined;
  973. var createLoop = function () {
  974. setTimeout(function () {
  975. if (!hashData) {
  976. hashData = _this._crypto.createHash('md5').update(scriptSource, 'utf8').digest();
  977. }
  978. var cachedData = script.createCachedData();
  979. if (cachedData.length === 0 || cachedData.length === lastSize || iteration >= 5) {
  980. // done
  981. return;
  982. }
  983. if (cachedData.length < lastSize) {
  984. // less data than before: skip, try again next round
  985. createLoop();
  986. return;
  987. }
  988. lastSize = cachedData.length;
  989. _this._fs.writeFile(cachedDataPath, Buffer.concat([hashData, cachedData]), function (err) {
  990. if (err) {
  991. moduleManager.getConfig().onError(err);
  992. }
  993. moduleManager.getRecorder().record(63 /* CachedDataCreated */, cachedDataPath);
  994. createLoop();
  995. });
  996. }, timeout * (Math.pow(4, iteration++)));
  997. };
  998. // with some delay (`timeout`) create cached data
  999. // and repeat that (with backoff delay) until the
  1000. // data seems to be not changing anymore
  1001. createLoop();
  1002. };
  1003. NodeScriptLoader.prototype._readSourceAndCachedData = function (sourcePath, cachedDataPath, recorder, callback) {
  1004. if (!cachedDataPath) {
  1005. // no cached data case
  1006. this._fs.readFile(sourcePath, { encoding: 'utf8' }, callback);
  1007. }
  1008. else {
  1009. // cached data case: read both files in parallel
  1010. var source_1 = undefined;
  1011. var cachedData_1 = undefined;
  1012. var hashData_1 = undefined;
  1013. var steps_1 = 2;
  1014. var step_1 = function (err) {
  1015. if (err) {
  1016. callback(err);
  1017. }
  1018. else if (--steps_1 === 0) {
  1019. callback(undefined, source_1, cachedData_1, hashData_1);
  1020. }
  1021. };
  1022. this._fs.readFile(sourcePath, { encoding: 'utf8' }, function (err, data) {
  1023. source_1 = data;
  1024. step_1(err);
  1025. });
  1026. this._fs.readFile(cachedDataPath, function (err, data) {
  1027. if (!err && data && data.length > 0) {
  1028. hashData_1 = data.slice(0, 16);
  1029. cachedData_1 = data.slice(16);
  1030. recorder.record(60 /* CachedDataFound */, cachedDataPath);
  1031. }
  1032. else {
  1033. recorder.record(61 /* CachedDataMissed */, cachedDataPath);
  1034. }
  1035. step_1(); // ignored: cached data is optional
  1036. });
  1037. }
  1038. };
  1039. NodeScriptLoader.prototype._verifyCachedData = function (script, scriptSource, cachedDataPath, hashData, moduleManager) {
  1040. var _this = this;
  1041. if (!hashData) {
  1042. // nothing to do
  1043. return;
  1044. }
  1045. if (script.cachedDataRejected) {
  1046. // invalid anyways
  1047. return;
  1048. }
  1049. setTimeout(function () {
  1050. // check source hash - the contract is that file paths change when file content
  1051. // change (e.g use the commit or version id as cache path). this check is
  1052. // for violations of this contract.
  1053. var hashDataNow = _this._crypto.createHash('md5').update(scriptSource, 'utf8').digest();
  1054. if (!hashData.equals(hashDataNow)) {
  1055. moduleManager.getConfig().onError(new Error("FAILED TO VERIFY CACHED DATA, deleting stale '" + cachedDataPath + "' now, but a RESTART IS REQUIRED"));
  1056. _this._fs.unlink(cachedDataPath, function (err) {
  1057. if (err) {
  1058. moduleManager.getConfig().onError(err);
  1059. }
  1060. });
  1061. }
  1062. }, Math.ceil(5000 * (1 + Math.random())));
  1063. };
  1064. NodeScriptLoader._BOM = 0xFEFF;
  1065. NodeScriptLoader._PREFIX = '(function (require, define, __filename, __dirname) { ';
  1066. NodeScriptLoader._SUFFIX = '\n});';
  1067. return NodeScriptLoader;
  1068. }());
  1069. function ensureRecordedNodeRequire(recorder, _nodeRequire) {
  1070. if (_nodeRequire.__$__isRecorded) {
  1071. // it is already recorded
  1072. return _nodeRequire;
  1073. }
  1074. var nodeRequire = function nodeRequire(what) {
  1075. recorder.record(33 /* NodeBeginNativeRequire */, what);
  1076. try {
  1077. return _nodeRequire(what);
  1078. }
  1079. finally {
  1080. recorder.record(34 /* NodeEndNativeRequire */, what);
  1081. }
  1082. };
  1083. nodeRequire.__$__isRecorded = true;
  1084. return nodeRequire;
  1085. }
  1086. AMDLoader.ensureRecordedNodeRequire = ensureRecordedNodeRequire;
  1087. function createScriptLoader(env) {
  1088. return new OnlyOnceScriptLoader(env);
  1089. }
  1090. AMDLoader.createScriptLoader = createScriptLoader;
  1091. })(AMDLoader || (AMDLoader = {}));
  1092. /*---------------------------------------------------------------------------------------------
  1093. * Copyright (c) Microsoft Corporation. All rights reserved.
  1094. * Licensed under the MIT License. See License.txt in the project root for license information.
  1095. *--------------------------------------------------------------------------------------------*/
  1096. var AMDLoader;
  1097. (function (AMDLoader) {
  1098. // ------------------------------------------------------------------------
  1099. // ModuleIdResolver
  1100. var ModuleIdResolver = /** @class */ (function () {
  1101. function ModuleIdResolver(fromModuleId) {
  1102. var lastSlash = fromModuleId.lastIndexOf('/');
  1103. if (lastSlash !== -1) {
  1104. this.fromModulePath = fromModuleId.substr(0, lastSlash + 1);
  1105. }
  1106. else {
  1107. this.fromModulePath = '';
  1108. }
  1109. }
  1110. /**
  1111. * Normalize 'a/../name' to 'name', etc.
  1112. */
  1113. ModuleIdResolver._normalizeModuleId = function (moduleId) {
  1114. var r = moduleId, pattern;
  1115. // replace /./ => /
  1116. pattern = /\/\.\//;
  1117. while (pattern.test(r)) {
  1118. r = r.replace(pattern, '/');
  1119. }
  1120. // replace ^./ => nothing
  1121. r = r.replace(/^\.\//g, '');
  1122. // replace /aa/../ => / (BUT IGNORE /../../)
  1123. pattern = /\/(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//;
  1124. while (pattern.test(r)) {
  1125. r = r.replace(pattern, '/');
  1126. }
  1127. // replace ^aa/../ => nothing (BUT IGNORE ../../)
  1128. r = r.replace(/^(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//, '');
  1129. return r;
  1130. };
  1131. /**
  1132. * Resolve relative module ids
  1133. */
  1134. ModuleIdResolver.prototype.resolveModule = function (moduleId) {
  1135. var result = moduleId;
  1136. if (!AMDLoader.Utilities.isAbsolutePath(result)) {
  1137. if (AMDLoader.Utilities.startsWith(result, './') || AMDLoader.Utilities.startsWith(result, '../')) {
  1138. result = ModuleIdResolver._normalizeModuleId(this.fromModulePath + result);
  1139. }
  1140. }
  1141. return result;
  1142. };
  1143. ModuleIdResolver.ROOT = new ModuleIdResolver('');
  1144. return ModuleIdResolver;
  1145. }());
  1146. AMDLoader.ModuleIdResolver = ModuleIdResolver;
  1147. // ------------------------------------------------------------------------
  1148. // Module
  1149. var Module = /** @class */ (function () {
  1150. function Module(id, strId, dependencies, callback, errorback, moduleIdResolver) {
  1151. this.id = id;
  1152. this.strId = strId;
  1153. this.dependencies = dependencies;
  1154. this._callback = callback;
  1155. this._errorback = errorback;
  1156. this.moduleIdResolver = moduleIdResolver;
  1157. this.exports = {};
  1158. this.error = null;
  1159. this.exportsPassedIn = false;
  1160. this.unresolvedDependenciesCount = this.dependencies.length;
  1161. this._isComplete = false;
  1162. }
  1163. Module._safeInvokeFunction = function (callback, args) {
  1164. try {
  1165. return {
  1166. returnedValue: callback.apply(AMDLoader.global, args),
  1167. producedError: null
  1168. };
  1169. }
  1170. catch (e) {
  1171. return {
  1172. returnedValue: null,
  1173. producedError: e
  1174. };
  1175. }
  1176. };
  1177. Module._invokeFactory = function (config, strModuleId, callback, dependenciesValues) {
  1178. if (config.isBuild() && !AMDLoader.Utilities.isAnonymousModule(strModuleId)) {
  1179. return {
  1180. returnedValue: null,
  1181. producedError: null
  1182. };
  1183. }
  1184. if (config.shouldCatchError()) {
  1185. return this._safeInvokeFunction(callback, dependenciesValues);
  1186. }
  1187. return {
  1188. returnedValue: callback.apply(AMDLoader.global, dependenciesValues),
  1189. producedError: null
  1190. };
  1191. };
  1192. Module.prototype.complete = function (recorder, config, dependenciesValues) {
  1193. this._isComplete = true;
  1194. var producedError = null;
  1195. if (this._callback) {
  1196. if (typeof this._callback === 'function') {
  1197. recorder.record(21 /* BeginInvokeFactory */, this.strId);
  1198. var r = Module._invokeFactory(config, this.strId, this._callback, dependenciesValues);
  1199. producedError = r.producedError;
  1200. recorder.record(22 /* EndInvokeFactory */, this.strId);
  1201. if (!producedError && typeof r.returnedValue !== 'undefined' && (!this.exportsPassedIn || AMDLoader.Utilities.isEmpty(this.exports))) {
  1202. this.exports = r.returnedValue;
  1203. }
  1204. }
  1205. else {
  1206. this.exports = this._callback;
  1207. }
  1208. }
  1209. if (producedError) {
  1210. var err = AMDLoader.ensureError(producedError);
  1211. err.phase = 'factory';
  1212. err.moduleId = this.strId;
  1213. this.error = err;
  1214. config.onError(err);
  1215. }
  1216. this.dependencies = null;
  1217. this._callback = null;
  1218. this._errorback = null;
  1219. this.moduleIdResolver = null;
  1220. };
  1221. /**
  1222. * One of the direct dependencies or a transitive dependency has failed to load.
  1223. */
  1224. Module.prototype.onDependencyError = function (err) {
  1225. this._isComplete = true;
  1226. this.error = err;
  1227. if (this._errorback) {
  1228. this._errorback(err);
  1229. return true;
  1230. }
  1231. return false;
  1232. };
  1233. /**
  1234. * Is the current module complete?
  1235. */
  1236. Module.prototype.isComplete = function () {
  1237. return this._isComplete;
  1238. };
  1239. return Module;
  1240. }());
  1241. AMDLoader.Module = Module;
  1242. var ModuleIdProvider = /** @class */ (function () {
  1243. function ModuleIdProvider() {
  1244. this._nextId = 0;
  1245. this._strModuleIdToIntModuleId = new Map();
  1246. this._intModuleIdToStrModuleId = [];
  1247. // Ensure values 0, 1, 2 are assigned accordingly with ModuleId
  1248. this.getModuleId('exports');
  1249. this.getModuleId('module');
  1250. this.getModuleId('require');
  1251. }
  1252. ModuleIdProvider.prototype.getMaxModuleId = function () {
  1253. return this._nextId;
  1254. };
  1255. ModuleIdProvider.prototype.getModuleId = function (strModuleId) {
  1256. var id = this._strModuleIdToIntModuleId.get(strModuleId);
  1257. if (typeof id === 'undefined') {
  1258. id = this._nextId++;
  1259. this._strModuleIdToIntModuleId.set(strModuleId, id);
  1260. this._intModuleIdToStrModuleId[id] = strModuleId;
  1261. }
  1262. return id;
  1263. };
  1264. ModuleIdProvider.prototype.getStrModuleId = function (moduleId) {
  1265. return this._intModuleIdToStrModuleId[moduleId];
  1266. };
  1267. return ModuleIdProvider;
  1268. }());
  1269. var RegularDependency = /** @class */ (function () {
  1270. function RegularDependency(id) {
  1271. this.id = id;
  1272. }
  1273. RegularDependency.EXPORTS = new RegularDependency(0 /* EXPORTS */);
  1274. RegularDependency.MODULE = new RegularDependency(1 /* MODULE */);
  1275. RegularDependency.REQUIRE = new RegularDependency(2 /* REQUIRE */);
  1276. return RegularDependency;
  1277. }());
  1278. AMDLoader.RegularDependency = RegularDependency;
  1279. var PluginDependency = /** @class */ (function () {
  1280. function PluginDependency(id, pluginId, pluginParam) {
  1281. this.id = id;
  1282. this.pluginId = pluginId;
  1283. this.pluginParam = pluginParam;
  1284. }
  1285. return PluginDependency;
  1286. }());
  1287. AMDLoader.PluginDependency = PluginDependency;
  1288. var ModuleManager = /** @class */ (function () {
  1289. function ModuleManager(env, scriptLoader, defineFunc, requireFunc, loaderAvailableTimestamp) {
  1290. if (loaderAvailableTimestamp === void 0) { loaderAvailableTimestamp = 0; }
  1291. this._env = env;
  1292. this._scriptLoader = scriptLoader;
  1293. this._loaderAvailableTimestamp = loaderAvailableTimestamp;
  1294. this._defineFunc = defineFunc;
  1295. this._requireFunc = requireFunc;
  1296. this._moduleIdProvider = new ModuleIdProvider();
  1297. this._config = new AMDLoader.Configuration(this._env);
  1298. this._hasDependencyCycle = false;
  1299. this._modules2 = [];
  1300. this._knownModules2 = [];
  1301. this._inverseDependencies2 = [];
  1302. this._inversePluginDependencies2 = new Map();
  1303. this._currentAnonymousDefineCall = null;
  1304. this._recorder = null;
  1305. this._buildInfoPath = [];
  1306. this._buildInfoDefineStack = [];
  1307. this._buildInfoDependencies = [];
  1308. }
  1309. ModuleManager.prototype.reset = function () {
  1310. return new ModuleManager(this._env, this._scriptLoader, this._defineFunc, this._requireFunc, this._loaderAvailableTimestamp);
  1311. };
  1312. ModuleManager.prototype.getGlobalAMDDefineFunc = function () {
  1313. return this._defineFunc;
  1314. };
  1315. ModuleManager.prototype.getGlobalAMDRequireFunc = function () {
  1316. return this._requireFunc;
  1317. };
  1318. ModuleManager._findRelevantLocationInStack = function (needle, stack) {
  1319. var normalize = function (str) { return str.replace(/\\/g, '/'); };
  1320. var normalizedPath = normalize(needle);
  1321. var stackPieces = stack.split(/\n/);
  1322. for (var i = 0; i < stackPieces.length; i++) {
  1323. var m = stackPieces[i].match(/(.*):(\d+):(\d+)\)?$/);
  1324. if (m) {
  1325. var stackPath = m[1];
  1326. var stackLine = m[2];
  1327. var stackColumn = m[3];
  1328. var trimPathOffset = Math.max(stackPath.lastIndexOf(' ') + 1, stackPath.lastIndexOf('(') + 1);
  1329. stackPath = stackPath.substr(trimPathOffset);
  1330. stackPath = normalize(stackPath);
  1331. if (stackPath === normalizedPath) {
  1332. var r = {
  1333. line: parseInt(stackLine, 10),
  1334. col: parseInt(stackColumn, 10)
  1335. };
  1336. if (r.line === 1) {
  1337. r.col -= '(function (require, define, __filename, __dirname) { '.length;
  1338. }
  1339. return r;
  1340. }
  1341. }
  1342. }
  1343. throw new Error('Could not correlate define call site for needle ' + needle);
  1344. };
  1345. ModuleManager.prototype.getBuildInfo = function () {
  1346. if (!this._config.isBuild()) {
  1347. return null;
  1348. }
  1349. var result = [], resultLen = 0;
  1350. for (var i = 0, len = this._modules2.length; i < len; i++) {
  1351. var m = this._modules2[i];
  1352. if (!m) {
  1353. continue;
  1354. }
  1355. var location_1 = this._buildInfoPath[m.id] || null;
  1356. var defineStack = this._buildInfoDefineStack[m.id] || null;
  1357. var dependencies = this._buildInfoDependencies[m.id];
  1358. result[resultLen++] = {
  1359. id: m.strId,
  1360. path: location_1,
  1361. defineLocation: (location_1 && defineStack ? ModuleManager._findRelevantLocationInStack(location_1, defineStack) : null),
  1362. dependencies: dependencies,
  1363. shim: null,
  1364. exports: m.exports
  1365. };
  1366. }
  1367. return result;
  1368. };
  1369. ModuleManager.prototype.getRecorder = function () {
  1370. if (!this._recorder) {
  1371. if (this._config.shouldRecordStats()) {
  1372. this._recorder = new AMDLoader.LoaderEventRecorder(this._loaderAvailableTimestamp);
  1373. }
  1374. else {
  1375. this._recorder = AMDLoader.NullLoaderEventRecorder.INSTANCE;
  1376. }
  1377. }
  1378. return this._recorder;
  1379. };
  1380. ModuleManager.prototype.getLoaderEvents = function () {
  1381. return this.getRecorder().getEvents();
  1382. };
  1383. /**
  1384. * Defines an anonymous module (without an id). Its name will be resolved as we receive a callback from the scriptLoader.
  1385. * @param dependencies @see defineModule
  1386. * @param callback @see defineModule
  1387. */
  1388. ModuleManager.prototype.enqueueDefineAnonymousModule = function (dependencies, callback) {
  1389. if (this._currentAnonymousDefineCall !== null) {
  1390. throw new Error('Can only have one anonymous define call per script file');
  1391. }
  1392. var stack = null;
  1393. if (this._config.isBuild()) {
  1394. stack = new Error('StackLocation').stack || null;
  1395. }
  1396. this._currentAnonymousDefineCall = {
  1397. stack: stack,
  1398. dependencies: dependencies,
  1399. callback: callback
  1400. };
  1401. };
  1402. /**
  1403. * Creates a module and stores it in _modules. The manager will immediately begin resolving its dependencies.
  1404. * @param strModuleId An unique and absolute id of the module. This must not collide with another module's id
  1405. * @param dependencies An array with the dependencies of the module. Special keys are: "require", "exports" and "module"
  1406. * @param callback if callback is a function, it will be called with the resolved dependencies. if callback is an object, it will be considered as the exports of the module.
  1407. */
  1408. ModuleManager.prototype.defineModule = function (strModuleId, dependencies, callback, errorback, stack, moduleIdResolver) {
  1409. var _this = this;
  1410. if (moduleIdResolver === void 0) { moduleIdResolver = new ModuleIdResolver(strModuleId); }
  1411. var moduleId = this._moduleIdProvider.getModuleId(strModuleId);
  1412. if (this._modules2[moduleId]) {
  1413. if (!this._config.isDuplicateMessageIgnoredFor(strModuleId)) {
  1414. console.warn('Duplicate definition of module \'' + strModuleId + '\'');
  1415. }
  1416. // Super important! Completely ignore duplicate module definition
  1417. return;
  1418. }
  1419. var m = new Module(moduleId, strModuleId, this._normalizeDependencies(dependencies, moduleIdResolver), callback, errorback, moduleIdResolver);
  1420. this._modules2[moduleId] = m;
  1421. if (this._config.isBuild()) {
  1422. this._buildInfoDefineStack[moduleId] = stack;
  1423. this._buildInfoDependencies[moduleId] = (m.dependencies || []).map(function (dep) { return _this._moduleIdProvider.getStrModuleId(dep.id); });
  1424. }
  1425. // Resolving of dependencies is immediate (not in a timeout). If there's a need to support a packer that concatenates in an
  1426. // unordered manner, in order to finish processing the file, execute the following method in a timeout
  1427. this._resolve(m);
  1428. };
  1429. ModuleManager.prototype._normalizeDependency = function (dependency, moduleIdResolver) {
  1430. if (dependency === 'exports') {
  1431. return RegularDependency.EXPORTS;
  1432. }
  1433. if (dependency === 'module') {
  1434. return RegularDependency.MODULE;
  1435. }
  1436. if (dependency === 'require') {
  1437. return RegularDependency.REQUIRE;
  1438. }
  1439. // Normalize dependency and then request it from the manager
  1440. var bangIndex = dependency.indexOf('!');
  1441. if (bangIndex >= 0) {
  1442. var strPluginId = moduleIdResolver.resolveModule(dependency.substr(0, bangIndex));
  1443. var pluginParam = moduleIdResolver.resolveModule(dependency.substr(bangIndex + 1));
  1444. var dependencyId = this._moduleIdProvider.getModuleId(strPluginId + '!' + pluginParam);
  1445. var pluginId = this._moduleIdProvider.getModuleId(strPluginId);
  1446. return new PluginDependency(dependencyId, pluginId, pluginParam);
  1447. }
  1448. return new RegularDependency(this._moduleIdProvider.getModuleId(moduleIdResolver.resolveModule(dependency)));
  1449. };
  1450. ModuleManager.prototype._normalizeDependencies = function (dependencies, moduleIdResolver) {
  1451. var result = [], resultLen = 0;
  1452. for (var i = 0, len = dependencies.length; i < len; i++) {
  1453. result[resultLen++] = this._normalizeDependency(dependencies[i], moduleIdResolver);
  1454. }
  1455. return result;
  1456. };
  1457. ModuleManager.prototype._relativeRequire = function (moduleIdResolver, dependencies, callback, errorback) {
  1458. if (typeof dependencies === 'string') {
  1459. return this.synchronousRequire(dependencies, moduleIdResolver);
  1460. }
  1461. this.defineModule(AMDLoader.Utilities.generateAnonymousModule(), dependencies, callback, errorback, null, moduleIdResolver);
  1462. };
  1463. /**
  1464. * Require synchronously a module by its absolute id. If the module is not loaded, an exception will be thrown.
  1465. * @param id The unique and absolute id of the required module
  1466. * @return The exports of module 'id'
  1467. */
  1468. ModuleManager.prototype.synchronousRequire = function (_strModuleId, moduleIdResolver) {
  1469. if (moduleIdResolver === void 0) { moduleIdResolver = new ModuleIdResolver(_strModuleId); }
  1470. var dependency = this._normalizeDependency(_strModuleId, moduleIdResolver);
  1471. var m = this._modules2[dependency.id];
  1472. if (!m) {
  1473. throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + _strModuleId + '\'. This is the first mention of this module!');
  1474. }
  1475. if (!m.isComplete()) {
  1476. throw new Error('Check dependency list! Synchronous require cannot resolve module \'' + _strModuleId + '\'. This module has not been resolved completely yet.');
  1477. }
  1478. if (m.error) {
  1479. throw m.error;
  1480. }
  1481. return m.exports;
  1482. };
  1483. ModuleManager.prototype.configure = function (params, shouldOverwrite) {
  1484. var oldShouldRecordStats = this._config.shouldRecordStats();
  1485. if (shouldOverwrite) {
  1486. this._config = new AMDLoader.Configuration(this._env, params);
  1487. }
  1488. else {
  1489. this._config = this._config.cloneAndMerge(params);
  1490. }
  1491. if (this._config.shouldRecordStats() && !oldShouldRecordStats) {
  1492. this._recorder = null;
  1493. }
  1494. };
  1495. ModuleManager.prototype.getConfig = function () {
  1496. return this._config;
  1497. };
  1498. /**
  1499. * Callback from the scriptLoader when a module has been loaded.
  1500. * This means its code is available and has been executed.
  1501. */
  1502. ModuleManager.prototype._onLoad = function (moduleId) {
  1503. if (this._currentAnonymousDefineCall !== null) {
  1504. var defineCall = this._currentAnonymousDefineCall;
  1505. this._currentAnonymousDefineCall = null;
  1506. // Hit an anonymous define call
  1507. this.defineModule(this._moduleIdProvider.getStrModuleId(moduleId), defineCall.dependencies, defineCall.callback, null, defineCall.stack);
  1508. }
  1509. };
  1510. ModuleManager.prototype._createLoadError = function (moduleId, _err) {
  1511. var _this = this;
  1512. var strModuleId = this._moduleIdProvider.getStrModuleId(moduleId);
  1513. var neededBy = (this._inverseDependencies2[moduleId] || []).map(function (intModuleId) { return _this._moduleIdProvider.getStrModuleId(intModuleId); });
  1514. var err = AMDLoader.ensureError(_err);
  1515. err.phase = 'loading';
  1516. err.moduleId = strModuleId;
  1517. err.neededBy = neededBy;
  1518. return err;
  1519. };
  1520. /**
  1521. * Callback from the scriptLoader when a module hasn't been loaded.
  1522. * This means that the script was not found (e.g. 404) or there was an error in the script.
  1523. */
  1524. ModuleManager.prototype._onLoadError = function (moduleId, err) {
  1525. var error = this._createLoadError(moduleId, err);
  1526. if (!this._modules2[moduleId]) {
  1527. this._modules2[moduleId] = new Module(moduleId, this._moduleIdProvider.getStrModuleId(moduleId), [], function () { }, null, null);
  1528. }
  1529. // Find any 'local' error handlers, walk the entire chain of inverse dependencies if necessary.
  1530. var seenModuleId = [];
  1531. for (var i = 0, len = this._moduleIdProvider.getMaxModuleId(); i < len; i++) {
  1532. seenModuleId[i] = false;
  1533. }
  1534. var someoneNotified = false;
  1535. var queue = [];
  1536. queue.push(moduleId);
  1537. seenModuleId[moduleId] = true;
  1538. while (queue.length > 0) {
  1539. var queueElement = queue.shift();
  1540. var m = this._modules2[queueElement];
  1541. if (m) {
  1542. someoneNotified = m.onDependencyError(error) || someoneNotified;
  1543. }
  1544. var inverseDeps = this._inverseDependencies2[queueElement];
  1545. if (inverseDeps) {
  1546. for (var i = 0, len = inverseDeps.length; i < len; i++) {
  1547. var inverseDep = inverseDeps[i];
  1548. if (!seenModuleId[inverseDep]) {
  1549. queue.push(inverseDep);
  1550. seenModuleId[inverseDep] = true;
  1551. }
  1552. }
  1553. }
  1554. }
  1555. if (!someoneNotified) {
  1556. this._config.onError(error);
  1557. }
  1558. };
  1559. /**
  1560. * Walks (recursively) the dependencies of 'from' in search of 'to'.
  1561. * Returns true if there is such a path or false otherwise.
  1562. * @param from Module id to start at
  1563. * @param to Module id to look for
  1564. */
  1565. ModuleManager.prototype._hasDependencyPath = function (fromId, toId) {
  1566. var from = this._modules2[fromId];
  1567. if (!from) {
  1568. return false;
  1569. }
  1570. var inQueue = [];
  1571. for (var i = 0, len = this._moduleIdProvider.getMaxModuleId(); i < len; i++) {
  1572. inQueue[i] = false;
  1573. }
  1574. var queue = [];
  1575. // Insert 'from' in queue
  1576. queue.push(from);
  1577. inQueue[fromId] = true;
  1578. while (queue.length > 0) {
  1579. // Pop first inserted element of queue
  1580. var element = queue.shift();
  1581. var dependencies = element.dependencies;
  1582. if (dependencies) {
  1583. // Walk the element's dependencies
  1584. for (var i = 0, len = dependencies.length; i < len; i++) {
  1585. var dependency = dependencies[i];
  1586. if (dependency.id === toId) {
  1587. // There is a path to 'to'
  1588. return true;
  1589. }
  1590. var dependencyModule = this._modules2[dependency.id];
  1591. if (dependencyModule && !inQueue[dependency.id]) {
  1592. // Insert 'dependency' in queue
  1593. inQueue[dependency.id] = true;
  1594. queue.push(dependencyModule);
  1595. }
  1596. }
  1597. }
  1598. }
  1599. // There is no path to 'to'
  1600. return false;
  1601. };
  1602. /**
  1603. * Walks (recursively) the dependencies of 'from' in search of 'to'.
  1604. * Returns cycle as array.
  1605. * @param from Module id to start at
  1606. * @param to Module id to look for
  1607. */
  1608. ModuleManager.prototype._findCyclePath = function (fromId, toId, depth) {
  1609. if (fromId === toId || depth === 50) {
  1610. return [fromId];
  1611. }
  1612. var from = this._modules2[fromId];
  1613. if (!from) {
  1614. return null;
  1615. }
  1616. // Walk the element's dependencies
  1617. var dependencies = from.dependencies;
  1618. if (dependencies) {
  1619. for (var i = 0, len = dependencies.length; i < len; i++) {
  1620. var path = this._findCyclePath(dependencies[i].id, toId, depth + 1);
  1621. if (path !== null) {
  1622. path.push(fromId);
  1623. return path;
  1624. }
  1625. }
  1626. }
  1627. return null;
  1628. };
  1629. /**
  1630. * Create the local 'require' that is passed into modules
  1631. */
  1632. ModuleManager.prototype._createRequire = function (moduleIdResolver) {
  1633. var _this = this;
  1634. var result = (function (dependencies, callback, errorback) {
  1635. return _this._relativeRequire(moduleIdResolver, dependencies, callback, errorback);
  1636. });
  1637. result.toUrl = function (id) {
  1638. return _this._config.requireToUrl(moduleIdResolver.resolveModule(id));
  1639. };
  1640. result.getStats = function () {
  1641. return _this.getLoaderEvents();
  1642. };
  1643. result.hasDependencyCycle = function () {
  1644. return _this._hasDependencyCycle;
  1645. };
  1646. result.config = function (params, shouldOverwrite) {
  1647. if (shouldOverwrite === void 0) { shouldOverwrite = false; }
  1648. _this.configure(params, shouldOverwrite);
  1649. };
  1650. result.__$__nodeRequire = AMDLoader.global.nodeRequire;
  1651. return result;
  1652. };
  1653. ModuleManager.prototype._loadModule = function (moduleId) {
  1654. var _this = this;
  1655. if (this._modules2[moduleId] || this._knownModules2[moduleId]) {
  1656. // known module
  1657. return;
  1658. }
  1659. this._knownModules2[moduleId] = true;
  1660. var strModuleId = this._moduleIdProvider.getStrModuleId(moduleId);
  1661. var paths = this._config.moduleIdToPaths(strModuleId);
  1662. var scopedPackageRegex = /^@[^\/]+\/[^\/]+$/; // matches @scope/package-name
  1663. if (this._env.isNode && (strModuleId.indexOf('/') === -1 || scopedPackageRegex.test(strModuleId))) {
  1664. paths.push('node|' + strModuleId);
  1665. }
  1666. var lastPathIndex = -1;
  1667. var loadNextPath = function (err) {
  1668. lastPathIndex++;
  1669. if (lastPathIndex >= paths.length) {
  1670. // No more paths to try
  1671. _this._onLoadError(moduleId, err);
  1672. }
  1673. else {
  1674. var currentPath_1 = paths[lastPathIndex];
  1675. var recorder_1 = _this.getRecorder();
  1676. if (_this._config.isBuild() && currentPath_1 === 'empty:') {
  1677. _this._buildInfoPath[moduleId] = currentPath_1;
  1678. _this.defineModule(_this._moduleIdProvider.getStrModuleId(moduleId), [], null, null, null);
  1679. _this._onLoad(moduleId);
  1680. return;
  1681. }
  1682. recorder_1.record(10 /* BeginLoadingScript */, currentPath_1);
  1683. _this._scriptLoader.load(_this, currentPath_1, function () {
  1684. if (_this._config.isBuild()) {
  1685. _this._buildInfoPath[moduleId] = currentPath_1;
  1686. }
  1687. recorder_1.record(11 /* EndLoadingScriptOK */, currentPath_1);
  1688. _this._onLoad(moduleId);
  1689. }, function (err) {
  1690. recorder_1.record(12 /* EndLoadingScriptError */, currentPath_1);
  1691. loadNextPath(err);
  1692. });
  1693. }
  1694. };
  1695. loadNextPath(null);
  1696. };
  1697. /**
  1698. * Resolve a plugin dependency with the plugin loaded & complete
  1699. * @param module The module that has this dependency
  1700. * @param pluginDependency The semi-normalized dependency that appears in the module. e.g. 'vs/css!./mycssfile'. Only the plugin part (before !) is normalized
  1701. * @param plugin The plugin (what the plugin exports)
  1702. */
  1703. ModuleManager.prototype._loadPluginDependency = function (plugin, pluginDependency) {
  1704. var _this = this;
  1705. if (this._modules2[pluginDependency.id] || this._knownModules2[pluginDependency.id]) {
  1706. // known module
  1707. return;
  1708. }
  1709. this._knownModules2[pluginDependency.id] = true;
  1710. // Delegate the loading of the resource to the plugin
  1711. var load = (function (value) {
  1712. _this.defineModule(_this._moduleIdProvider.getStrModuleId(pluginDependency.id), [], value, null, null);
  1713. });
  1714. load.error = function (err) {
  1715. _this._config.onError(_this._createLoadError(pluginDependency.id, err));
  1716. };
  1717. plugin.load(pluginDependency.pluginParam, this._createRequire(ModuleIdResolver.ROOT), load, this._config.getOptionsLiteral());
  1718. };
  1719. /**
  1720. * Examine the dependencies of module 'module' and resolve them as needed.
  1721. */
  1722. ModuleManager.prototype._resolve = function (module) {
  1723. var _this = this;
  1724. var dependencies = module.dependencies;
  1725. if (dependencies) {
  1726. for (var i = 0, len = dependencies.length; i < len; i++) {
  1727. var dependency = dependencies[i];
  1728. if (dependency === RegularDependency.EXPORTS) {
  1729. module.exportsPassedIn = true;
  1730. module.unresolvedDependenciesCount--;
  1731. continue;
  1732. }
  1733. if (dependency === RegularDependency.MODULE) {
  1734. module.unresolvedDependenciesCount--;
  1735. continue;
  1736. }
  1737. if (dependency === RegularDependency.REQUIRE) {
  1738. module.unresolvedDependenciesCount--;
  1739. continue;
  1740. }
  1741. var dependencyModule = this._modules2[dependency.id];
  1742. if (dependencyModule && dependencyModule.isComplete()) {
  1743. if (dependencyModule.error) {
  1744. module.onDependencyError(dependencyModule.error);
  1745. return;
  1746. }
  1747. module.unresolvedDependenciesCount--;
  1748. continue;
  1749. }
  1750. if (this._hasDependencyPath(dependency.id, module.id)) {
  1751. this._hasDependencyCycle = true;
  1752. console.warn('There is a dependency cycle between \'' + this._moduleIdProvider.getStrModuleId(dependency.id) + '\' and \'' + this._moduleIdProvider.getStrModuleId(module.id) + '\'. The cyclic path follows:');
  1753. var cyclePath = this._findCyclePath(dependency.id, module.id, 0) || [];
  1754. cyclePath.reverse();
  1755. cyclePath.push(dependency.id);
  1756. console.warn(cyclePath.map(function (id) { return _this._moduleIdProvider.getStrModuleId(id); }).join(' => \n'));
  1757. // Break the cycle
  1758. module.unresolvedDependenciesCount--;
  1759. continue;
  1760. }
  1761. // record inverse dependency
  1762. this._inverseDependencies2[dependency.id] = this._inverseDependencies2[dependency.id] || [];
  1763. this._inverseDependencies2[dependency.id].push(module.id);
  1764. if (dependency instanceof PluginDependency) {
  1765. var plugin = this._modules2[dependency.pluginId];
  1766. if (plugin && plugin.isComplete()) {
  1767. this._loadPluginDependency(plugin.exports, dependency);
  1768. continue;
  1769. }
  1770. // Record dependency for when the plugin gets loaded
  1771. var inversePluginDeps = this._inversePluginDependencies2.get(dependency.pluginId);
  1772. if (!inversePluginDeps) {
  1773. inversePluginDeps = [];
  1774. this._inversePluginDependencies2.set(dependency.pluginId, inversePluginDeps);
  1775. }
  1776. inversePluginDeps.push(dependency);
  1777. this._loadModule(dependency.pluginId);
  1778. continue;
  1779. }
  1780. this._loadModule(dependency.id);
  1781. }
  1782. }
  1783. if (module.unresolvedDependenciesCount === 0) {
  1784. this._onModuleComplete(module);
  1785. }
  1786. };
  1787. ModuleManager.prototype._onModuleComplete = function (module) {
  1788. var _this = this;
  1789. var recorder = this.getRecorder();
  1790. if (module.isComplete()) {
  1791. // already done
  1792. return;
  1793. }
  1794. var dependencies = module.dependencies;
  1795. var dependenciesValues = [];
  1796. if (dependencies) {
  1797. for (var i = 0, len = dependencies.length; i < len; i++) {
  1798. var dependency = dependencies[i];
  1799. if (dependency === RegularDependency.EXPORTS) {
  1800. dependenciesValues[i] = module.exports;
  1801. continue;
  1802. }
  1803. if (dependency === RegularDependency.MODULE) {
  1804. dependenciesValues[i] = {
  1805. id: module.strId,
  1806. config: function () {
  1807. return _this._config.getConfigForModule(module.strId);
  1808. }
  1809. };
  1810. continue;
  1811. }
  1812. if (dependency === RegularDependency.REQUIRE) {
  1813. dependenciesValues[i] = this._createRequire(module.moduleIdResolver);
  1814. continue;
  1815. }
  1816. var dependencyModule = this._modules2[dependency.id];
  1817. if (dependencyModule) {
  1818. dependenciesValues[i] = dependencyModule.exports;
  1819. continue;
  1820. }
  1821. dependenciesValues[i] = null;
  1822. }
  1823. }
  1824. module.complete(recorder, this._config, dependenciesValues);
  1825. // Fetch and clear inverse dependencies
  1826. var inverseDeps = this._inverseDependencies2[module.id];
  1827. this._inverseDependencies2[module.id] = null;
  1828. if (inverseDeps) {
  1829. // Resolve one inverse dependency at a time, always
  1830. // on the lookout for a completed module.
  1831. for (var i = 0, len = inverseDeps.length; i < len; i++) {
  1832. var inverseDependencyId = inverseDeps[i];
  1833. var inverseDependency = this._modules2[inverseDependencyId];
  1834. inverseDependency.unresolvedDependenciesCount--;
  1835. if (inverseDependency.unresolvedDependenciesCount === 0) {
  1836. this._onModuleComplete(inverseDependency);
  1837. }
  1838. }
  1839. }
  1840. var inversePluginDeps = this._inversePluginDependencies2.get(module.id);
  1841. if (inversePluginDeps) {
  1842. // This module is used as a plugin at least once
  1843. // Fetch and clear these inverse plugin dependencies
  1844. this._inversePluginDependencies2.delete(module.id);
  1845. // Resolve plugin dependencies one at a time
  1846. for (var i = 0, len = inversePluginDeps.length; i < len; i++) {
  1847. this._loadPluginDependency(module.exports, inversePluginDeps[i]);
  1848. }
  1849. }
  1850. };
  1851. return ModuleManager;
  1852. }());
  1853. AMDLoader.ModuleManager = ModuleManager;
  1854. })(AMDLoader || (AMDLoader = {}));
  1855. var define;
  1856. var AMDLoader;
  1857. (function (AMDLoader) {
  1858. var env = new AMDLoader.Environment();
  1859. var moduleManager = null;
  1860. var DefineFunc = function (id, dependencies, callback) {
  1861. if (typeof id !== 'string') {
  1862. callback = dependencies;
  1863. dependencies = id;
  1864. id = null;
  1865. }
  1866. if (typeof dependencies !== 'object' || !Array.isArray(dependencies)) {
  1867. callback = dependencies;
  1868. dependencies = null;
  1869. }
  1870. if (!dependencies) {
  1871. dependencies = ['require', 'exports', 'module'];
  1872. }
  1873. if (id) {
  1874. moduleManager.defineModule(id, dependencies, callback, null, null);
  1875. }
  1876. else {
  1877. moduleManager.enqueueDefineAnonymousModule(dependencies, callback);
  1878. }
  1879. };
  1880. DefineFunc.amd = {
  1881. jQuery: true
  1882. };
  1883. var _requireFunc_config = function (params, shouldOverwrite) {
  1884. if (shouldOverwrite === void 0) { shouldOverwrite = false; }
  1885. moduleManager.configure(params, shouldOverwrite);
  1886. };
  1887. var RequireFunc = function () {
  1888. if (arguments.length === 1) {
  1889. if ((arguments[0] instanceof Object) && !Array.isArray(arguments[0])) {
  1890. _requireFunc_config(arguments[0]);
  1891. return;
  1892. }
  1893. if (typeof arguments[0] === 'string') {
  1894. return moduleManager.synchronousRequire(arguments[0]);
  1895. }
  1896. }
  1897. if (arguments.length === 2 || arguments.length === 3) {
  1898. if (Array.isArray(arguments[0])) {
  1899. moduleManager.defineModule(AMDLoader.Utilities.generateAnonymousModule(), arguments[0], arguments[1], arguments[2], null);
  1900. return;
  1901. }
  1902. }
  1903. throw new Error('Unrecognized require call');
  1904. };
  1905. RequireFunc.config = _requireFunc_config;
  1906. RequireFunc.getConfig = function () {
  1907. return moduleManager.getConfig().getOptionsLiteral();
  1908. };
  1909. RequireFunc.reset = function () {
  1910. moduleManager = moduleManager.reset();
  1911. };
  1912. RequireFunc.getBuildInfo = function () {
  1913. return moduleManager.getBuildInfo();
  1914. };
  1915. RequireFunc.getStats = function () {
  1916. return moduleManager.getLoaderEvents();
  1917. };
  1918. RequireFunc.define = DefineFunc;
  1919. function init() {
  1920. if (typeof AMDLoader.global.require !== 'undefined' || typeof require !== 'undefined') {
  1921. var _nodeRequire = (AMDLoader.global.require || require);
  1922. if (typeof _nodeRequire === 'function' && typeof _nodeRequire.resolve === 'function') {
  1923. // re-expose node's require function
  1924. var nodeRequire = AMDLoader.ensureRecordedNodeRequire(moduleManager.getRecorder(), _nodeRequire);
  1925. AMDLoader.global.nodeRequire = nodeRequire;
  1926. RequireFunc.nodeRequire = nodeRequire;
  1927. RequireFunc.__$__nodeRequire = nodeRequire;
  1928. }
  1929. }
  1930. if (env.isNode && !env.isElectronRenderer && !env.isElectronNodeIntegrationWebWorker) {
  1931. module.exports = RequireFunc;
  1932. require = RequireFunc;
  1933. }
  1934. else {
  1935. if (!env.isElectronRenderer) {
  1936. AMDLoader.global.define = DefineFunc;
  1937. }
  1938. AMDLoader.global.require = RequireFunc;
  1939. }
  1940. }
  1941. AMDLoader.init = init;
  1942. if (typeof AMDLoader.global.define !== 'function' || !AMDLoader.global.define.amd) {
  1943. moduleManager = new AMDLoader.ModuleManager(env, AMDLoader.createScriptLoader(env), DefineFunc, RequireFunc, AMDLoader.Utilities.getHighPerformanceTimestamp());
  1944. // The global variable require can configure the loader
  1945. if (typeof AMDLoader.global.require !== 'undefined' && typeof AMDLoader.global.require !== 'function') {
  1946. RequireFunc.config(AMDLoader.global.require);
  1947. }
  1948. // This define is for the local closure defined in node in the case that the loader is concatenated
  1949. define = function () {
  1950. return DefineFunc.apply(null, arguments);
  1951. };
  1952. define.amd = DefineFunc.amd;
  1953. if (typeof doNotInitLoader === 'undefined') {
  1954. init();
  1955. }
  1956. }
  1957. })(AMDLoader || (AMDLoader = {}));