react-monaco-editor
Version:
Monaco Editor for React
1,076 lines (1,075 loc) • 79.5 kB
JavaScript
/*!-----------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.10.1(ebbf400719be21761361804bf63fb3916e64a845)
* Released under the MIT license
* https://github.com/Microsoft/vscode/blob/master/LICENSE.txt
*-----------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
* Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*---------------------------------------------------------------------------------------------
*--------------------------------------------------------------------------------------------*/
var _amdLoaderGlobal = this;
var AMDLoader;
(function (AMDLoader) {
AMDLoader.global = _amdLoaderGlobal;
var Environment = (function () {
function Environment(opts) {
this.isWindows = opts.isWindows;
this.isNode = opts.isNode;
this.isElectronRenderer = opts.isElectronRenderer;
this.isWebWorker = opts.isWebWorker;
}
Environment.detect = function () {
return new Environment({
isWindows: this._isWindows(),
isNode: (typeof module !== 'undefined' && !!module.exports),
isElectronRenderer: (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer'),
isWebWorker: (typeof AMDLoader.global.importScripts === 'function')
});
};
Environment._isWindows = function () {
if (typeof navigator !== 'undefined') {
if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) {
return true;
}
}
if (typeof process !== 'undefined') {
return (process.platform === 'win32');
}
return false;
};
return Environment;
}());
AMDLoader.Environment = Environment;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
var LoaderEventType;
(function (LoaderEventType) {
LoaderEventType[LoaderEventType["LoaderAvailable"] = 1] = "LoaderAvailable";
LoaderEventType[LoaderEventType["BeginLoadingScript"] = 10] = "BeginLoadingScript";
LoaderEventType[LoaderEventType["EndLoadingScriptOK"] = 11] = "EndLoadingScriptOK";
LoaderEventType[LoaderEventType["EndLoadingScriptError"] = 12] = "EndLoadingScriptError";
LoaderEventType[LoaderEventType["BeginInvokeFactory"] = 21] = "BeginInvokeFactory";
LoaderEventType[LoaderEventType["EndInvokeFactory"] = 22] = "EndInvokeFactory";
LoaderEventType[LoaderEventType["NodeBeginEvaluatingScript"] = 31] = "NodeBeginEvaluatingScript";
LoaderEventType[LoaderEventType["NodeEndEvaluatingScript"] = 32] = "NodeEndEvaluatingScript";
LoaderEventType[LoaderEventType["NodeBeginNativeRequire"] = 33] = "NodeBeginNativeRequire";
LoaderEventType[LoaderEventType["NodeEndNativeRequire"] = 34] = "NodeEndNativeRequire";
})(LoaderEventType = AMDLoader.LoaderEventType || (AMDLoader.LoaderEventType = {}));
var LoaderEvent = (function () {
function LoaderEvent(type, detail, timestamp) {
this.type = type;
this.detail = detail;
this.timestamp = timestamp;
}
return LoaderEvent;
}());
AMDLoader.LoaderEvent = LoaderEvent;
var LoaderEventRecorder = (function () {
function LoaderEventRecorder(loaderAvailableTimestamp) {
this._events = [new LoaderEvent(LoaderEventType.LoaderAvailable, '', loaderAvailableTimestamp)];
}
LoaderEventRecorder.prototype.record = function (type, detail) {
this._events.push(new LoaderEvent(type, detail, AMDLoader.Utilities.getHighPerformanceTimestamp()));
};
LoaderEventRecorder.prototype.getEvents = function () {
return this._events;
};
return LoaderEventRecorder;
}());
AMDLoader.LoaderEventRecorder = LoaderEventRecorder;
var NullLoaderEventRecorder = (function () {
function NullLoaderEventRecorder() {
}
NullLoaderEventRecorder.prototype.record = function (type, detail) {
// Nothing to do
};
NullLoaderEventRecorder.prototype.getEvents = function () {
return [];
};
return NullLoaderEventRecorder;
}());
NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder();
AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
var Utilities = (function () {
function Utilities() {
}
/**
* This method does not take care of / vs \
*/
Utilities.fileUriToFilePath = function (isWindows, uri) {
uri = decodeURI(uri);
if (isWindows) {
if (/^file:\/\/\//.test(uri)) {
// This is a URI without a hostname => return only the path segment
return uri.substr(8);
}
if (/^file:\/\//.test(uri)) {
return uri.substr(5);
}
}
else {
if (/^file:\/\//.test(uri)) {
return uri.substr(7);
}
}
// Not sure...
return uri;
};
Utilities.startsWith = function (haystack, needle) {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
};
Utilities.endsWith = function (haystack, needle) {
return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle;
};
// only check for "?" before "#" to ensure that there is a real Query-String
Utilities.containsQueryString = function (url) {
return /^[^\#]*\?/gi.test(url);
};
/**
* Does `url` start with http:// or https:// or file:// or / ?
*/
Utilities.isAbsolutePath = function (url) {
return /^((http:\/\/)|(https:\/\/)|(file:\/\/)|(\/))/.test(url);
};
Utilities.forEachProperty = function (obj, callback) {
if (obj) {
var key = void 0;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
callback(key, obj[key]);
}
}
}
};
Utilities.isEmpty = function (obj) {
var isEmpty = true;
Utilities.forEachProperty(obj, function () {
isEmpty = false;
});
return isEmpty;
};
Utilities.recursiveClone = function (obj) {
if (!obj || typeof obj !== 'object') {
return obj;
}
var result = Array.isArray(obj) ? [] : {};
Utilities.forEachProperty(obj, function (key, value) {
if (value && typeof value === 'object') {
result[key] = Utilities.recursiveClone(value);
}
else {
result[key] = value;
}
});
return result;
};
Utilities.generateAnonymousModule = function () {
return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '===';
};
Utilities.isAnonymousModule = function (id) {
return /^===anonymous/.test(id);
};
Utilities.getHighPerformanceTimestamp = function () {
if (!this.PERFORMANCE_NOW_PROBED) {
this.PERFORMANCE_NOW_PROBED = true;
this.HAS_PERFORMANCE_NOW = (AMDLoader.global.performance && typeof AMDLoader.global.performance.now === 'function');
}
return (this.HAS_PERFORMANCE_NOW ? AMDLoader.global.performance.now() : Date.now());
};
return Utilities;
}());
Utilities.NEXT_ANONYMOUS_ID = 1;
Utilities.PERFORMANCE_NOW_PROBED = false;
Utilities.HAS_PERFORMANCE_NOW = false;
AMDLoader.Utilities = Utilities;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
var ConfigurationOptionsUtil = (function () {
function ConfigurationOptionsUtil() {
}
/**
* Ensure configuration options make sense
*/
ConfigurationOptionsUtil.validateConfigurationOptions = function (isWebWorker, options) {
function defaultOnError(err) {
if (err.errorCode === 'load') {
console.error('Loading "' + err.moduleId + '" failed');
console.error('Detail: ', err.detail);
if (err.detail && err.detail.stack) {
console.error(err.detail.stack);
}
console.error('Here are the modules that depend on it:');
console.error(err.neededBy);
return;
}
if (err.errorCode === 'factory') {
console.error('The factory method of "' + err.moduleId + '" has thrown an exception');
console.error(err.detail);
if (err.detail && err.detail.stack) {
console.error(err.detail.stack);
}
return;
}
}
options = options || {};
if (typeof options.baseUrl !== 'string') {
options.baseUrl = '';
}
if (typeof options.isBuild !== 'boolean') {
options.isBuild = false;
}
if (typeof options.paths !== 'object') {
options.paths = {};
}
if (typeof options.config !== 'object') {
options.config = {};
}
if (typeof options.catchError === 'undefined') {
// Catch errors by default in web workers, do not catch errors by default in other contexts
options.catchError = isWebWorker;
}
if (typeof options.urlArgs !== 'string') {
options.urlArgs = '';
}
if (typeof options.onError !== 'function') {
options.onError = defaultOnError;
}
if (typeof options.ignoreDuplicateModules !== 'object' || !Array.isArray(options.ignoreDuplicateModules)) {
options.ignoreDuplicateModules = [];
}
if (options.baseUrl.length > 0) {
if (!AMDLoader.Utilities.endsWith(options.baseUrl, '/')) {
options.baseUrl += '/';
}
}
if (!Array.isArray(options.nodeModules)) {
options.nodeModules = [];
}
if (typeof options.nodeCachedDataWriteDelay !== 'number' || options.nodeCachedDataWriteDelay < 0) {
options.nodeCachedDataWriteDelay = 1000 * 7;
}
if (typeof options.onNodeCachedData !== 'function') {
options.onNodeCachedData = function (err, data) {
if (!err) {
// ignore
}
else if (err.errorCode === 'cachedDataRejected') {
console.warn('Rejected cached data from file: ' + err.path);
}
else if (err.errorCode === 'unlink' || err.errorCode === 'writeFile') {
console.error('Problems writing cached data file: ' + err.path);
console.error(err.detail);
}
else {
console.error(err);
}
};
}
return options;
};
ConfigurationOptionsUtil.mergeConfigurationOptions = function (isWebWorker, overwrite, base) {
if (overwrite === void 0) { overwrite = null; }
if (base === void 0) { base = null; }
var result = AMDLoader.Utilities.recursiveClone(base || {});
// Merge known properties and overwrite the unknown ones
AMDLoader.Utilities.forEachProperty(overwrite, function (key, value) {
if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') {
result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value);
}
else if (key === 'paths' && typeof result.paths !== 'undefined') {
AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.paths[key2] = value2; });
}
else if (key === 'config' && typeof result.config !== 'undefined') {
AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.config[key2] = value2; });
}
else {
result[key] = AMDLoader.Utilities.recursiveClone(value);
}
});
return ConfigurationOptionsUtil.validateConfigurationOptions(isWebWorker, result);
};
return ConfigurationOptionsUtil;
}());
AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil;
var Configuration = (function () {
function Configuration(env, options) {
this._env = env;
this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(this._env.isWebWorker, options);
this._createIgnoreDuplicateModulesMap();
this._createNodeModulesMap();
this._createSortedPathsRules();
if (this.options.baseUrl === '') {
if (this._env.isNode && this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename) {
var nodeMain = this.options.nodeRequire.main.filename;
var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
}
if (this._env.isNode && this.options.nodeMain) {
var nodeMain = this.options.nodeMain;
var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\'));
this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1);
}
}
}
Configuration.prototype._createIgnoreDuplicateModulesMap = function () {
// Build a map out of the ignoreDuplicateModules array
this.ignoreDuplicateModulesMap = {};
for (var i = 0; i < this.options.ignoreDuplicateModules.length; i++) {
this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true;
}
};
Configuration.prototype._createNodeModulesMap = function () {
// Build a map out of nodeModules array
this.nodeModulesMap = Object.create(null);
for (var _i = 0, _a = this.options.nodeModules; _i < _a.length; _i++) {
var nodeModule = _a[_i];
this.nodeModulesMap[nodeModule] = true;
}
};
Configuration.prototype._createSortedPathsRules = function () {
var _this = this;
// Create an array our of the paths rules, sorted descending by length to
// result in a more specific -> less specific order
this.sortedPathsRules = [];
AMDLoader.Utilities.forEachProperty(this.options.paths, function (from, to) {
if (!Array.isArray(to)) {
_this.sortedPathsRules.push({
from: from,
to: [to]
});
}
else {
_this.sortedPathsRules.push({
from: from,
to: to
});
}
});
this.sortedPathsRules.sort(function (a, b) {
return b.from.length - a.from.length;
});
};
/**
* Clone current configuration and overwrite options selectively.
* @param options The selective options to overwrite with.
* @result A new configuration
*/
Configuration.prototype.cloneAndMerge = function (options) {
return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(this._env.isWebWorker, options, this.options));
};
/**
* Get current options bag. Useful for passing it forward to plugins.
*/
Configuration.prototype.getOptionsLiteral = function () {
return this.options;
};
Configuration.prototype._applyPaths = function (moduleId) {
var pathRule;
for (var i = 0, len = this.sortedPathsRules.length; i < len; i++) {
pathRule = this.sortedPathsRules[i];
if (AMDLoader.Utilities.startsWith(moduleId, pathRule.from)) {
var result = [];
for (var j = 0, lenJ = pathRule.to.length; j < lenJ; j++) {
result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length));
}
return result;
}
}
return [moduleId];
};
Configuration.prototype._addUrlArgsToUrl = function (url) {
if (AMDLoader.Utilities.containsQueryString(url)) {
return url + '&' + this.options.urlArgs;
}
else {
return url + '?' + this.options.urlArgs;
}
};
Configuration.prototype._addUrlArgsIfNecessaryToUrl = function (url) {
if (this.options.urlArgs) {
return this._addUrlArgsToUrl(url);
}
return url;
};
Configuration.prototype._addUrlArgsIfNecessaryToUrls = function (urls) {
if (this.options.urlArgs) {
for (var i = 0, len = urls.length; i < len; i++) {
urls[i] = this._addUrlArgsToUrl(urls[i]);
}
}
return urls;
};
/**
* Transform a module id to a location. Appends .js to module ids
*/
Configuration.prototype.moduleIdToPaths = function (moduleId) {
if (this.nodeModulesMap[moduleId] === true) {
// This is a node module...
if (this.isBuild()) {
// ...and we are at build time, drop it
return ['empty:'];
}
else {
// ...and at runtime we create a `shortcut`-path
return ['node|' + moduleId];
}
}
var result = moduleId;
var results;
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.isAbsolutePath(result)) {
results = this._applyPaths(result);
for (var i = 0, len = results.length; i < len; i++) {
if (this.isBuild() && results[i] === 'empty:') {
continue;
}
if (!AMDLoader.Utilities.isAbsolutePath(results[i])) {
results[i] = this.options.baseUrl + results[i];
}
if (!AMDLoader.Utilities.endsWith(results[i], '.js') && !AMDLoader.Utilities.containsQueryString(results[i])) {
results[i] = results[i] + '.js';
}
}
}
else {
if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.containsQueryString(result)) {
result = result + '.js';
}
results = [result];
}
return this._addUrlArgsIfNecessaryToUrls(results);
};
/**
* Transform a module id or url to a location.
*/
Configuration.prototype.requireToUrl = function (url) {
var result = url;
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
result = this._applyPaths(result)[0];
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
result = this.options.baseUrl + result;
}
}
return this._addUrlArgsIfNecessaryToUrl(result);
};
/**
* Flag to indicate if current execution is as part of a build.
*/
Configuration.prototype.isBuild = function () {
return this.options.isBuild;
};
/**
* Test if module `moduleId` is expected to be defined multiple times
*/
Configuration.prototype.isDuplicateMessageIgnoredFor = function (moduleId) {
return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId);
};
/**
* Get the configuration settings for the provided module id
*/
Configuration.prototype.getConfigForModule = function (moduleId) {
if (this.options.config) {
return this.options.config[moduleId];
}
};
/**
* Should errors be caught when executing module factories?
*/
Configuration.prototype.shouldCatchError = function () {
return this.options.catchError;
};
/**
* Should statistics be recorded?
*/
Configuration.prototype.shouldRecordStats = function () {
return this.options.recordStats;
};
/**
* Forward an error to the error handler.
*/
Configuration.prototype.onError = function (err) {
this.options.onError(err);
};
return Configuration;
}());
AMDLoader.Configuration = Configuration;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
/**
* Load `scriptSrc` only once (avoid multiple <script> tags)
*/
var OnlyOnceScriptLoader = (function () {
function OnlyOnceScriptLoader(actualScriptLoader) {
this.actualScriptLoader = actualScriptLoader;
this.callbackMap = {};
}
OnlyOnceScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
var _this = this;
var scriptCallbacks = {
callback: callback,
errorback: errorback
};
if (this.callbackMap.hasOwnProperty(scriptSrc)) {
this.callbackMap[scriptSrc].push(scriptCallbacks);
return;
}
this.callbackMap[scriptSrc] = [scriptCallbacks];
this.actualScriptLoader.load(moduleManager, scriptSrc, function () { return _this.triggerCallback(scriptSrc); }, function (err) { return _this.triggerErrorback(scriptSrc, err); });
};
OnlyOnceScriptLoader.prototype.triggerCallback = function (scriptSrc) {
var scriptCallbacks = this.callbackMap[scriptSrc];
delete this.callbackMap[scriptSrc];
for (var i = 0; i < scriptCallbacks.length; i++) {
scriptCallbacks[i].callback();
}
};
OnlyOnceScriptLoader.prototype.triggerErrorback = function (scriptSrc, err) {
var scriptCallbacks = this.callbackMap[scriptSrc];
delete this.callbackMap[scriptSrc];
for (var i = 0; i < scriptCallbacks.length; i++) {
scriptCallbacks[i].errorback(err);
}
};
return OnlyOnceScriptLoader;
}());
var BrowserScriptLoader = (function () {
function BrowserScriptLoader() {
}
/**
* Attach load / error listeners to a script element and remove them when either one has fired.
* Implemented for browssers supporting HTML5 standard 'load' and 'error' events.
*/
BrowserScriptLoader.prototype.attachListeners = function (script, callback, errorback) {
var unbind = function () {
script.removeEventListener('load', loadEventListener);
script.removeEventListener('error', errorEventListener);
};
var loadEventListener = function (e) {
unbind();
callback();
};
var errorEventListener = function (e) {
unbind();
errorback(e);
};
script.addEventListener('load', loadEventListener);
script.addEventListener('error', errorEventListener);
};
BrowserScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
var script = document.createElement('script');
script.setAttribute('async', 'async');
script.setAttribute('type', 'text/javascript');
this.attachListeners(script, callback, errorback);
script.setAttribute('src', scriptSrc);
document.getElementsByTagName('head')[0].appendChild(script);
};
return BrowserScriptLoader;
}());
var WorkerScriptLoader = (function () {
function WorkerScriptLoader() {
}
WorkerScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
try {
importScripts(scriptSrc);
callback();
}
catch (e) {
errorback(e);
}
};
return WorkerScriptLoader;
}());
var NodeScriptLoader = (function () {
function NodeScriptLoader(env) {
this._env = env;
this._didInitialize = false;
this._didPatchNodeRequire = false;
}
NodeScriptLoader.prototype._init = function (nodeRequire) {
if (this._didInitialize) {
return;
}
this._didInitialize = true;
// capture node modules
this._fs = nodeRequire('fs');
this._vm = nodeRequire('vm');
this._path = nodeRequire('path');
this._crypto = nodeRequire('crypto');
// js-flags have an impact on cached data
this._jsflags = '';
for (var _i = 0, _a = process.argv; _i < _a.length; _i++) {
var arg = _a[_i];
if (arg.indexOf('--js-flags=') === 0) {
this._jsflags = arg;
break;
}
}
};
// patch require-function of nodejs such that we can manually create a script
// from cached data. this is done by overriding the `Module._compile` function
NodeScriptLoader.prototype._initNodeRequire = function (nodeRequire, moduleManager) {
var nodeCachedDataDir = moduleManager.getConfig().getOptionsLiteral().nodeCachedDataDir;
if (!nodeCachedDataDir || this._didPatchNodeRequire) {
return;
}
this._didPatchNodeRequire = true;
var that = this;
var Module = nodeRequire('module');
function makeRequireFunction(mod) {
var Module = mod.constructor;
var require = function require(path) {
try {
return mod.require(path);
}
finally {
// nothing
}
};
require.resolve = function resolve(request) {
return Module._resolveFilename(request, mod);
};
require.main = process.mainModule;
require.extensions = Module._extensions;
require.cache = Module._cache;
return require;
}
Module.prototype._compile = function (content, filename) {
// remove shebang
content = content.replace(/^#!.*/, '');
// create wrapper function
var wrapper = Module.wrap(content);
var cachedDataPath = that._getCachedDataPath(nodeCachedDataDir, filename);
var options = { filename: filename };
try {
options.cachedData = that._fs.readFileSync(cachedDataPath);
}
catch (e) {
options.produceCachedData = true;
}
var script = new that._vm.Script(wrapper, options);
var compileWrapper = script.runInThisContext(options);
var dirname = that._path.dirname(filename);
var require = makeRequireFunction(this);
var args = [this.exports, require, this, filename, dirname, process, AMDLoader.global, Buffer];
var result = compileWrapper.apply(this.exports, args);
that._processCachedData(moduleManager, script, cachedDataPath);
return result;
};
};
NodeScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) {
var _this = this;
var opts = moduleManager.getConfig().getOptionsLiteral();
var nodeRequire = (opts.nodeRequire || AMDLoader.global.nodeRequire);
var nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; });
this._init(nodeRequire);
this._initNodeRequire(nodeRequire, moduleManager);
var recorder = moduleManager.getRecorder();
if (/^node\|/.test(scriptSrc)) {
var pieces = scriptSrc.split('|');
var moduleExports_1 = null;
try {
moduleExports_1 = nodeRequire(pieces[1]);
}
catch (err) {
errorback(err);
return;
}
moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_1; });
callback();
}
else {
scriptSrc = AMDLoader.Utilities.fileUriToFilePath(this._env.isWindows, scriptSrc);
this._fs.readFile(scriptSrc, { encoding: 'utf8' }, function (err, data) {
if (err) {
errorback(err);
return;
}
var normalizedScriptSrc = _this._path.normalize(scriptSrc);
var vmScriptSrc = normalizedScriptSrc;
// Make the script src friendly towards electron
if (_this._env.isElectronRenderer) {
var driveLetterMatch = vmScriptSrc.match(/^([a-z])\:(.*)/i);
if (driveLetterMatch) {
// windows
vmScriptSrc = "file:///" + (driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2]).replace(/\\/g, '/');
}
else {
// nix
vmScriptSrc = "file://" + vmScriptSrc;
}
}
var contents, prefix = '(function (require, define, __filename, __dirname) { ', suffix = '\n});';
if (data.charCodeAt(0) === NodeScriptLoader._BOM) {
contents = prefix + data.substring(1) + suffix;
}
else {
contents = prefix + data + suffix;
}
contents = nodeInstrumenter(contents, normalizedScriptSrc);
if (!opts.nodeCachedDataDir) {
_this._loadAndEvalScript(moduleManager, scriptSrc, vmScriptSrc, contents, { filename: vmScriptSrc }, recorder);
callback();
}
else {
var cachedDataPath_1 = _this._getCachedDataPath(opts.nodeCachedDataDir, scriptSrc);
_this._fs.readFile(cachedDataPath_1, function (err, cachedData) {
// create script options
var options = {
filename: vmScriptSrc,
produceCachedData: typeof cachedData === 'undefined',
cachedData: cachedData
};
var script = _this._loadAndEvalScript(moduleManager, scriptSrc, vmScriptSrc, contents, options, recorder);
callback();
_this._processCachedData(moduleManager, script, cachedDataPath_1);
});
}
});
}
};
NodeScriptLoader.prototype._loadAndEvalScript = function (moduleManager, scriptSrc, vmScriptSrc, contents, options, recorder) {
// create script, run script
recorder.record(AMDLoader.LoaderEventType.NodeBeginEvaluatingScript, scriptSrc);
var script = new this._vm.Script(contents, options);
var r = script.runInThisContext(options);
r.call(AMDLoader.global, moduleManager.getGlobalAMDRequireFunc(), moduleManager.getGlobalAMDDefineFunc(), vmScriptSrc, this._path.dirname(scriptSrc));
// signal done
recorder.record(AMDLoader.LoaderEventType.NodeEndEvaluatingScript, scriptSrc);
return script;
};
NodeScriptLoader.prototype._getCachedDataPath = function (basedir, filename) {
var hash = this._crypto.createHash('md5').update(filename, 'utf8').update(this._jsflags, 'utf8').digest('hex');
var basename = this._path.basename(filename).replace(/\.js$/, '');
return this._path.join(basedir, basename + "-" + hash + ".code");
};
NodeScriptLoader.prototype._processCachedData = function (moduleManager, script, cachedDataPath) {
var _this = this;
if (script.cachedDataRejected) {
// data rejected => delete cache file
moduleManager.getConfig().getOptionsLiteral().onNodeCachedData({
errorCode: 'cachedDataRejected',
path: cachedDataPath
});
NodeScriptLoader._runSoon(function () { return _this._fs.unlink(cachedDataPath, function (err) {
if (err) {
moduleManager.getConfig().getOptionsLiteral().onNodeCachedData({
errorCode: 'unlink',
path: cachedDataPath,
detail: err
});
}
}); }, moduleManager.getConfig().getOptionsLiteral().nodeCachedDataWriteDelay);
}
else if (script.cachedDataProduced) {
// data produced => tell outside world
moduleManager.getConfig().getOptionsLiteral().onNodeCachedData(undefined, {
path: cachedDataPath,
length: script.cachedData.length
});
// data produced => write cache file
NodeScriptLoader._runSoon(function () { return _this._fs.writeFile(cachedDataPath, script.cachedData, function (err) {
if (err) {
moduleManager.getConfig().getOptionsLiteral().onNodeCachedData({
errorCode: 'writeFile',
path: cachedDataPath,
detail: err
});
}
}); }, moduleManager.getConfig().getOptionsLiteral().nodeCachedDataWriteDelay);
}
};
NodeScriptLoader._runSoon = function (callback, minTimeout) {
var timeout = minTimeout + Math.ceil(Math.random() * minTimeout);
setTimeout(callback, timeout);
};
return NodeScriptLoader;
}());
NodeScriptLoader._BOM = 0xFEFF;
function createScriptLoader(env) {
return new OnlyOnceScriptLoader(env.isWebWorker ?
new WorkerScriptLoader()
: env.isNode ?
new NodeScriptLoader(env)
: new BrowserScriptLoader());
}
AMDLoader.createScriptLoader = createScriptLoader;
})(AMDLoader || (AMDLoader = {}));
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var AMDLoader;
(function (AMDLoader) {
// ------------------------------------------------------------------------
// ModuleIdResolver
var ModuleIdResolver = (function () {
function ModuleIdResolver(fromModuleId) {
var lastSlash = fromModuleId.lastIndexOf('/');
if (lastSlash !== -1) {
this.fromModulePath = fromModuleId.substr(0, lastSlash + 1);
}
else {
this.fromModulePath = '';
}
}
/**
* Normalize 'a/../name' to 'name', etc.
*/
ModuleIdResolver._normalizeModuleId = function (moduleId) {
var r = moduleId, pattern;
// replace /./ => /
pattern = /\/\.\//;
while (pattern.test(r)) {
r = r.replace(pattern, '/');
}
// replace ^./ => nothing
r = r.replace(/^\.\//g, '');
// replace /aa/../ => / (BUT IGNORE /../../)
pattern = /\/(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//;
while (pattern.test(r)) {
r = r.replace(pattern, '/');
}
// replace ^aa/../ => nothing (BUT IGNORE ../../)
r = r.replace(/^(([^\/])|([^\/][^\/\.])|([^\/\.][^\/])|([^\/][^\/][^\/]+))\/\.\.\//, '');
return r;
};
/**
* Resolve relative module ids
*/
ModuleIdResolver.prototype.resolveModule = function (moduleId) {
var result = moduleId;
if (!AMDLoader.Utilities.isAbsolutePath(result)) {
if (AMDLoader.Utilities.startsWith(result, './') || AMDLoader.Utilities.startsWith(result, '../')) {
result = ModuleIdResolver._normalizeModuleId(this.fromModulePath + result);
}
}
return result;
};
return ModuleIdResolver;
}());
ModuleIdResolver.ROOT = new ModuleIdResolver('');
AMDLoader.ModuleIdResolver = ModuleIdResolver;
// ------------------------------------------------------------------------
// Module
var Module = (function () {
function Module(id, strId, dependencies, callback, errorback, moduleIdResolver) {
this.id = id;
this.strId = strId;
this.dependencies = dependencies;
this._callback = callback;
this._errorback = errorback;
this.moduleIdResolver = moduleIdResolver;
this.exports = {};
this.exportsPassedIn = false;
this.unresolvedDependenciesCount = this.dependencies.length;
this._isComplete = false;
}
Module._safeInvokeFunction = function (callback, args) {
try {
return {
returnedValue: callback.apply(AMDLoader.global, args),
producedError: null
};
}
catch (e) {
return {
returnedValue: null,
producedError: e
};
}
};
Module._invokeFactory = function (config, strModuleId, callback, dependenciesValues) {
if (config.isBuild() && !AMDLoader.Utilities.isAnonymousModule(strModuleId)) {
return {
returnedValue: null,
producedError: null
};
}
if (config.shouldCatchError()) {
return this._safeInvokeFunction(callback, dependenciesValues);
}
return {
returnedValue: callback.apply(AMDLoader.global, dependenciesValues),
producedError: null
};
};
Module.prototype.complete = function (recorder, config, dependenciesValues) {
this._isComplete = true;
var producedError = null;
if (this._callback) {
if (typeof this._callback === 'function') {
recorder.record(AMDLoader.LoaderEventType.BeginInvokeFactory, this.strId);
var r = Module._invokeFactory(config, this.strId, this._callback, dependenciesValues);
producedError = r.producedError;
recorder.record(AMDLoader.LoaderEventType.EndInvokeFactory, this.strId);
if (!producedError && typeof r.returnedValue !== 'undefined' && (!this.exportsPassedIn || AMDLoader.Utilities.isEmpty(this.exports))) {
this.exports = r.returnedValue;
}
}
else {
this.exports = this._callback;
}
}
if (producedError) {
config.onError({
errorCode: 'factory',
moduleId: this.strId,
detail: producedError
});
}
this.dependencies = null;
this._callback = null;
this._errorback = null;
this.moduleIdResolver = null;
};
/**
* One of the direct dependencies or a transitive dependency has failed to load.
*/
Module.prototype.onDependencyError = function (err) {
if (this._errorback) {
this._errorback(err);
return true;
}
return false;
};
/**
* Is the current module complete?
*/
Module.prototype.isComplete = function () {
return this._isComplete;
};
return Module;
}());
AMDLoader.Module = Module;
var ModuleIdProvider = (function () {
function ModuleIdProvider() {
this._nextId = 0;
this._strModuleIdToIntModuleId = new Map();
this._intModuleIdToStrModuleId = [];
// Ensure values 0, 1, 2 are assigned accordingly with ModuleId
this.getModuleId('exports');
this.getModuleId('module');
this.getModuleId('require');
}
ModuleIdProvider.prototype.getMaxModuleId = function () {
return this._nextId;
};
ModuleIdProvider.prototype.getModuleId = function (strModuleId) {
var id = this._strModuleIdToIntModuleId.get(strModuleId);
if (typeof id === 'undefined') {
id = this._nextId++;
this._strModuleIdToIntModuleId.set(strModuleId, id);
this._intModuleIdToStrModuleId[id] = strModuleId;
}
return id;
};
ModuleIdProvider.prototype.getStrModuleId = function (moduleId) {
return this._intModuleIdToStrModuleId[moduleId];
};
return ModuleIdProvider;
}());
var RegularDependency = (function () {
function RegularDependency(id) {
this.id = id;
}
return RegularDependency;
}());
RegularDependency.EXPORTS = new RegularDependency(0 /* EXPORTS */);
RegularDependency.MODULE = new RegularDependency(1 /* MODULE */);
RegularDependency.REQUIRE = new RegularDependency(2 /* REQUIRE */);
AMDLoader.RegularDependency = RegularDependency;
var PluginDependency = (function () {
function PluginDependency(id, pluginId, pluginParam) {
this.id = id;
this.pluginId = pluginId;
this.pluginParam = pluginParam;
}
return PluginDependency;
}());
AMDLoader.PluginDependency = PluginDependency;
var ModuleManager = (function () {
function ModuleManager(env, scriptLoader, defineFunc, requireFunc, loaderAvailableTimestamp) {
if (loaderAvailableTimestamp === void 0) { loaderAvailableTimestamp = 0; }
this._env = env;
this._scriptLoader = scriptLoader;
this._loaderAvailableTimestamp = loaderAvailableTimestamp;
this._defineFunc = defineFunc;
this._requireFunc = requireFunc;
this._moduleIdProvider = new ModuleIdProvider();
this._config = new AMDLoader.Configuration(this._env);
this._modules2 = [];
this._knownModules2 = [];
this._inverseDependencies2 = [];
this._inversePluginDependencies2 = new Map();
this._currentAnnonymousDefineCall = null;
this._recorder = null;
this._buildInfoPath = [];
this._buildInfoDefineStack = [];
this._buildInfoDependencies = [];
}
ModuleManager.prototype.reset = function () {
return new ModuleManager(this._env, this._scriptLoader, this._defineFunc, this._requireFunc, this._loaderAvailableTimestamp);
};
ModuleManager.prototype.getGlobalAMDDefineFunc = function () {
return this._defineFunc;
};
ModuleManager.prototype.getGlobalAMDRequireFunc = function () {
return this._requireFunc;
};
ModuleManager._findRelevantLocationInStack = function (needle, stack) {
var normalize = function (str) { return str.replace(/\\/g, '/'); };
var normalizedPath = normalize(needle);
var stackPieces = stack.split(/\n/);
for (var i = 0; i < stackPieces.length; i++) {
var m = stackPieces[i].match(/(.*):(\d+):(\d+)\)?$/);
if (m) {
var stackPath = m[1];
var stackLine = m[2];
var stackColumn = m[3];
var trimPathOffset = Math.max(stackPath.lastIndexOf(' ') + 1, stackPath.lastIndexOf('(') + 1);
stackPath = stackPath.substr(trimPathOffset);
stackPath = normalize(stackPath);
if (stackPath === normalizedPath) {
var r = {
line: parseInt(stackLine, 10),
col: parseInt(stackColumn, 10)
};
if (r.line === 1